forked from NVIDIA/cuda-quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertExpr.cpp
More file actions
3900 lines (3680 loc) · 167 KB
/
Copy pathConvertExpr.cpp
File metadata and controls
3900 lines (3680 loc) · 167 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 - 2026 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/Frontend/nvqpp/ASTBridge.h"
#include "cudaq/Frontend/nvqpp/QisBuilder.h"
#include "cudaq/Optimizer/Builder/Factory.h"
#include "cudaq/Optimizer/Builder/Intrinsics.h"
#include "cudaq/Optimizer/Dialect/CC/CCOps.h"
#include "cudaq/Optimizer/Dialect/QEC/QECOps.h"
#include "cudaq/Optimizer/Dialect/Quake/QuakeOps.h"
#include "llvm/Support/Debug.h"
#include "mlir/Dialect/Complex/IR/Complex.h"
#include "mlir/Dialect/Math/IR/Math.h"
#define DEBUG_TYPE "lower-ast-expr"
using namespace mlir;
// Get the result type if \p ty is a function type or just return \p ty.
static Type getResultType(Type ty) {
assert(ty && "Type cannot be null");
if (auto funcTy = dyn_cast<FunctionType>(ty)) {
assert(funcTy.getNumResults() == 1);
return funcTy.getResult(0);
}
return ty;
}
namespace {
// Same intent as `isInNamespace`, but only matches when the immediate
// enclosing namespace is `nsName`. `isInNamespace` drills through nested
// namespaces, so it would silently "hijack" a user-defined
// `cudaq::qec::detector` or `cudaq::foo::detector` that happens to
// share a name with a bridge-intercepted call.
bool isInDirectNamespace(const clang::Decl *x, mlir::StringRef nsName) {
assert(x && "decl is null");
auto *ctx = x->getDeclContext();
// Walk past transparent contexts (linkage specs, etc.) but not through
// regular namespaces.
while (ctx && ctx->isTransparentContext())
ctx = ctx->getParent();
if (auto *ns = llvm::dyn_cast_or_null<clang::NamespaceDecl>(ctx))
if (const auto *ident = ns->getIdentifier())
return ident->getName() == nsName;
return false;
}
} // namespace
// Operands of `&&`, `||`, and `?:` lower into the orphan regions that
// `cc::IfOp::create`'s region-builder lambdas populate before the op is
// attached to its parent block. A function-rooted `mlir::DominanceInfo` cannot
// see ops in that subtree, so the unbound-handle check needs a structural
// ancestor walk instead. Return true iff the store's block lexically dominates
// the load's insertion point, treating yet-unattached parent regions as
// post-store by construction (the bridge always emits the store at the outer
// level before opening the inner `cc.if`).
static bool storeDominatesLoad(cudaq::cc::StoreOp store,
cudaq::cc::LoadOp load) {
Block *storeBlock = store.getOperation()->getBlock();
if (!storeBlock)
return false;
Operation *anchor = load.getOperation();
while (anchor && anchor->getBlock() != storeBlock) {
Block *anchorBlock = anchor->getBlock();
if (!anchorBlock)
return false;
anchor = anchorBlock->getParentOp();
if (!anchor)
return true;
}
if (!anchor)
return false;
return anchor == store.getOperation() ||
store.getOperation()->isBeforeInBlock(anchor);
}
// Follow a pointer back to the `cc.alloca` that owns its storage. Returns null
// if the chain does not bottom out at a local alloca (e.g. a function argument
// or heap pointer).
static cudaq::cc::AllocaOp getOwningAlloca(Value ptr) {
while (true) {
if (auto cp = ptr.getDefiningOp<cudaq::cc::ComputePtrOp>()) {
ptr = cp.getBase();
continue;
}
if (auto cs = ptr.getDefiningOp<cudaq::cc::CastOp>()) {
ptr = cs.getValue();
continue;
}
break;
}
return ptr.getDefiningOp<cudaq::cc::AllocaOp>();
}
// True if any `cc.store` into `alloca` satisfies `pred`. The bridge addresses a
// slot's storage with a single indexing/retyping step before the store, so it
// suffices to check stores directly on the alloca plus stores one hop away
// through a `cc.compute_ptr` / `cc.cast` of it (e.g. brace-init writes elem 0
// via a decay `cc.cast` and elem 1 via a `cc.compute_ptr`).
static bool anyStoreInto(cudaq::cc::AllocaOp alloca,
llvm::function_ref<bool(cudaq::cc::StoreOp)> pred) {
for (Operation *allocaUser : alloca->getUsers()) {
if (auto store = dyn_cast<cudaq::cc::StoreOp>(allocaUser)) {
if (pred(store))
return true;
continue;
}
if (isa<cudaq::cc::ComputePtrOp, cudaq::cc::CastOp>(allocaUser))
for (Operation *uu : allocaUser->getUsers())
if (auto store = dyn_cast<cudaq::cc::StoreOp>(uu))
if (store.getPtrvalue() == allocaUser->getResult(0) && pred(store))
return true;
}
return false;
}
// Walks the use-def chain back to the originating `mz`/`mx`/`my` so the bridge
// can statically diagnose `bool b = h;` when `h` was default-constructed.
//
// On the scalar-handle alloca path, every store reaching the alloca must
// dominate the load (`storeDominatesLoad`); the aggregate / array path stays
// coarse because per-element/per-member tracking would need reasoning about
// SSA `cc.compute_ptr` indices, deferred to a follow-up
// (NVIDIA/cuda-quantum#4479). Recursive because the source of a binding store
// may itself be the result of another load through copy/move stores between
// local allocas. The `visited` set prevents cycles when handles flow through
// multiple allocas.
static bool isBoundHandle(Value v, llvm::SmallPtrSetImpl<Value> &visited) {
if (!visited.insert(v).second)
return false;
if (v.getDefiningOp<cudaq::quake::MeasurementInterface>())
return true;
auto load = v.getDefiningOp<cudaq::cc::LoadOp>();
if (!load)
return true;
Value ptr = load.getPtrvalue();
auto alloca = getOwningAlloca(ptr);
if (!alloca)
return true;
auto eleTy = alloca.getElementType();
bool isScalarHandleAlloca = isa<cudaq::cc::MeasureHandleType>(eleTy);
if (!isScalarHandleAlloca && !cudaq::cc::containsMeasureHandle(eleTy))
return true;
// Bound iff at least one store reaches this alloca with a value that is
// itself bound.
auto checkStore = [&](cudaq::cc::StoreOp store) {
if (!isScalarHandleAlloca)
return true;
if (!storeDominatesLoad(store, load))
return false;
return isBoundHandle(store.getValue(), visited);
};
if (anyStoreInto(alloca, checkStore))
return true;
return false;
}
/// Convert a name, value pair into a symbol name allocated in `allocator`.
static llvm::StringRef
createQubitSymbolTableName(StringRef qregName, Value idxVal,
llvm::BumpPtrAllocator &allocator) {
std::string name;
if (auto idxIntVal = idxVal.getDefiningOp<arith::ConstantIntOp>())
name = qregName.str() + "%" + std::to_string(idxIntVal.value());
else if (auto idxIdxVal = idxVal.getDefiningOp<arith::ConstantIndexOp>())
name = qregName.str() + "%" + std::to_string(idxIdxVal.value());
else {
// idxVal is a general value, like a loop idx
std::stringstream ss;
ss << qregName.str() << "%" << idxVal.getAsOpaquePointer();
name = ss.str();
}
// move `name` to heap memory allocated by the allocator
char *namePtr = allocator.Allocate<char>(name.size());
std::memcpy(namePtr, name.data(), name.size());
return llvm::StringRef(namePtr, name.size());
}
/// Helper to get the declaration of a decl-ref expression.
/// Precondition: \p expr must be a pointer to a DeclRefExpr.
static clang::NamedDecl *getNamedDecl(clang::Expr *expr) {
auto *call = cast<clang::DeclRefExpr>(expr);
return call->getDecl()->getUnderlyingDecl();
}
static std::pair<SmallVector<Value>, SmallVector<Value>>
maybeUnpackOperands(OpBuilder &builder, Location loc, ValueRange operands,
bool isControl = false, size_t targetCount = 1) {
// If this is not a controlled op, then we just keep all operands as targets.
if (!isControl)
return std::make_pair(operands, SmallVector<Value>{});
if (operands.size() > 1)
return std::make_pair(SmallVector<Value>{operands.take_back(targetCount)},
SmallVector<Value>{operands.drop_back(targetCount)});
SmallVector<Value> targets = operands.take_back(targetCount);
Value last_target = operands.back();
if (isa<cudaq::quake::VeqType>(last_target.getType())) {
// Split the vector. Last `targetCount` are targets, front `N-targetCount`
// are controls.
auto vecSize = cudaq::quake::VeqSizeOp::create(
builder, loc, builder.getIntegerType(64), targets);
auto size =
cudaq::cc::CastOp::create(builder, loc, builder.getI64Type(), vecSize,
cudaq::cc::CastOpMode::Unsigned);
auto numTargets = arith::ConstantIntOp::create(
builder, loc, builder.getI64Type(), targetCount);
auto offset = arith::SubIOp::create(builder, loc, size, numTargets);
auto zero =
arith::ConstantIntOp::create(builder, loc, builder.getI64Type(), 0);
auto last = arith::SubIOp::create(builder, loc, offset, numTargets);
// The canonicalizer will compute a constant size, if possible.
auto unsizedVeqTy = cudaq::quake::VeqType::getUnsized(builder.getContext());
// Get the subvector of all targets
Value targetSubveq = cudaq::quake::SubVeqOp::create(
builder, loc, unsizedVeqTy, last_target, zero, offset);
// Get the subvector of all qubits excluding the last one: controls.
Value ctrlSubveq = cudaq::quake::SubVeqOp::create(
builder, loc, unsizedVeqTy, last_target, zero, last);
return std::make_pair(SmallVector<Value>{targetSubveq},
SmallVector<Value>{ctrlSubveq});
}
return std::make_pair(targets, SmallVector<Value>{});
}
namespace {
// Type used to specialize the buildOp function. This extends the cases below by
// prefixing a single parameter value to the list of arguments for cases 1
// and 2. A Param does not have a case 3 defined.
class Param {};
} // namespace
/// Create a negated controls attribute from a range of controls, \p ctrls, and
/// a list of which ones should be negated, \p negations.
static DenseBoolArrayAttr
negatedControlsAttribute(MLIRContext *ctx, ValueRange ctrls,
SmallVector<Value> &negations) {
if (negations.empty())
return {};
SmallVector<bool> negatedControls(ctrls.size());
for (auto v : llvm::enumerate(ctrls))
negatedControls[v.index()] = std::find(negations.begin(), negations.end(),
v.value()) != negations.end();
auto boolVecAttr = DenseBoolArrayAttr::get(ctx, negatedControls);
negations.clear();
return {boolVecAttr};
}
// There are three basic overloads of the "single target" CUDA-Q ops.
//
// 1. op(qubit...)
// This form takes the last qubit as the target and all qubits to
// the left as controls.
// 2. op(qurange, qubit)
// Similar to above except the control qubits are packed in a
// range container.
// 3. op(qurange)
// This is not like the other 2. This is syntactic sugar for
// invoking the op elementally across the entire range container.
// There are no controls.
//
// In the future, it may be decided to add more overloads to this family (e.g.,
// adding controls to case 3).
template <typename A, typename P = void>
bool buildOp(OpBuilder &builder, Location loc, ValueRange operands,
SmallVector<Value> &negations,
llvm::function_ref<void()> reportNegateError,
bool isAdjoint = false, bool isControl = false,
size_t paramCount = 1) {
if constexpr (std::is_same_v<P, Param>) {
assert(operands.size() >= 2 && "must be at least 2 operands");
auto params = operands.take_front(paramCount);
auto [target, ctrls] = maybeUnpackOperands(
builder, loc, operands.drop_front(paramCount), isControl);
for (auto v : target)
if (std::find(negations.begin(), negations.end(), v) != negations.end())
reportNegateError();
auto negs =
negatedControlsAttribute(builder.getContext(), ctrls, negations);
if (ctrls.empty())
for (auto t : target)
A::create(builder, loc, isAdjoint, params, ctrls, t, negs);
else {
assert(target.size() == 1 &&
"can only have a single target with control qubits.");
A::create(builder, loc, isAdjoint, params, ctrls, target, negs);
}
} else {
assert(operands.size() >= 1 && "must be at least 1 operand");
if ((operands.size() == 1) &&
isa<cudaq::quake::VeqType>(operands[0].getType())) {
auto target = operands[0];
if (!negations.empty())
reportNegateError();
Type i64Ty = builder.getI64Type();
auto size = cudaq::quake::VeqSizeOp::create(
builder, loc, builder.getIntegerType(64), target);
Value rank = cudaq::cc::CastOp::create(builder, loc, i64Ty, size,
cudaq::cc::CastOpMode::Unsigned);
auto bodyBuilder = [&](OpBuilder &builder, Location loc, Region &,
Block &block) {
Value ref = cudaq::quake::ExtractRefOp::create(builder, loc, target,
block.getArgument(0));
A::create(builder, loc, ValueRange(), ref);
};
cudaq::opt::factory::createInvariantLoop(builder, loc, rank, bodyBuilder);
} else {
auto [target, ctrls] =
maybeUnpackOperands(builder, loc, operands, isControl);
for (auto v : target)
if (std::find(negations.begin(), negations.end(), v) != negations.end())
reportNegateError();
auto negs =
negatedControlsAttribute(builder.getContext(), ctrls, negations);
if (ctrls.empty())
// May have multiple targets, but no controls, op(q, r, s, ...)
for (auto t : target)
A::create(builder, loc, isAdjoint, ValueRange(), ValueRange(), t,
negs);
else {
assert(target.size() == 1 &&
"can only have a single target with control qubits.");
A::create(builder, loc, isAdjoint, ValueRange(), ctrls, target, negs);
}
}
}
return true;
}
static Value getConstantInt(OpBuilder &builder, Location loc,
const uint64_t value, const int bitwidth) {
return arith::ConstantIntOp::create(builder, loc,
builder.getIntegerType(bitwidth), value);
}
static Value getConstantInt(OpBuilder &builder, Location loc,
const uint64_t value, Type intTy) {
assert(isa<IntegerType>(intTy));
return arith::ConstantIntOp::create(builder, loc, intTy, value);
}
template <auto KindConst, typename T,
typename = std::enable_if_t<std::is_same_v<decltype(KindConst), T>>>
bool isOperatorKind(T kindValue) {
return kindValue == KindConst;
}
/// Is \p kind the `operator[]` function?
static bool isSubscriptOperator(clang::OverloadedOperatorKind kind) {
return isOperatorKind<clang::OverloadedOperatorKind::OO_Subscript>(kind);
}
/// Is \p kind the `operator==` function?
static bool isCompareEqualOperator(clang::OverloadedOperatorKind kind) {
return isOperatorKind<clang::OverloadedOperatorKind::OO_EqualEqual>(kind);
}
/// Is \p kind the `operator=` function?
static bool isAssignmentOperator(clang::OverloadedOperatorKind kind) {
return isOperatorKind<clang::OverloadedOperatorKind::OO_Equal>(kind);
}
/// Is \p kind the `operator!` function?
static bool isExclaimOperator(clang::OverloadedOperatorKind kind) {
return isOperatorKind<clang::OverloadedOperatorKind::OO_Exclaim>(kind);
}
// Perform the standard type coercions when the syntactic expression from the
// AST has arguments of different types.
static void castToSameType(OpBuilder builder, Location loc,
const clang::Type *lhsType, Value &lhs,
const clang::Type *rhsType, Value &rhs) {
if (lhsType == rhsType)
return;
auto lhsTy = lhs.getType();
auto rhsTy = rhs.getType();
if (lhsTy == rhsTy)
return;
if (isa<ComplexType>(lhsTy) || isa<ComplexType>(rhsTy)) {
auto widenComplex = [&](const clang::Type *lEleTy,
const clang::Type *rEleTy) {
Value lre = complex::ReOp::create(builder, loc, lhs);
Value lim = complex::ImOp::create(builder, loc, lhs);
Value rre = complex::ReOp::create(builder, loc, rhs);
Value rim = complex::ImOp::create(builder, loc, rhs);
castToSameType(builder, loc, lEleTy, lre, rEleTy, rre);
castToSameType(builder, loc, lEleTy, lim, rEleTy, rim);
auto cmplxTy = ComplexType::get(lre.getType());
lhs = complex::CreateOp::create(builder, loc, cmplxTy, lre, lim);
rhs = complex::CreateOp::create(builder, loc, cmplxTy, rre, rim);
};
auto promoteToComplex = [&](const clang::Type *cmplxTy, Value cmplx,
const clang::Type *otherTy, Value &other) {
Value dummy = complex::ReOp::create(builder, loc, cmplx);
Value otherDummy = other;
castToSameType(builder, loc, cmplxTy, dummy, otherTy, otherDummy);
auto newTy = ComplexType::get(dummy.getType());
Value zero = arith::getZeroConstant(builder, loc, dummy.getType());
other = complex::CreateOp::create(builder, loc, newTy, otherDummy, zero);
};
if (isa<ComplexType>(lhsTy) && isa<ComplexType>(rhsTy)) {
widenComplex(
cast<clang::ComplexType>(lhsType)->getElementType().getTypePtr(),
cast<clang::ComplexType>(rhsType)->getElementType().getTypePtr());
return;
}
if (isa<ComplexType>(lhsTy)) {
promoteToComplex(
cast<clang::ComplexType>(lhsType)->getElementType().getTypePtr(), lhs,
rhsType, rhs);
return;
}
promoteToComplex(
cast<clang::ComplexType>(rhsType)->getElementType().getTypePtr(), rhs,
lhsType, lhs);
return;
}
if (isa<IntegerType>(lhsTy) && isa<IntegerType>(rhsTy)) {
if (lhsTy.getIntOrFloatBitWidth() < rhsTy.getIntOrFloatBitWidth()) {
auto mode = (lhsType && lhsType->isUnsignedIntegerOrEnumerationType())
? cudaq::cc::CastOpMode::Unsigned
: cudaq::cc::CastOpMode::Signed;
lhs = cudaq::cc::CastOp::create(builder, loc, rhs.getType(), lhs, mode);
return;
}
auto mode = (rhsType && rhsType->isUnsignedIntegerOrEnumerationType())
? cudaq::cc::CastOpMode::Unsigned
: cudaq::cc::CastOpMode::Signed;
rhs = cudaq::cc::CastOp::create(builder, loc, lhs.getType(), rhs, mode);
return;
}
if (isa<FloatType>(lhsTy) && isa<FloatType>(rhsTy)) {
if (lhsTy.getIntOrFloatBitWidth() < rhsTy.getIntOrFloatBitWidth()) {
lhs = cudaq::cc::CastOp::create(builder, loc, rhs.getType(), lhs);
return;
}
rhs = cudaq::cc::CastOp::create(builder, loc, lhs.getType(), rhs);
return;
}
if (isa<FloatType>(lhsTy) && isa<IntegerType>(rhsTy)) {
auto mode = (rhsType && rhsType->isUnsignedIntegerOrEnumerationType())
? cudaq::cc::CastOpMode::Unsigned
: cudaq::cc::CastOpMode::Signed;
rhs = cudaq::cc::CastOp::create(builder, loc, lhs.getType(), rhs, mode);
return;
}
if (isa<IntegerType>(lhsTy) && isa<FloatType>(rhsTy)) {
auto mode = (lhsType && lhsType->isUnsignedIntegerOrEnumerationType())
? cudaq::cc::CastOpMode::Unsigned
: cudaq::cc::CastOpMode::Signed;
lhs = cudaq::cc::CastOp::create(builder, loc, rhs.getType(), lhs, mode);
return;
}
TODO_loc(loc, "conversion of operands in binary expression");
}
static clang::CXXRecordDecl *
classDeclFromTemplateArgument(clang::FunctionDecl &func,
std::size_t argumentPosition,
clang::ASTContext &astContext) {
if (auto *paramDecl = func.getParamDecl(argumentPosition))
if (auto *defn = paramDecl->getDefinition(astContext)) {
// Check `auto &&` case.
if (auto *rvalueRefTy = dyn_cast<clang::RValueReferenceType>(
defn->getType().getTypePtr()))
if (auto *substTmpl = dyn_cast<clang::SubstTemplateTypeParmType>(
rvalueRefTy->getPointeeType().getTypePtr())) {
auto qualTy = substTmpl->getReplacementType();
return qualTy.getTypePtr()->getAsCXXRecordDecl();
}
// Check `class-name &` case.
if (auto *lvalueRefTy = dyn_cast<clang::LValueReferenceType>(
defn->getType().getTypePtr()))
return lvalueRefTy->getPointeeType().getTypePtr()->getAsCXXRecordDecl();
}
return nullptr;
}
static bool isStdVectorType(clang::QualType type) {
const auto canonicalType = type.getCanonicalType();
const auto *recordDecl = canonicalType.getTypePtr()->getAsCXXRecordDecl();
return recordDecl && recordDecl->getName() == "vector" &&
cudaq::isInNamespace(recordDecl, "std");
}
static const clang::FunctionProtoType *
functionProtoTypeFromDeviceCallTarget(clang::QualType type) {
auto canonicalType = type.getCanonicalType();
if (auto *pointerType = canonicalType->getAs<clang::PointerType>())
canonicalType = pointerType->getPointeeType().getCanonicalType();
if (auto *referenceType = canonicalType->getAs<clang::ReferenceType>())
canonicalType = referenceType->getPointeeType().getCanonicalType();
return canonicalType->getAs<clang::FunctionProtoType>();
}
static DenseI64ArrayAttr
buildByRefVecArgIndicesAttr(OpBuilder &builder, clang::CallExpr *call,
std::size_t targetArgIndex) {
const auto *prototype = functionProtoTypeFromDeviceCallTarget(
call->getArg(targetArgIndex)->IgnoreParenImpCasts()->getType());
if (!prototype)
return {};
SmallVector<std::int64_t> indices;
for (unsigned i = 0, e = prototype->getNumParams(); i < e; ++i) {
const auto paramType = prototype->getParamType(i);
const auto *refType = paramType->getAs<clang::LValueReferenceType>();
if (!refType)
continue;
const clang::QualType pointeeType = refType->getPointeeType();
if (pointeeType.isConstQualified() || !isStdVectorType(pointeeType))
continue;
indices.push_back(i);
}
if (indices.empty())
return {};
return builder.getDenseI64ArrayAttr(indices);
}
/// Is this type name one of the `cudaq` types that map to a VeqType?
static bool isCudaQType(StringRef tn) {
return tn == "qreg" || tn == "qspan" || tn == "qarray" || tn == "qview" ||
tn == "qvector";
}
namespace cudaq::detail {
/// Is \p x the `operator()` function?
static bool isCallOperator(clang::CXXOperatorCallExpr *x) {
return cudaq::isCallOperator(x->getOperator());
}
FunctionType QuakeBridgeVisitor::peelPointerFromFunction(Type ty) {
if (auto ptrTy = dyn_cast<cudaq::cc::PointerType>(ty))
ty = ptrTy.getElementType();
return cast<FunctionType>(ty);
}
bool QuakeBridgeVisitor::VisitArraySubscriptExpr(clang::ArraySubscriptExpr *x) {
auto loc = toLocation(x->getSourceRange());
auto rhs = popValue();
auto lhs = popValue();
Type eleTy = [&]() {
// NB: Check both arguments as expression may be inverted.
if (auto ptrTy = dyn_cast<cc::PointerType>(lhs.getType()))
return ptrTy.getElementType();
return cast<cc::PointerType>(rhs.getType()).getElementType();
}();
Type arrEleTy = [&]() {
// FIXME: The following dyn_cast should never fail.
if (auto arrTy = dyn_cast<cc::ArrayType>(eleTy))
return arrTy.getElementType();
return eleTy;
}();
auto elePtrTy = cc::PointerType::get(arrEleTy);
return pushValue(cc::ComputePtrOp::create(builder, loc, elePtrTy, lhs, rhs));
}
bool QuakeBridgeVisitor::VisitFloatingLiteral(clang::FloatingLiteral *x) {
// Literals do not push a type on the type stack.
auto loc = toLocation(x->getSourceRange());
auto bltTy = cast<clang::BuiltinType>(x->getType().getTypePtr());
auto fltTy = cast<FloatType>(builtinTypeToType(bltTy));
auto fltVal = x->getValue();
return pushValue(
opt::factory::createFloatConstant(loc, builder, fltVal, fltTy));
}
bool QuakeBridgeVisitor::VisitImaginaryLiteral(clang::ImaginaryLiteral *x) {
auto loc = toLocation(x->getSourceRange());
auto *subExpr = x->getSubExpr();
auto *fltLit = cast<clang::FloatingLiteral>(subExpr);
auto bltTy = cast<clang::BuiltinType>(fltLit->getType().getTypePtr());
auto fltTy = cast<FloatType>(builtinTypeToType(bltTy));
auto cmplxTy = ComplexType::get(fltTy);
auto imag = popValue();
auto zero = arith::getZeroConstant(builder, loc, imag.getType());
return pushValue(
complex::CreateOp::create(builder, loc, cmplxTy, zero, imag));
}
bool QuakeBridgeVisitor::VisitCXXBoolLiteralExpr(clang::CXXBoolLiteralExpr *x) {
auto loc = toLocation(x->getSourceRange());
auto intTy =
builtinTypeToType(cast<clang::BuiltinType>(x->getType().getTypePtr()));
auto intVal = x->getValue();
return pushValue(getConstantInt(builder, loc, intVal ? 1 : 0, intTy));
}
bool QuakeBridgeVisitor::VisitIntegerLiteral(clang::IntegerLiteral *x) {
auto loc = toLocation(x->getSourceRange());
auto intTy =
builtinTypeToType(cast<clang::BuiltinType>(x->getType().getTypePtr()));
auto intVal = x->getValue().getLimitedValue();
return pushValue(getConstantInt(builder, loc, intVal, intTy));
}
bool QuakeBridgeVisitor::VisitCharacterLiteral(clang::CharacterLiteral *x) {
auto loc = toLocation(x->getSourceRange());
auto intTy =
builtinTypeToType(cast<clang::BuiltinType>(x->getType().getTypePtr()));
auto intVal = x->getValue();
return pushValue(arith::ConstantIntOp::create(builder, loc, intTy, intVal));
}
bool QuakeBridgeVisitor::VisitUnaryOperator(clang::UnaryOperator *x) {
auto loc = toLocation(x->getSourceRange());
switch (x->getOpcode()) {
case clang::UnaryOperatorKind::UO_PostInc: {
auto var = popValue();
auto loaded = cc::LoadOp::create(builder, loc, var);
auto incremented = arith::AddIOp::create(
builder, loc, loaded,
getConstantInt(builder, loc, 1,
loaded.getType().getIntOrFloatBitWidth()));
cc::StoreOp::create(builder, loc, incremented, var);
return pushValue(loaded);
}
case clang::UnaryOperatorKind::UO_PreInc: {
auto var = popValue();
auto loaded = cc::LoadOp::create(builder, loc, var);
auto incremented = arith::AddIOp::create(
builder, loc, loaded,
getConstantInt(builder, loc, 1,
loaded.getType().getIntOrFloatBitWidth()));
cc::StoreOp::create(builder, loc, incremented, var);
return pushValue(incremented);
}
case clang::UnaryOperatorKind::UO_PostDec: {
auto var = popValue();
auto loaded = cc::LoadOp::create(builder, loc, var);
auto decremented = arith::SubIOp::create(
builder, loc, loaded,
getConstantInt(builder, loc, 1,
loaded.getType().getIntOrFloatBitWidth()));
cc::StoreOp::create(builder, loc, decremented, var);
return pushValue(loaded);
}
case clang::UnaryOperatorKind::UO_PreDec: {
auto var = popValue();
auto loaded = cc::LoadOp::create(builder, loc, var);
auto decremented = arith::SubIOp::create(
builder, loc, loaded,
getConstantInt(builder, loc, 1,
loaded.getType().getIntOrFloatBitWidth()));
cc::StoreOp::create(builder, loc, decremented, var);
return pushValue(decremented);
}
case clang::UnaryOperatorKind::UO_LNot: {
auto var = popValue();
auto zero = arith::ConstantIntOp::create(builder, loc, var.getType(), 0);
Value unaryNot = arith::CmpIOp::create(builder, loc,
arith::CmpIPredicate::eq, var, zero);
return pushValue(unaryNot);
}
case clang::UnaryOperatorKind::UO_Minus: {
auto subExpr = popValue();
auto resTy = subExpr.getType();
if (isa<IntegerType>(resTy))
return pushValue(arith::MulIOp::create(
builder, loc, subExpr,
getConstantInt(builder, loc, -1, resTy.getIntOrFloatBitWidth())));
if (isa<FloatType>(resTy)) {
auto neg_one = opt::factory::createFloatConstant(loc, builder, -1.0,
cast<FloatType>(resTy));
return pushValue(arith::MulFOp::create(builder, loc, subExpr, neg_one));
}
TODO_x(loc, x, mangler, "unknown type for unary minus");
return false;
}
case clang::UnaryOperatorKind::UO_Deref: {
auto subExpr = popValue();
assert(isa<cc::PointerType>(subExpr.getType()));
return pushValue(cc::LoadOp::create(builder, loc, subExpr));
}
case clang::UnaryOperatorKind::UO_AddrOf: {
auto subExpr = peekValue();
assert(isa<cc::PointerType>(subExpr.getType()));
return true;
}
case clang::UnaryOperatorKind::UO_Extension: {
TODO_x(loc, x, mangler, "__extension__ operator");
return false;
}
case clang::UnaryOperatorKind::UO_Coawait: {
TODO_x(loc, x, mangler, "co_await operator");
return false;
}
}
TODO_x(loc, x, mangler, "unprocessed unary operator");
return false;
}
Value QuakeBridgeVisitor::floatingPointCoercion(Location loc, Type toType,
Value value) {
auto fromType = value.getType();
if (toType == fromType)
return value;
assert(isa<FloatType>(fromType) && isa<FloatType>(toType));
return cudaq::cc::CastOp::create(builder, loc, toType, value);
}
Value QuakeBridgeVisitor::integerCoercion(Location loc,
const clang::QualType &clangTy,
Type dstTy, Value srcVal) {
auto fromTy = getResultType(srcVal.getType());
if (dstTy == fromTy)
return srcVal;
assert(isa<IntegerType>(fromTy) && isa<IntegerType>(dstTy));
if (fromTy.getIntOrFloatBitWidth() < dstTy.getIntOrFloatBitWidth()) {
auto mode = (clangTy->isUnsignedIntegerOrEnumerationType())
? cudaq::cc::CastOpMode::Unsigned
: cudaq::cc::CastOpMode::Signed;
return cudaq::cc::CastOp::create(builder, loc, dstTy, srcVal, mode);
}
assert(fromTy.getIntOrFloatBitWidth() > dstTy.getIntOrFloatBitWidth());
return cudaq::cc::CastOp::create(builder, loc, dstTy, srcVal);
}
/// Generalized kernel argument morphing. When traversing the AST, the calling
/// context's argument values that have already been created may be similar to
/// but not identical to the callee's signature types. This function deals with
/// adding the glue code to make the call strongly (exactly) type conforming.
SmallVector<Value> QuakeBridgeVisitor::convertKernelArgs(
Location loc, std::size_t dropFrontNum, const SmallVector<Value> &args,
ArrayRef<Type> kernelArgTys, clang::CallExpr *x) {
SmallVector<Value> result;
assert(args.size() - dropFrontNum == kernelArgTys.size());
for (auto i = dropFrontNum, end = args.size(); i < end; ++i) {
auto v = args[i];
auto vTy = v.getType();
auto kTy = kernelArgTys[i - dropFrontNum];
if (vTy == kTy) {
result.push_back(v);
continue;
}
if (auto ptrTy = dyn_cast<cudaq::cc::PointerType>(vTy)) {
auto eleTy = ptrTy.getElementType();
if (eleTy == kTy) {
// Promote pass-by-reference to pass-by-value.
auto load = cudaq::cc::LoadOp::create(builder, loc, v);
result.push_back(load);
continue;
}
// We've passed clang++'s semantics checks but the types are distinct.
if (isa<cudaq::cc::PointerType>(kTy)) {
result.push_back(cudaq::cc::CastOp::create(builder, loc, kTy, v));
continue;
}
auto load = cudaq::cc::LoadOp::create(builder, loc, v);
auto loadTy = load.getType();
Value castTo;
if (isa<IntegerType>(loadTy) && isa<IntegerType>(kTy)) {
castTo = integerCoercion(loc, x->getArg(i)->getType(), kTy, load);
} else if (isa<FloatType>(loadTy) && isa<FloatType>(kTy)) {
castTo = floatingPointCoercion(loc, kTy, load);
} else if (isa<FloatType>(loadTy) && isa<IntegerType>(kTy)) {
TODO_loc(loc, "implicit argument type conversion (fp to integral)");
} else if (isa<IntegerType>(loadTy) && isa<FloatType>(kTy)) {
TODO_loc(loc, "implicit argument type conversion (integral to fp)");
}
result.push_back(castTo);
continue;
}
if (auto vVecTy = dyn_cast<cudaq::quake::VeqType>(vTy))
if (auto kVecTy = dyn_cast<cudaq::quake::VeqType>(kTy)) {
// Both are Veq but the Veq are not identical. If the callee has a
// dynamic size, we can relax the size from the calling context.
if (vVecTy.hasSpecifiedSize() && !kVecTy.hasSpecifiedSize()) {
auto relax =
cudaq::quake::RelaxSizeOp::create(builder, loc, kVecTy, v);
result.push_back(relax);
continue;
}
}
LLVM_DEBUG(llvm::dbgs() << "convert: " << v << "\nto:" << kTy << '\n');
TODO_loc(loc, "argument type conversion");
}
return result;
}
bool QuakeBridgeVisitor::TraverseCastExpr(clang::CastExpr *x,
DataRecursionQueue *) {
// RecursiveASTVisitor is tuned for dumping surface syntax so doesn't
// necessarily visit the type. Override so that the casted to type is visited
// and pushed on the stack.
[[maybe_unused]] auto typeStackDepth = typeStack.size();
LLVM_DEBUG(llvm::dbgs() << "%% "; x->dump());
if (!TraverseType(x->getType()))
return false;
assert(typeStack.size() == typeStackDepth + 1 && "must push a type");
for (auto *sub : getStmtChildren(x))
if (!TraverseStmt(sub))
return false;
bool result = WalkUpFromCastExpr(x);
assert((!result || typeStack.size() == typeStackDepth) &&
"must be original depth");
return result;
}
bool QuakeBridgeVisitor::VisitCastExpr(clang::CastExpr *x) {
// The type to cast the expression into is pushed during the traversal of the
// ImplicitCastExpr in non-error cases.
auto castToTy = popType();
auto loc = toLocation(x);
auto intToIntCast = [&](Location locSub, Value mlirVal) {
clang::QualType srcTy = x->getSubExpr()->getType();
// Check for and handle reference to integer cases.
if (isa<cudaq::cc::PointerType>(mlirVal.getType()))
mlirVal = cudaq::cc::LoadOp::create(builder, loc, mlirVal);
return pushValue(integerCoercion(locSub, srcTy, castToTy, mlirVal));
};
switch (x->getCastKind()) {
case clang::CastKind::CK_LValueToRValue: {
auto subValue = loadLValue(popValue());
return pushValue(subValue);
}
case clang::CastKind::CK_BitCast: {
auto value = popValue();
return pushValue(cudaq::cc::CastOp::create(builder, loc, castToTy, value));
}
case clang::CastKind::CK_FloatingCast: {
[[maybe_unused]] auto dstType = x->getType();
[[maybe_unused]] auto val = x->getSubExpr();
assert(val->getType()->isFloatingType() && dstType->isFloatingType());
auto value = popValue();
auto toType = cast<FloatType>(castToTy);
auto fromType = cast<FloatType>(value.getType());
assert(toType && fromType);
if (toType == fromType)
return pushValue(value);
return pushValue(cudaq::cc::CastOp::create(builder, loc, toType, value));
}
case clang::CastKind::CK_IntegralCast: {
auto locSub = toLocation(x->getSubExpr());
auto result = intToIntCast(locSub, popValue());
assert(result && "integer conversion failed");
return result;
}
case clang::CastKind::CK_FunctionToPointerDecay:
case clang::CastKind::CK_ArrayToPointerDecay:
case clang::CastKind::CK_NoOp:
case clang::CastKind::CK_ToVoid:
case clang::CastKind::CK_BuiltinFnToFnPtr:
return true;
case clang::CastKind::CK_FloatingToIntegral: {
auto qualTy = x->getType();
auto mode = qualTy->isUnsignedIntegerOrEnumerationType()
? cudaq::cc::CastOpMode::Unsigned
: cudaq::cc::CastOpMode::Signed;
return pushValue(
cudaq::cc::CastOp::create(builder, loc, castToTy, popValue(), mode));
}
case clang::CastKind::CK_IntegralToFloating: {
auto mode =
(x->getSubExpr()->getType()->isUnsignedIntegerOrEnumerationType())
? cudaq::cc::CastOpMode::Unsigned
: cudaq::cc::CastOpMode::Signed;
return pushValue(
cudaq::cc::CastOp::create(builder, loc, castToTy, popValue(), mode));
}
case clang::CastKind::CK_IntegralToBoolean: {
auto last = popValue();
Value zero = arith::ConstantIntOp::create(builder, loc, last.getType(), 0);
return pushValue(arith::CmpIOp::create(
builder, loc, arith::CmpIPredicate::ne, last, zero));
}
case clang::CastKind::CK_FloatingToBoolean: {
auto last = popValue();
Value zero = opt::factory::createFloatConstant(
loc, builder, 0.0, cast<FloatType>(last.getType()));
return pushValue(arith::CmpFOp::create(
builder, loc, arith::CmpFPredicate::UNE, last, zero));
}
case clang::CastKind::CK_UserDefinedConversion: {
auto sub = popValue();
// castToTy is the destination type of the user-defined conversion.
castToTy = popType();
if (isa<IntegerType>(castToTy) && isa<IntegerType>(sub.getType())) {
auto locSub = toLocation(x->getSubExpr());
bool result = intToIntCast(locSub, sub);
assert(result && "integer conversion failed");
return result;
}
// `cudaq::measure_handle::operator bool()` is the single sanctioned
// coercion surface on `measure_handle`. Every bool-coercion context lowers
// through this call site. We emit the single required `quake.discriminate`
// here so the inserted op's location is the coercion site. The
// unbound-handle check catches the `measure_handle h; bool b = h;`
// pattern, including chains routed through copy/move stores between
// local `alloca`s.
if (auto intTy = dyn_cast<IntegerType>(castToTy);
intTy && intTy.getWidth() == 1) {
Value handleVal = loadHandleIfPointer(builder, loc, sub);
if (isa<cc::MeasureHandleType>(handleVal.getType())) {
llvm::SmallPtrSet<Value, 4> visited;
if (!isBoundHandle(handleVal, visited)) {
reportClangError(x, mangler,
"discriminating an unbound measure_handle");
// Push a placeholder `i1` so the enclosing statement's value
// stack stays balanced. Returning `false` here would cause
// the outer `TraverseStmt` to emit a second, generic
// "statement not supported" diagnostic.
return pushValue(arith::ConstantIntOp::create(
builder, loc, builder.getI1Type(), /*value=*/0));
}
return pushValue(cudaq::quake::DiscriminateOp::create(
builder, loc, builder.getI1Type(), handleVal));
}
}
TODO_loc(loc, "unhandled user-defined implicit conversion");
}
case clang::CastKind::CK_ConstructorConversion: {
// Enable implicit conversion of surface types, which both map to VeqType.
if (isa<cudaq::quake::VeqType>(castToTy))
if (auto cxxExpr = dyn_cast<clang::CXXConstructExpr>(x->getSubExpr()))
if (cxxExpr->getNumArgs() == 1 &&
isa<cudaq::quake::VeqType>(peekValue().getType()))
return true;
// ... or which both map to RefType.
if (isa<cudaq::quake::RefType>(castToTy))
if (auto cxxExpr = dyn_cast<clang::CXXConstructExpr>(x->getSubExpr()))
if (cxxExpr->getNumArgs() == 1 &&
isa<cudaq::quake::RefType>(peekValue().getType()))
return true;
// Enable implicit conversion of lambda -> std::function, which are both
// cc::CallableType.
if (isa<cc::CallableType>(castToTy)) {
// Enable implicit conversion of callable -> std::function.
if (auto cxxExpr = dyn_cast<clang::CXXConstructExpr>(x->getSubExpr()))
if (cxxExpr->getNumArgs() == 1)
return true;
}
if (isa<ComplexType>(castToTy) && isa<ComplexType>(peekValue().getType()))
return true;
if (isa<cudaq::quake::StateType>(castToTy))
if (auto ptrTy = dyn_cast<cudaq::cc::PointerType>(peekValue().getType()))
if (isa<cudaq::quake::StateType>(ptrTy.getElementType()))
return pushValue(cudaq::cc::LoadOp::create(builder, loc, popValue()));
if (auto funcTy = peelPointerFromFunction(castToTy))
if (auto fromTy = dyn_cast<cc::CallableType>(peekValue().getType())) {
auto inputs = funcTy.getInputs();
if (!inputs.empty() && inputs[0] == fromTy)
return true;
}
TODO_loc(loc, "unhandled implicit cast expression: constructor conversion");
}
}
// Handle the case where we have if ( vec[i] ), where vec == vector<i32>.
// This leads to an ImplicitCastExpr (IntegralToBoolean) -> ImplicitCastExpr
// (LvalueToRvalue)
if (auto anotherCast = dyn_cast<clang::ImplicitCastExpr>(x->getSubExpr())) {
if (!VisitImplicitCastExpr(anotherCast))
return false;
if (x->getCastKind() == clang::CastKind::CK_IntegralToBoolean) {
auto last = popValue();
Value zero =
arith::ConstantIntOp::create(builder, loc, last.getType(), 0);
return pushValue(arith::CmpIOp::create(
builder, loc, arith::CmpIPredicate::ne, last, zero));
}
}
TODO_loc(loc, "unhandled implicit cast expression");
}
bool QuakeBridgeVisitor::TraverseBinaryOperator(clang::BinaryOperator *x,
DataRecursionQueue *) {
bool shortCircuitWhenTrue =
x->getOpcode() == clang::BinaryOperatorKind::BO_LOr;
// The && and || operators are semantically if statements. Traverse them
// differently than other expressions since both sides of the expression are
// not always evaluated.
switch (x->getOpcode()) {
case clang::BinaryOperatorKind::BO_LAnd:
case clang::BinaryOperatorKind::BO_LOr: {
auto *lhs = x->getLHS();
if (!TraverseStmt(lhs))
return false;
auto lhsVal = popValue();