forked from NVIDIA/cuda-quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCCOps.cpp
More file actions
2355 lines (2158 loc) · 90.5 KB
/
CCOps.cpp
File metadata and controls
2355 lines (2158 loc) · 90.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2022 - 2025 NVIDIA Corporation & Affiliates. *
* All rights reserved. *
* *
* This source code and the accompanying materials are made available under *
* the terms of the Apache License 2.0 which accompanies this distribution. *
******************************************************************************/
#include "cudaq/Optimizer/Dialect/CC/CCOps.h"
#include "cudaq/Optimizer/Builder/Factory.h"
#include "cudaq/Optimizer/Dialect/CC/CCDialect.h"
#include "cudaq/Optimizer/Dialect/Quake/QuakeOps.h"
#include "llvm/ADT/TypeSwitch.h"
#include "mlir/Dialect/Complex/IR/Complex.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/Utils/IndexingUtils.h"
#include "mlir/Dialect/Utils/StructuredOpsUtils.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/TypeUtilities.h"
using namespace mlir;
template <typename R>
R getParentOfType(Operation *op) {
do {
op = op->getParentOp();
if (auto r = dyn_cast_or_null<R>(op))
return r;
} while (op);
return {};
}
std::optional<std::int64_t> cudaq::opt::factory::getIntIfConstant(Value value) {
APInt constant;
if (matchPattern(value, m_ConstantInt(&constant)))
return {constant.getSExtValue()};
return {};
}
std::optional<APFloat> cudaq::opt::factory::getDoubleIfConstant(Value value) {
APFloat constant{0.0};
if (matchPattern(value, m_ConstantFloat(&constant)))
return {constant};
return {};
}
Value cudaq::cc::getByteSizeOfType(OpBuilder &builder, Location loc, Type ty,
bool useSizeOf) {
auto createInt = [&](std::int32_t byteWidth) -> Value {
return builder.create<arith::ConstantIntOp>(loc, byteWidth, 64);
};
// Handle primitive types with constant sizes.
auto primSize = [](auto ty) -> unsigned {
return (ty.getIntOrFloatBitWidth() + 7) / 8;
};
auto rawSize =
TypeSwitch<Type, std::optional<std::int32_t>>(ty)
.Case([&](IntegerType intTy) -> std::optional<std::int32_t> {
return {primSize(intTy)};
})
.Case([&](FloatType fltTy) -> std::optional<std::int32_t> {
return {primSize(fltTy)};
})
.Case([&](ComplexType complexTy) -> std::optional<std::int32_t> {
auto eleTy = complexTy.getElementType();
if (isa<IntegerType, FloatType>(eleTy))
return {2 * primSize(eleTy)};
return {};
})
.Case(
[](cudaq::cc::PointerType ptrTy) -> std::optional<std::int32_t> {
// TODO: get this from the target specification. For now
// we're assuming pointers are 64 bits.
return {8};
})
.Default({});
if (rawSize)
return createInt(*rawSize);
// Handle aggregate types.
return TypeSwitch<Type, Value>(ty)
.Case([&](cudaq::cc::StructType strTy) -> Value {
if (std::size_t bitWidth = strTy.getBitSize()) {
assert(bitWidth % 8 == 0 && "struct ought to be in bytes");
std::size_t byteWidth = bitWidth / 8;
return createInt(byteWidth);
}
if (useSizeOf)
return builder.create<cudaq::cc::SizeOfOp>(loc, builder.getI64Type(),
strTy);
return {};
})
.Case([&](cudaq::cc::ArrayType arrTy) -> Value {
if (arrTy.isUnknownSize())
return {};
auto v =
getByteSizeOfType(builder, loc, arrTy.getElementType(), useSizeOf);
if (!v)
return {};
auto scale = createInt(arrTy.getSize());
return builder.create<arith::MulIOp>(loc, builder.getI64Type(), v,
scale);
})
.Case([&](cudaq::cc::SpanLikeType) -> Value {
// Uniformly on the device size: {ptr, i64}
return createInt(16);
})
.Default({});
}
//===----------------------------------------------------------------------===//
// AddressOfOp
//===----------------------------------------------------------------------===//
LogicalResult
cudaq::cc::AddressOfOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
Operation *op = symbolTable.lookupSymbolIn(
getParentOfType<ModuleOp>(getOperation()), getGlobalNameAttr());
if (!isa_and_nonnull<func::FuncOp, GlobalOp, LLVM::GlobalOp>(op))
return emitOpError("must reference a global");
return success();
}
//===----------------------------------------------------------------------===//
// AllocaOp
//===----------------------------------------------------------------------===//
void cudaq::cc::AllocaOp::print(OpAsmPrinter &p) {
p << ' ' << getElementType();
if (auto size = getSeqSize())
p << '[' << size << " : " << size.getType() << ']';
}
ParseResult cudaq::cc::AllocaOp::parse(OpAsmParser &parser,
OperationState &result) {
Type eleTy;
if (parser.parseType(eleTy))
return failure();
result.addAttribute("elementType", TypeAttr::get(eleTy));
Type resTy;
if (succeeded(parser.parseOptionalLSquare())) {
OpAsmParser::UnresolvedOperand operand;
Type operTy;
if (parser.parseOperand(operand) || parser.parseColonType(operTy) ||
parser.parseRSquare() ||
parser.resolveOperand(operand, operTy, result.operands))
return failure();
resTy = cc::PointerType::get(cc::ArrayType::get(eleTy));
} else {
resTy = cc::PointerType::get(eleTy);
}
if (!resTy || parser.parseOptionalAttrDict(result.attributes) ||
parser.addTypeToList(resTy, result.types))
return failure();
return success();
}
namespace {
struct FuseAllocLength : public OpRewritePattern<cudaq::cc::AllocaOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(cudaq::cc::AllocaOp alloca,
PatternRewriter &rewriter) const override {
auto params = alloca.getOperands();
if (params.size() == 1) {
// If allocating a contiguous block of elements and the size of the block
// is a constant, fold the size into the cc.array type and allocate a
// constant sized block.
if (auto size = cudaq::opt::factory::getIntIfConstant(params[0]))
if (*size > 0) {
auto loc = alloca.getLoc();
auto *context = rewriter.getContext();
Type oldTy = alloca.getElementType();
auto arrTy = cudaq::cc::ArrayType::get(context, oldTy, *size);
Type origTy = alloca.getType();
auto newAlloc = rewriter.create<cudaq::cc::AllocaOp>(loc, arrTy);
rewriter.replaceOpWithNewOp<cudaq::cc::CastOp>(alloca, origTy,
newAlloc);
return success();
}
}
return failure();
}
};
} // namespace
void cudaq::cc::AllocaOp::getCanonicalizationPatterns(
RewritePatternSet &patterns, MLIRContext *context) {
patterns.add<FuseAllocLength>(context);
}
//===----------------------------------------------------------------------===//
// CastOp
//===----------------------------------------------------------------------===//
OpFoldResult cudaq::cc::CastOp::fold(FoldAdaptor adaptor) {
// If cast is a nop, just forward the argument to the uses.
if (getType() == getValue().getType())
return getValue();
if (auto optConst = adaptor.getValue()) {
// Replace a constant + cast with a new constant of an updated type.
auto ty = getType();
OpBuilder builder(*this);
auto fltTy = builder.getF32Type();
auto dblTy = builder.getF64Type();
auto loc = getLoc();
if (auto attr = dyn_cast<IntegerAttr>(optConst)) {
auto val = attr.getInt();
if (isa<IntegerType>(ty)) {
auto width = ty.getIntOrFloatBitWidth();
return builder.create<arith::ConstantIntOp>(loc, val, width)
.getResult();
} else if (ty == fltTy) {
if (getZint()) {
APFloat fval(static_cast<float>(static_cast<std::uint64_t>(val)));
return builder.create<arith::ConstantFloatOp>(loc, fval, fltTy)
.getResult();
}
if (getSint()) {
APFloat fval(static_cast<float>(val));
return builder.create<arith::ConstantFloatOp>(loc, fval, fltTy)
.getResult();
}
} else if (ty == dblTy) {
if (getZint()) {
APFloat fval(static_cast<double>(static_cast<std::uint64_t>(val)));
return builder.create<arith::ConstantFloatOp>(loc, fval, dblTy)
.getResult();
}
if (getSint()) {
APFloat fval(static_cast<double>(val));
return builder.create<arith::ConstantFloatOp>(loc, fval, dblTy)
.getResult();
}
}
}
if (auto attr = dyn_cast<FloatAttr>(optConst)) {
auto val = attr.getValue();
if (isa<IntegerType>(ty)) {
auto width = ty.getIntOrFloatBitWidth();
if (getZint()) {
std::uint64_t v = val.convertToDouble();
return builder.create<arith::ConstantIntOp>(loc, v, width)
.getResult();
}
if (getSint()) {
std::int64_t v = val.convertToDouble();
return builder.create<arith::ConstantIntOp>(loc, v, width)
.getResult();
}
} else if (ty == fltTy) {
float f = val.convertToDouble();
APFloat fval(f);
return builder.create<arith::ConstantFloatOp>(loc, fval, fltTy)
.getResult();
} else if (ty == dblTy) {
APFloat fval{val.convertToDouble()};
return builder.create<arith::ConstantFloatOp>(loc, fval, dblTy)
.getResult();
}
}
// %5 = complex.constant ... -> complex<T>
// %6 = cc.cast %5 : (complex<T>) -> complex<U>
// ────────────────────────────────────────────
// %6 = complex.constant ... -> complex<U>
if (auto attr = dyn_cast<ArrayAttr>(optConst)) {
auto eleTy = cast<ComplexType>(ty).getElementType();
auto reFp = dyn_cast<FloatAttr>(attr[0]);
auto imFp = dyn_cast<FloatAttr>(attr[1]);
if (reFp && imFp) {
if (eleTy == fltTy) {
float reVal = reFp.getValue().convertToDouble();
float imVal = imFp.getValue().convertToDouble();
auto rePart = builder.getFloatAttr(eleTy, APFloat{reVal});
auto imPart = builder.getFloatAttr(eleTy, APFloat{imVal});
auto cv = builder.getArrayAttr({rePart, imPart});
return builder.create<complex::ConstantOp>(loc, ty, cv).getResult();
} else if (eleTy == dblTy) {
double reVal = reFp.getValue().convertToDouble();
double imVal = imFp.getValue().convertToDouble();
auto rePart = builder.getFloatAttr(eleTy, APFloat{reVal});
auto imPart = builder.getFloatAttr(eleTy, APFloat{imVal});
auto cv = builder.getArrayAttr({rePart, imPart});
return builder.create<complex::ConstantOp>(loc, ty, cv).getResult();
}
}
}
}
return nullptr;
}
LogicalResult cudaq::cc::CastOp::verify() {
auto inTy = getValue().getType();
auto outTy = getType();
// Make sure sint/zint are properly used.
if (getSint() || getZint()) {
if (getSint() && getZint())
return emitOpError("cannot be both signed and unsigned.");
if ((isa<IntegerType>(inTy) && isa<IntegerType>(outTy)) ||
(isa<FloatType>(inTy) && isa<IntegerType>(outTy)) ||
(isa<IntegerType>(inTy) && isa<FloatType>(outTy))) {
// ok, do nothing.
} else {
return emitOpError("signed (unsigned) may only be applied to integer to "
"integer or integer to/from float.");
}
}
// Make sure this cast can be translated to one of LLVM's instructions.
if (isa<IntegerType>(inTy) || isa<IntegerType>(outTy)) {
// Check casts to and from integer types.
if (isa<IntegerType>(inTy) && isa<IntegerType>(outTy)) {
// trunc, sext, zext, nop
auto iTy1 = cast<IntegerType>(inTy);
auto iTy2 = cast<IntegerType>(outTy);
if ((iTy1.getWidth() < iTy2.getWidth()) && !getSint() && !getZint())
return emitOpError("integer extension must be signed or unsigned.");
} else if (isa<IntegerType>(inTy) && isa<cc::IndirectCallableType>(outTy)) {
// ok: nop
// the indirect callable value is an integer key on the device side.
} else if (isa<IntegerType>(inTy) && isa<cc::PointerType>(outTy)) {
// ok: inttoptr
} else if (isa<cc::PointerType>(inTy) && isa<IntegerType>(outTy)) {
// ok: ptrtoint
} else if (isa<IntegerType>(inTy) && isa<FloatType>(outTy)) {
if (!getSint() && !getZint()) {
// bitcast
auto iTy1 = cast<IntegerType>(inTy);
auto fTy2 = cast<FloatType>(outTy);
if (iTy1.getWidth() != fTy2.getWidth())
return emitOpError("bitcast must be same number of bits.");
} else {
// ok: sitofp, uitofp
}
} else if (isa<FloatType>(inTy) && isa<IntegerType>(outTy)) {
if (!getSint() && !getZint()) {
// bitcast
auto iTy1 = cast<IntegerType>(outTy);
auto fTy2 = cast<FloatType>(inTy);
if (iTy1.getWidth() != fTy2.getWidth())
return emitOpError("bitcast must be same number of bits.");
} else {
// ok: fptosi, fptoui
}
} else {
return emitOpError("invalid integer cast.");
}
} else if (isa<FloatType>(inTy) && isa<FloatType>(outTy)) {
// ok, floating-point casts: fptrunc, fpext, nop
} else if (isa<cc::PointerType, LLVM::LLVMPointerType>(inTy) &&
isa<cc::PointerType, LLVM::LLVMPointerType>(outTy)) {
// ok, pointer casts: bitcast, nop
} else if (isa<ComplexType>(inTy) && isa<ComplexType>(outTy)) {
// ok, type conversion of a complex value
// NB: use complex.re or complex.im to convert (extract) a fp value.
} else if (isa<FunctionType>(inTy) && isa<cc::IndirectCallableType>(outTy)) {
// ok, type conversion of a function to an indirect callable
// Folding will remove this.
} else {
// Could support a bitcast of a float with pointer size bits to/from a
// pointer, but that doesn't seem like it would be very common.
return emitOpError("invalid cast.");
}
return success();
}
namespace {
// There are a number of series of casts that can be fused. For now, fuse
// pointer cast chains.
struct FuseCastCascade : public OpRewritePattern<cudaq::cc::CastOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(cudaq::cc::CastOp castOp,
PatternRewriter &rewriter) const override {
if (auto castToCast = castOp.getValue().getDefiningOp<cudaq::cc::CastOp>())
if (isa<cudaq::cc::PointerType>(castOp.getType()) &&
isa<cudaq::cc::PointerType>(castToCast.getType())) {
// %4 = cc.cast %3 : (!cc.ptr<T>) -> !cc.ptr<U>
// %5 = cc.cast %4 : (!cc.ptr<U>) -> !cc.ptr<V>
// ────────────────────────────────────────────
// %5 = cc.cast %3 : (!cc.ptr<T>) -> !cc.ptr<V>
rewriter.replaceOpWithNewOp<cudaq::cc::CastOp>(castOp, castOp.getType(),
castToCast.getValue());
return success();
}
return failure();
}
};
// Ad hoc pattern to erase casts used by arith.cmpi.
struct SimplifyIntegerCompare : public OpRewritePattern<arith::CmpIOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(arith::CmpIOp compare,
PatternRewriter &rewriter) const override {
auto lhsCast = compare.getLhs().getDefiningOp<cudaq::cc::CastOp>();
auto rhsCast = compare.getRhs().getDefiningOp<cudaq::cc::CastOp>();
// %4 = cc.cast %2 ...
// %5 = cc.cast %3 ...
// %6 = arith.cmpi %4, %5 ...
// and
// type(%2) == type(%3)
// and
// %4 and %5 are compatible casts
// ──────────────────────────────
// %5 = arith.cmpi %2, %3 ...
if (lhsCast && rhsCast) {
auto lhsVal = lhsCast.getValue();
auto rhsVal = rhsCast.getValue();
if (lhsVal.getType() == rhsVal.getType() &&
lhsCast.getSint() == rhsCast.getSint() &&
lhsCast.getZint() == rhsCast.getZint()) {
rewriter.replaceOpWithNewOp<arith::CmpIOp>(
compare, compare.getType(), compare.getPredicate(), lhsVal, rhsVal);
return success();
}
}
return failure();
}
};
// Ad hoc pattern to erase complex.create. (MLIR doesn't do this.)
struct FuseComplexCreate : public OpRewritePattern<complex::CreateOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(complex::CreateOp create,
PatternRewriter &rewriter) const override {
auto reVal = cudaq::opt::factory::getDoubleIfConstant(create.getReal());
auto imVal =
cudaq::opt::factory::getDoubleIfConstant(create.getImaginary());
if (reVal && imVal) {
auto eleTy = cast<ComplexType>(create.getType()).getElementType();
auto rePart = rewriter.getFloatAttr(eleTy, *reVal);
auto imPart = rewriter.getFloatAttr(eleTy, *imVal);
auto arrAttr = rewriter.getArrayAttr({rePart, imPart});
rewriter.replaceOpWithNewOp<complex::ConstantOp>(
create, ComplexType::get(eleTy), arrAttr);
return success();
}
return failure();
}
};
} // namespace
void cudaq::cc::CastOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
MLIRContext *context) {
patterns.add<FuseCastCascade, SimplifyIntegerCompare, FuseComplexCreate>(
context);
}
//===----------------------------------------------------------------------===//
// Support for operations with interleaved indices.
//===----------------------------------------------------------------------===//
template <typename A>
ParseResult parseInterleavedIndices(
OpAsmParser &parser,
SmallVectorImpl<OpAsmParser::UnresolvedOperand> &indices,
DenseI32ArrayAttr &rawConstantIndices) {
SmallVector<std::int32_t> constantIndices;
auto idxParser = [&]() -> ParseResult {
std::int32_t constantIndex;
OptionalParseResult parsedInteger =
parser.parseOptionalInteger(constantIndex);
if (parsedInteger.has_value()) {
if (failed(parsedInteger.value()))
return failure();
constantIndices.push_back(constantIndex);
return success();
}
constantIndices.push_back(A::kDynamicIndex);
return parser.parseOperand(indices.emplace_back());
};
if (parser.parseCommaSeparatedList(idxParser))
return failure();
rawConstantIndices =
DenseI32ArrayAttr::get(parser.getContext(), constantIndices);
return success();
}
template <typename Adaptor, typename B>
void printInterleavedIndices(OpAsmPrinter &printer, B computePtrOp,
OperandRange indices,
DenseI32ArrayAttr rawConstantIndices) {
llvm::interleaveComma(Adaptor{rawConstantIndices, indices}, printer,
[&](PointerUnion<IntegerAttr, Value> cst) {
if (Value val = cst.dyn_cast<Value>())
printer.printOperand(val);
else
printer << cst.get<IntegerAttr>().getInt();
});
}
//===----------------------------------------------------------------------===//
// ComputePtrOp
//===----------------------------------------------------------------------===//
LogicalResult cudaq::cc::ComputePtrOp::verify() {
auto basePtrTy = cast<cc::PointerType>(getBase().getType());
Type eleTy = basePtrTy.getElementType();
auto resultTy = cast<cc::PointerType>(getResult().getType());
for (std::int32_t i : getRawConstantIndices()) {
if (auto arrTy = dyn_cast<cc::ArrayType>(eleTy)) {
if (i != kDynamicIndex && !arrTy.isUnknownSize() &&
(i < 0 || i > arrTy.getSize())) {
// Note: allow indexing of last element + 1 so we can compute a
// pointer to `end()` of a stdvec buffer. Consider adding a flag
// to cc.compute_ptr explicitly for this or using casts.
return emitOpError("array cannot index out of bounds elements");
}
eleTy = arrTy.getElementType();
} else if (auto strTy = dyn_cast<cc::StructType>(eleTy)) {
if (i == kDynamicIndex)
return emitOpError("struct cannot have non-constant index");
if (i < 0 || static_cast<std::size_t>(i) >= strTy.getMembers().size())
return emitOpError("struct cannot index out of bounds members");
eleTy = strTy.getMember(i);
} else if (auto complexTy = dyn_cast<ComplexType>(eleTy)) {
if (!(i == 0 || i == 1 || i == kDynamicIndex))
return emitOpError("complex index is out of bounds");
eleTy = complexTy.getElementType();
} else {
return emitOpError("too many indices (" +
std::to_string(getRawConstantIndices().size()) +
") for the source pointer");
}
}
if (eleTy != resultTy.getElementType())
return emitOpError("result type does not match input");
return success();
}
// Is this `cc.compute_ptr` in LLVM normal form?
// To be in LLVM normal form, the base object must have a type of
// `!cc.ptr<!cc.array<T x ?>>`, which corresponds 1:1 with LLVM's GEP semantics.
bool cudaq::cc::ComputePtrOp::llvmNormalForm() {
if (auto ptrTy = dyn_cast<PointerType>(getBase().getType()))
if (auto arrTy = dyn_cast<ArrayType>(ptrTy.getElementType()))
return arrTy.isUnknownSize();
return false;
}
static ParseResult
parseComputePtrIndices(OpAsmParser &parser,
SmallVectorImpl<OpAsmParser::UnresolvedOperand> &indices,
DenseI32ArrayAttr &rawConstantIndices) {
return parseInterleavedIndices<cudaq::cc::ComputePtrOp>(parser, indices,
rawConstantIndices);
}
static void printComputePtrIndices(OpAsmPrinter &printer,
cudaq::cc::ComputePtrOp computePtrOp,
OperandRange indices,
DenseI32ArrayAttr rawConstantIndices) {
printInterleavedIndices<cudaq::cc::ComputePtrIndicesAdaptor<OperandRange>>(
printer, computePtrOp, indices, rawConstantIndices);
}
void cudaq::cc::ComputePtrOp::build(OpBuilder &builder, OperationState &result,
Type resultType, Value basePtr,
ValueRange indices,
ArrayRef<NamedAttribute> attrs) {
build(builder, result, resultType, basePtr,
SmallVector<ComputePtrArg>(indices), attrs);
}
template <typename A, typename B>
void destructureIndices(Type currType, ArrayRef<B> indices,
SmallVectorImpl<std::int32_t> &rawConstantIndices,
SmallVectorImpl<Value> &dynamicIndices) {
for (const B &iter : indices) {
if (Value val = iter.template dyn_cast<Value>()) {
rawConstantIndices.push_back(A::kDynamicIndex);
dynamicIndices.push_back(val);
} else {
rawConstantIndices.push_back(
iter.template get<cudaq::cc::InterleavedArgumentConstantIndex>());
}
currType =
TypeSwitch<Type, Type>(currType)
.Case([](cudaq::cc::ArrayType containerType) {
return containerType.getElementType();
})
.Case([&](cudaq::cc::StructType structType) -> Type {
auto memberIndex = rawConstantIndices.back();
if (memberIndex >= 0 && static_cast<std::size_t>(memberIndex) <
structType.getMembers().size())
return structType.getMembers()[memberIndex];
return {};
})
.Default(Type{});
}
}
void cudaq::cc::ComputePtrOp::build(OpBuilder &builder, OperationState &result,
Type resultType, Value basePtr,
ArrayRef<ComputePtrArg> cpArgs,
ArrayRef<NamedAttribute> attrs) {
SmallVector<std::int32_t> rawConstantIndices;
SmallVector<Value> dynamicIndices;
Type elementType = cast<cc::PointerType>(basePtr.getType()).getElementType();
destructureIndices<cudaq::cc::ComputePtrOp>(
elementType, cpArgs, rawConstantIndices, dynamicIndices);
result.addTypes(resultType);
result.addAttributes(attrs);
result.addAttribute(getRawConstantIndicesAttrName(result.name),
builder.getDenseI32ArrayAttr(rawConstantIndices));
result.addOperands(basePtr);
result.addOperands(dynamicIndices);
}
OpFoldResult cudaq::cc::ComputePtrOp::fold(FoldAdaptor adaptor) {
if (getDynamicIndices().empty())
return nullptr;
// Params is a list of possible substitutions (Attributes) the length of the
// SSA arguments. Skip the first one, which is the base pointer argument.
auto paramIter = adaptor.getOperands().begin();
++paramIter;
auto dynamicIndexIter = getDynamicIndices().begin();
SmallVector<std::int32_t> newConstantIndices;
SmallVector<Value> newIndices;
bool changed = false;
// Build lists of raw constants and SSA values with the SSA values that have
// substituions omitted and properly interleaved in as constants in the first
// list.
for (auto index : getRawConstantIndices()) {
if (index != kDynamicIndex) {
newConstantIndices.push_back(index);
continue;
}
if (auto newVal = dyn_cast_if_present<IntegerAttr>(*paramIter)) {
newConstantIndices.push_back(newVal.getInt());
changed = true;
} else {
newConstantIndices.push_back(kDynamicIndex);
newIndices.push_back(*dynamicIndexIter);
}
++dynamicIndexIter;
++paramIter;
}
// If any new constants were found, update the cc.compute_ptr in place, adding
// the new constants and dropping any unneeded SSA arguments on the floor.
if (changed) {
assert(newConstantIndices.size() == getRawConstantIndices().size());
assert(newIndices.size() < getDynamicIndices().size());
getDynamicIndicesMutable().assign(newIndices);
setRawConstantIndices(newConstantIndices);
return Value{*this};
}
return nullptr;
}
namespace {
/// If two (or more) `cc.compute_ptr` are chained then they can be fused into a
/// single `cc.compute_ptr`.
struct FuseAddressArithmetic
: public OpRewritePattern<cudaq::cc::ComputePtrOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(cudaq::cc::ComputePtrOp ptrOp,
PatternRewriter &rewriter) const override {
auto base = ptrOp.getBase();
if (auto prev = base.getDefiningOp<cudaq::cc::ComputePtrOp>()) {
// %prev = cc.compute_ptr %pb[<pargs>] : (!ptr<U>, Ts) -> !ptr<V>
// %this = cc.compute_ptr %prev[<targs>] : (!ptr<V>, Ss) -> !ptr<W>
// ────────────────────────────────────────────────────────────────
// %prev = <left as is>
// %this' = cc.compute_ptr %pb[<pargs>, <targs>] :
// (!ptr<U>, Ts Ss) -> !ptr<W>
auto newBase = prev.getBase();
SmallVector<Value> newDynamics = prev.getDynamicIndices();
newDynamics.append(ptrOp.getDynamicIndices().begin(),
ptrOp.getDynamicIndices().end());
SmallVector<std::int32_t> newConstants{
prev.getRawConstantIndices().begin(),
prev.getRawConstantIndices().end()};
newConstants.append(ptrOp.getRawConstantIndices().begin(),
ptrOp.getRawConstantIndices().end());
rewriter.replaceOpWithNewOp<cudaq::cc::ComputePtrOp>(
ptrOp, ptrOp.getType(), newBase, newDynamics, newConstants);
return success();
}
// We always favor the more restricted array type over an open array type.
// Consider tagged the compute_ptr so a less restrictive correctness check
// might be made.
if (auto cast = base.getDefiningOp<cudaq::cc::CastOp>()) {
// %cast = cc.cast %p : (!ptr<array<U x n>>) -> !ptr<array<U x ?>>
// %this = cc.compute_ptr %cast[<targs>] : (!ptr<U x ?>, Ts) -> !ptr<V>
// ────────────────────────────────────────────────────────────────────
// %cast = <left as is>
// %this' = cc.compute_ptr %p[<targs>] : (!ptr<U x n>, Ts) -> !ptr<V>
auto fromTy = dyn_cast<cudaq::cc::PointerType>(cast.getValue().getType());
auto toTy = dyn_cast<cudaq::cc::PointerType>(cast.getType());
if (fromTy && toTy) {
auto fromArrTy =
dyn_cast<cudaq::cc::ArrayType>(fromTy.getElementType());
auto toArrTy = dyn_cast<cudaq::cc::ArrayType>(toTy.getElementType());
if (fromArrTy && toArrTy &&
fromArrTy.getElementType() == toArrTy.getElementType() &&
!fromArrTy.isUnknownSize() && toArrTy.isUnknownSize()) {
rewriter.replaceOpWithNewOp<cudaq::cc::ComputePtrOp>(
ptrOp, ptrOp.getType(), cast.getValue(),
ptrOp.getDynamicIndices(), ptrOp.getRawConstantIndices());
return success();
}
}
}
if (ptrOp.getRawConstantIndices().empty()) {
// This is a degenerate form and really a cast.
rewriter.replaceOpWithNewOp<cudaq::cc::CastOp>(ptrOp, ptrOp.getType(),
ptrOp.getBase());
return success();
}
if (ptrOp.getDynamicIndices().empty()) {
bool allZeros = true;
for (std::int32_t i : ptrOp.getRawConstantIndices())
if (i != 0) {
allZeros = false;
break;
}
if (allZeros) {
// This is really a cast. Replace it with a cast.
rewriter.replaceOpWithNewOp<cudaq::cc::CastOp>(ptrOp, ptrOp.getType(),
ptrOp.getBase());
return success();
}
}
if (ptrOp.llvmNormalForm() && ptrOp.getRawConstantIndices()[0] == 0) {
// This is in LLVM normal form. Simplify it using the following rule.
//
// %8 = cc.compute_ptr %7[0, ...] :
// (!cc.ptr<!cc.array<T x ?>, ...) -> !cc.ptr<U>
// ────────────────────────────────────────────────────────────────
// %new = cc.cast %7 : (!cc.ptr<!cc.array<T x ?>) -> !cc.ptr<T>
// %8 = cc.compute_ptr %new[...] : (!cc.ptr<T>, ...) -> !cc.ptr<U>
// We want to avoid expanding the code and adding more casts.
if (auto castOp = ptrOp.getBase().getDefiningOp<cudaq::cc::CastOp>())
if (isa<cudaq::cc::PointerType>(castOp.getValue().getType())) {
auto ptrTy = cast<cudaq::cc::PointerType>(ptrOp.getBase().getType());
auto eleTy = cast<cudaq::cc::ArrayType>(ptrTy.getElementType());
auto subTy = eleTy.getElementType();
auto simpleTy = cudaq::cc::PointerType::get(subTy);
auto simple = rewriter.create<cudaq::cc::CastOp>(
ptrOp.getLoc(), simpleTy, ptrOp.getBase());
// Collect indices.
auto iter = ptrOp.getDynamicIndices().begin();
SmallVector<cudaq::cc::ComputePtrArg> indices;
for (auto i : ptrOp.getRawConstantIndices().drop_front(1)) {
if (i == cudaq::cc::ComputePtrOp::getDynamicIndexValue())
indices.push_back(*iter++);
else
indices.push_back(i);
}
rewriter.replaceOpWithNewOp<cudaq::cc::ComputePtrOp>(
ptrOp, ptrOp.getType(), simple, indices);
return success();
}
}
return failure();
}
};
} // namespace
void cudaq::cc::ComputePtrOp::getCanonicalizationPatterns(
RewritePatternSet &patterns, MLIRContext *context) {
patterns.add<FuseAddressArithmetic>(context);
}
std::optional<std::int32_t>
cudaq::cc::ComputePtrOp::getConstantIndex(std::size_t arg) {
if (arg >= getRawConstantIndices().size())
return {};
std::int32_t result = getRawConstantIndices()[arg];
if (result == getDynamicIndexValue())
return {};
return {result};
}
//===----------------------------------------------------------------------===//
// ExtractValueOp
//===----------------------------------------------------------------------===//
// Recursively determine if \p ty1 and \p ty2 are compatible. Ordinarily we can
// use type equality, but for StructType we may have a named and unnamed struct
// that are equivalent structurally.
static bool isCompatible(Type ty1, Type ty2) {
if (ty1 == ty2)
return true;
auto sty1 = dyn_cast<cudaq::cc::StructType>(ty1);
auto sty2 = dyn_cast<cudaq::cc::StructType>(ty2);
if (sty1 && sty2) {
if (sty1.getMembers().size() != sty2.getMembers().size() ||
sty1.getPacked() != sty2.getPacked())
return false;
for (auto [a, b] : llvm::zip(sty1.getMembers(), sty2.getMembers()))
if (!isCompatible(a, b))
return false;
return true;
}
return false;
}
LogicalResult cudaq::cc::ExtractValueOp::verify() {
Type eleTy = getAggregate().getType();
auto resultTy = getResult().getType();
for (std::int32_t i : getRawConstantIndices()) {
if (auto arrTy = dyn_cast<cc::ArrayType>(eleTy)) {
if (arrTy.isUnknownSize())
return emitOpError("array must have constant size");
if (i != kDynamicIndex && (i < 0 || i >= arrTy.getSize()))
return emitOpError("array cannot index out of bounds elements");
eleTy = arrTy.getElementType();
} else if (auto strTy = dyn_cast<cc::StructType>(eleTy)) {
if (i == kDynamicIndex)
return emitOpError("struct cannot have non-constant index");
if (i < 0 || static_cast<std::size_t>(i) >= strTy.getMembers().size())
return emitOpError("struct cannot index out of bounds members");
eleTy = strTy.getMember(i);
} else if (auto complexTy = dyn_cast<ComplexType>(eleTy)) {
if (!(i == 0 || i == 1))
return emitOpError("complex index is out of bounds");
eleTy = complexTy.getElementType();
} else {
return emitOpError("too many indices (" +
std::to_string(getRawConstantIndices().size()) +
") for the source pointer");
}
}
if (!isCompatible(eleTy, resultTy))
return emitOpError("result type does not match input");
return success();
}
OpFoldResult cudaq::cc::ExtractValueOp::fold(FoldAdaptor adaptor) {
if (indicesAreConstant())
return nullptr;
// Params is a list of possible substitutions (Attributes) the length of the
// SSA arguments. Skip the first one, which is the base pointer argument.
auto paramIter = adaptor.getOperands().begin();
++paramIter;
auto dynamicIndexIter = getDynamicIndices().begin();
SmallVector<std::int32_t> newConstantIndices;
SmallVector<Value> newIndices;
bool changed = false;
// Build lists of raw constants and SSA values with the SSA values that have
// substituions omitted and properly interleaved in as constants in the first
// list.
for (auto index : getRawConstantIndices()) {
if (index != kDynamicIndex) {
newConstantIndices.push_back(index);
continue;
}
if (auto newVal = dyn_cast_if_present<IntegerAttr>(*paramIter)) {
newConstantIndices.push_back(newVal.getInt());
changed = true;
} else {
newConstantIndices.push_back(kDynamicIndex);
newIndices.push_back(*dynamicIndexIter);
}
++dynamicIndexIter;
++paramIter;
}
// If any new constants were found, update the cc.compute_ptr in place, adding
// the new constants and dropping any unneeded SSA arguments on the floor.
if (changed) {
assert(newConstantIndices.size() == getRawConstantIndices().size());
assert(newIndices.size() < getDynamicIndices().size());
getDynamicIndicesMutable().assign(newIndices);
setRawConstantIndices(newConstantIndices);
return Value{*this};
}
return nullptr;
}
static ParseResult parseExtractValueIndices(
OpAsmParser &parser,
SmallVectorImpl<OpAsmParser::UnresolvedOperand> &indices,
DenseI32ArrayAttr &rawConstantIndices) {
return parseInterleavedIndices<cudaq::cc::ExtractValueOp>(parser, indices,
rawConstantIndices);
}
static void printExtractValueIndices(OpAsmPrinter &printer,
cudaq::cc::ExtractValueOp extractValueOp,
OperandRange indices,
DenseI32ArrayAttr rawConstantIndices) {
printInterleavedIndices<cudaq::cc::ExtractValueIndicesAdaptor<OperandRange>>(
printer, extractValueOp, indices, rawConstantIndices);
}
void cudaq::cc::ExtractValueOp::build(OpBuilder &builder,
OperationState &result, Type resultType,
Value aggregate,
ArrayRef<ExtractValueArg> indices,
ArrayRef<NamedAttribute> attrs) {
SmallVector<std::int32_t> rawConstantIndices;
SmallVector<Value> dynamicIndices;
Type elementType = aggregate.getType();
destructureIndices<cudaq::cc::ExtractValueOp>(
elementType, indices, rawConstantIndices, dynamicIndices);
result.addTypes(resultType);
result.addAttributes(attrs);
result.addAttribute(getRawConstantIndicesAttrName(result.name),
builder.getDenseI32ArrayAttr(rawConstantIndices));
result.addOperands(aggregate);
result.addOperands(dynamicIndices);
}
void cudaq::cc::ExtractValueOp::build(OpBuilder &builder,
OperationState &result, Type resultType,
Value aggregate, ValueRange indices,
ArrayRef<NamedAttribute> attrs) {
SmallVector<ExtractValueArg> args{indices.begin(), indices.end()};
build(builder, result, resultType, aggregate, args, attrs);
}
void cudaq::cc::ExtractValueOp::build(OpBuilder &builder,
OperationState &result, Type resultType,
Value aggregate, std::int32_t index,
ArrayRef<NamedAttribute> attrs) {
build(builder, result, resultType, aggregate,
ArrayRef<ExtractValueArg>{index}, attrs);
}
void cudaq::cc::ExtractValueOp::build(OpBuilder &builder,
OperationState &result, Type resultType,
Value aggregate, Value index,
ArrayRef<NamedAttribute> attrs) {
build(builder, result, resultType, aggregate, ValueRange{index}, attrs);
}
namespace {
struct FuseWithConstantArray
: public OpRewritePattern<cudaq::cc::ExtractValueOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(cudaq::cc::ExtractValueOp extval,
PatternRewriter &rewriter) const override {
if (auto conarr =
extval.getAggregate().getDefiningOp<cudaq::cc::ConstantArrayOp>())
if (extval.indicesAreConstant() &&
extval.getRawConstantIndices().size() == 1) {
if (auto intTy = dyn_cast<IntegerType>(extval.getType())) {
std::int32_t i = extval.getRawConstantIndices()[0];
auto cval = cast<IntegerAttr>(conarr.getConstantValues()[i]).getInt();
rewriter.replaceOpWithNewOp<arith::ConstantIntOp>(extval, cval,
intTy);
return success();
}
if (auto fltTy = dyn_cast<FloatType>(extval.getType())) {
std::int32_t i = extval.getRawConstantIndices()[0];
auto cval = cast<FloatAttr>(conarr.getConstantValues()[i]).getValue();
rewriter.replaceOpWithNewOp<arith::ConstantFloatOp>(extval, cval,
fltTy);
return success();
}
}
return failure();
}
};
} // namespace
void cudaq::cc::ExtractValueOp::getCanonicalizationPatterns(
RewritePatternSet &patterns, MLIRContext *context) {
patterns.add<FuseWithConstantArray>(context);
}
//===----------------------------------------------------------------------===//
// GlobalOp
//===----------------------------------------------------------------------===//
ParseResult cudaq::cc::GlobalOp::parse(OpAsmParser &parser,
OperationState &result) {
// Check for the `extern` optional keyword first.