forked from NVIDIA/cuda-quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertToQIRAPI.cpp
More file actions
1889 lines (1686 loc) · 75.5 KB
/
ConvertToQIRAPI.cpp
File metadata and controls
1889 lines (1686 loc) · 75.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 - 2024 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 "CodeGenOps.h"
#include "cudaq/Optimizer/Builder/Intrinsics.h"
#include "cudaq/Optimizer/Builder/Runtime.h"
#include "cudaq/Optimizer/CodeGen/CodeGenDialect.h"
#include "cudaq/Optimizer/CodeGen/Passes.h"
#include "cudaq/Optimizer/CodeGen/Pipelines.h"
#include "cudaq/Optimizer/CodeGen/QIRAttributeNames.h"
#include "cudaq/Optimizer/CodeGen/QIRFunctionNames.h"
#include "cudaq/Optimizer/CodeGen/QIROpaqueStructTypes.h"
#include "cudaq/Optimizer/CodeGen/QuakeToExecMgr.h"
#include "cudaq/Optimizer/Dialect/CC/CCDialect.h"
#include "cudaq/Optimizer/Dialect/CC/CCOps.h"
#include "cudaq/Optimizer/Dialect/Quake/QuakeDialect.h"
#include "cudaq/Optimizer/Dialect/Quake/QuakeOps.h"
#include "nlohmann/json.hpp"
#include "llvm/Support/Debug.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Pass/PassOptions.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#define DEBUG_TYPE "convert-to-qir-api"
namespace cudaq::opt {
#define GEN_PASS_DEF_QUAKETOQIRAPI
#define GEN_PASS_DEF_QUAKETOQIRAPIPREP
#define GEN_PASS_DEF_QUAKETOQIRAPIFINAL
#include "cudaq/Optimizer/CodeGen/Passes.h.inc"
} // namespace cudaq::opt
using namespace mlir;
//===----------------------------------------------------------------------===//
static std::string getGateName(Operation *op) {
return op->getName().stripDialect().str();
}
static std::string getGateFunctionPrefix(Operation *op) {
return cudaq::opt::QIRQISPrefix + getGateName(op);
}
constexpr std::array<std::string_view, 2> filterAdjointNames = {"s", "t"};
template <typename OP>
std::pair<std::string, bool> generateGateFunctionName(OP op) {
auto prefix = getGateFunctionPrefix(op.getOperation());
auto gateName = getGateName(op.getOperation());
if (op.isAdj()) {
if (std::find(filterAdjointNames.begin(), filterAdjointNames.end(),
gateName) != filterAdjointNames.end())
prefix += "dg";
}
if (!op.getControls().empty())
return {prefix + "__ctl", false};
return {prefix, true};
}
static Value createGlobalCString(Operation *op, Location loc,
ConversionPatternRewriter &rewriter,
StringRef regName) {
cudaq::IRBuilder irb(rewriter.getContext());
auto mod = op->getParentOfType<ModuleOp>();
auto nameObj = irb.genCStringLiteralAppendNul(loc, mod, regName);
Value nameVal = rewriter.create<cudaq::cc::AddressOfOp>(
loc, cudaq::cc::PointerType::get(nameObj.getType()), nameObj.getName());
auto cstrTy = cudaq::cc::PointerType::get(rewriter.getI8Type());
return rewriter.create<cudaq::cc::CastOp>(loc, cstrTy, nameVal);
}
/// Use modifier class classes to specialize the QIR API to a particular flavor
/// of QIR. For example, the names of the actual functions in "full QIR" are
/// different than the names used by the other API flavors.
namespace {
//===----------------------------------------------------------------------===//
// Type converter
//===----------------------------------------------------------------------===//
/// Type converter for converting quake dialect to one of the QIR APIs. This
/// class is used for conversions as well as instantiating QIR types in
/// conversion patterns.
struct QIRAPITypeConverter : public TypeConverter {
using TypeConverter::convertType;
QIRAPITypeConverter(bool useOpaque) : useOpaque(useOpaque) {
addConversion([&](Type ty) { return ty; });
addConversion([&](FunctionType ft) { return convertFunctionType(ft); });
addConversion([&](cudaq::cc::PointerType ty) {
return cudaq::cc::PointerType::get(convertType(ty.getElementType()));
});
addConversion([&](cudaq::cc::CallableType ty) {
auto newSig = cast<FunctionType>(convertType(ty.getSignature()));
return cudaq::cc::CallableType::get(newSig);
});
addConversion([&](cudaq::cc::IndirectCallableType ty) {
auto newSig = cast<FunctionType>(convertType(ty.getSignature()));
return cudaq::cc::IndirectCallableType::get(newSig);
});
addConversion(
[&](quake::VeqType ty) { return getArrayType(ty.getContext()); });
addConversion(
[&](quake::RefType ty) { return getQubitType(ty.getContext()); });
addConversion(
[&](quake::WireType ty) { return getQubitType(ty.getContext()); });
addConversion(
[&](quake::ControlType ty) { return getQubitType(ty.getContext()); });
addConversion(
[&](quake::MeasureType ty) { return getResultType(ty.getContext()); });
addConversion([&](quake::StruqType ty) { return convertStruqType(ty); });
}
Type convertFunctionType(FunctionType ty) {
SmallVector<Type> args;
if (failed(convertTypes(ty.getInputs(), args)))
return {};
SmallVector<Type> res;
if (failed(convertTypes(ty.getResults(), res)))
return {};
return FunctionType::get(ty.getContext(), args, res);
}
Type convertStruqType(quake::StruqType ty) {
SmallVector<Type> mems;
mems.reserve(ty.getNumMembers());
if (failed(convertTypes(ty.getMembers(), mems)))
return {};
return cudaq::cc::StructType::get(ty.getContext(), mems);
}
Type getQubitType(MLIRContext *ctx) {
return cudaq::cg::getQubitType(ctx, useOpaque);
}
Type getArrayType(MLIRContext *ctx) {
return cudaq::cg::getArrayType(ctx, useOpaque);
}
Type getResultType(MLIRContext *ctx) {
return cudaq::cg::getResultType(ctx, useOpaque);
}
bool useOpaque;
};
} // namespace
namespace {
//===----------------------------------------------------------------------===//
// Conversion patterns
//===----------------------------------------------------------------------===//
template <typename M>
struct AllocaOpToCallsRewrite : public OpConversionPattern<quake::AllocaOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::AllocaOp alloc, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// If this alloc is just returning a qubit
if (auto resultType =
dyn_cast_if_present<quake::RefType>(alloc.getType())) {
// StringRef qirQubitAllocate = cudaq::opt::QIRQubitAllocate;
StringRef qirQubitAllocate = cudaq::opt::QIRQubitAllocate;
Type qubitTy = M::getQubitType(rewriter.getContext());
rewriter.replaceOpWithNewOp<func::CallOp>(alloc, TypeRange{qubitTy},
qirQubitAllocate, ValueRange{});
return success();
}
// Create a QIR call to allocate the qubits.
StringRef qirQubitArrayAllocate = cudaq::opt::QIRArrayQubitAllocateArray;
Type arrayQubitTy = M::getArrayType(rewriter.getContext());
// AllocaOp could have a size operand, or the size could be compile time
// known and encoded in the veq return type.
Value sizeOperand;
auto loc = alloc.getLoc();
if (adaptor.getOperands().empty()) {
auto type = alloc.getType().cast<quake::VeqType>();
if (!type.hasSpecifiedSize())
return failure();
auto constantSize = type.getSize();
sizeOperand =
rewriter.create<arith::ConstantIntOp>(loc, constantSize, 64);
} else {
sizeOperand = adaptor.getOperands().front();
auto sizeOpTy = cast<IntegerType>(sizeOperand.getType());
if (sizeOpTy.getWidth() < 64)
sizeOperand = rewriter.create<cudaq::cc::CastOp>(
loc, rewriter.getI64Type(), sizeOperand,
cudaq::cc::CastOpMode::Unsigned);
else if (sizeOpTy.getWidth() > 64)
sizeOperand = rewriter.create<cudaq::cc::CastOp>(
loc, rewriter.getI64Type(), sizeOperand);
}
// Replace the AllocaOp with the QIR call.
rewriter.replaceOpWithNewOp<func::CallOp>(alloc, TypeRange{arrayQubitTy},
qirQubitArrayAllocate,
ValueRange{sizeOperand});
return success();
}
};
template <typename M>
struct AllocaOpToIntRewrite : public OpConversionPattern<quake::AllocaOp> {
using OpConversionPattern::OpConversionPattern;
// Precondition: every allocation must have been annotated with a starting
// index by the preparation phase.
LogicalResult
matchAndRewrite(quake::AllocaOp alloc, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
if (!alloc->hasAttr(cudaq::opt::StartingOffsetAttrName))
return alloc.emitOpError("allocation must be annotated.");
auto loc = alloc.getLoc();
// If this alloc is just returning a qubit, so just replace it with the
// attribute.
Type ty = alloc.getType();
if (!ty)
return alloc.emitOpError("quake alloca is malformed");
auto startingOffsetAttr =
alloc->getAttr(cudaq::opt::StartingOffsetAttrName);
auto startingOffset = cast<IntegerAttr>(startingOffsetAttr).getInt();
// In the case this is allocating a single qubit, we can just substitute
// the startingIndex as the qubit value. Voila!
if (auto resultType = dyn_cast<quake::RefType>(ty)) {
Value index =
rewriter.create<arith::ConstantIntOp>(loc, startingOffset, 64);
auto qubitTy = M::getQubitType(rewriter.getContext());
rewriter.replaceOpWithNewOp<cudaq::cc::CastOp>(alloc, qubitTy, index);
return success();
}
auto veqTy = dyn_cast<quake::VeqType>(ty);
if (!veqTy)
return alloc.emitOpError("quake alloca must be a veq");
if (!veqTy.hasSpecifiedSize())
return alloc.emitOpError("quake alloca must be a veq with constant size");
// Otherwise, the allocation is of a sequence of qubits. Here, we allocate a
// constant array value with the qubit integral values in an ascending
// sequence. These will be accessed by extract_value or used collectively.
auto *ctx = rewriter.getContext();
const std::int64_t veqSize = veqTy.getSize();
auto arrTy = cudaq::cc::ArrayType::get(ctx, rewriter.getI64Type(), veqSize);
SmallVector<std::int64_t> data;
for (std::int64_t i = 0; i < veqSize; ++i)
data.emplace_back(startingOffset + i);
auto arr = rewriter.create<cudaq::cc::ConstantArrayOp>(
loc, arrTy, rewriter.getI64ArrayAttr(data));
Type qirArrTy = M::getArrayType(rewriter.getContext());
rewriter.replaceOpWithNewOp<cudaq::codegen::MaterializeConstantArrayOp>(
alloc, qirArrTy, arr);
return success();
}
};
struct MaterializeConstantArrayOpRewrite
: public OpConversionPattern<cudaq::codegen::MaterializeConstantArrayOp> {
using OpConversionPattern::OpConversionPattern;
// Rewrite this operation into a stack allocation and storing the array value
// to that stack slot.
// TODO: it is more efficient to use a global constant, which is done by the
// pass `globalize-array-values`.
LogicalResult
matchAndRewrite(cudaq::codegen::MaterializeConstantArrayOp mca,
OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto loc = mca.getLoc();
auto arr = adaptor.getConstArray();
auto veqSize = cast<cudaq::cc::ArrayType>(arr.getType()).getSize();
Value stackObj = cudaq::opt::factory::createTemporary(
loc, rewriter, rewriter.getI64Type(), veqSize);
rewriter.create<cudaq::cc::StoreOp>(loc, arr, stackObj);
auto ty = mca.getType();
rewriter.replaceOpWithNewOp<cudaq::cc::CastOp>(mca, ty, stackObj);
return success();
}
};
template <typename M, typename OP>
struct QubitHelperConversionPattern : public OpConversionPattern<OP> {
using Base = OpConversionPattern<OP>;
using Base::Base;
Value wrapQubitAsArray(Location loc, ConversionPatternRewriter &rewriter,
Value val) const {
Type qubitTy = M::getQubitType(rewriter.getContext());
if (val.getType() != qubitTy)
return val;
// Create a QIR array container of 1 element.
auto ptrTy = cudaq::cc::PointerType::get(rewriter.getNoneType());
Value sizeofPtrVal =
rewriter.create<cudaq::cc::SizeOfOp>(loc, rewriter.getI32Type(), ptrTy);
Value one = rewriter.create<arith::ConstantIntOp>(loc, 1, 64);
Type arrayTy = M::getArrayType(rewriter.getContext());
auto newArr = rewriter.create<func::CallOp>(
loc, TypeRange{arrayTy}, cudaq::opt::QIRArrayCreateArray,
ArrayRef<Value>{sizeofPtrVal, one});
Value result = newArr.getResult(0);
// Get a pointer to element 0.
Value zero = rewriter.create<arith::ConstantIntOp>(loc, 0, 64);
auto ptrQubitTy = cudaq::cc::PointerType::get(qubitTy);
auto elePtr = rewriter.create<func::CallOp>(
loc, TypeRange{ptrQubitTy}, cudaq::opt::QIRArrayGetElementPtr1d,
ArrayRef<Value>{result, zero});
// Write the qubit into the array at position 0.
auto castVal = rewriter.create<cudaq::cc::CastOp>(loc, qubitTy, val);
Value addr = elePtr.getResult(0);
rewriter.create<cudaq::cc::StoreOp>(loc, castVal, addr);
return result;
}
};
template <typename M>
struct ConcatOpRewrite
: public QubitHelperConversionPattern<M, quake::ConcatOp> {
using Base = QubitHelperConversionPattern<M, quake::ConcatOp>;
using Base::Base;
// For this rewrite, we walk the list of operands (if any) and for each
// operand, $o$, we ensure $o$ is already of type QIR array or convert $o$ to
// the array type using QIR functions. Then, we walk the list and pairwise
// concatenate each operand. First, take $c$ to be $o_0$ and then update $c$
// to be the concat of the previous $c$ and $o_i \forall i \in \{ 1..N \}$.
// This algorithm will generate a linear number of concat calls for the number
// of operands.
LogicalResult
matchAndRewrite(quake::ConcatOp concat, Base::OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
if (adaptor.getOperands().empty()) {
rewriter.eraseOp(concat);
return success();
}
auto loc = concat.getLoc();
Type arrayTy = M::getArrayType(rewriter.getContext());
Value firstOperand = adaptor.getOperands().front();
Value resultArray = Base::wrapQubitAsArray(loc, rewriter, firstOperand);
for (auto next : adaptor.getOperands().drop_front()) {
Value wrapNext = Base::wrapQubitAsArray(loc, rewriter, next);
auto appended = rewriter.create<func::CallOp>(
loc, arrayTy, cudaq::opt::QIRArrayConcatArray,
ArrayRef<Value>{resultArray, wrapNext});
resultArray = appended.getResult(0);
}
rewriter.replaceOp(concat, resultArray);
return success();
}
};
struct DeallocOpRewrite : public OpConversionPattern<quake::DeallocOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::DeallocOp dealloc, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto ty = dealloc.getReference().getType();
StringRef qirFuncName = isa<quake::VeqType>(ty)
? cudaq::opt::QIRArrayQubitReleaseArray
: cudaq::opt::QIRArrayQubitReleaseQubit;
rewriter.replaceOpWithNewOp<func::CallOp>(dealloc, TypeRange{}, qirFuncName,
adaptor.getReference());
return success();
}
};
struct DeallocOpErase : public OpConversionPattern<quake::DeallocOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::DeallocOp dealloc, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
rewriter.eraseOp(dealloc);
return success();
}
};
struct DiscriminateOpRewrite
: public OpConversionPattern<quake::DiscriminateOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::DiscriminateOp disc, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto loc = disc.getLoc();
Value m = adaptor.getMeasurement();
auto i1PtrTy = cudaq::cc::PointerType::get(rewriter.getI1Type());
auto cast = rewriter.create<cudaq::cc::CastOp>(loc, i1PtrTy, m);
rewriter.replaceOpWithNewOp<cudaq::cc::LoadOp>(disc, cast);
return success();
}
};
template <typename M>
struct DiscriminateOpToCallRewrite
: public OpConversionPattern<quake::DiscriminateOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::DiscriminateOp disc, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
if constexpr (M::discriminateToClassical) {
rewriter.replaceOpWithNewOp<func::CallOp>(disc, rewriter.getI1Type(),
cudaq::opt::QIRReadResultBody,
adaptor.getOperands());
} else {
rewriter.replaceOpWithNewOp<cudaq::cc::PoisonOp>(disc,
rewriter.getI1Type());
}
return success();
}
};
template <typename M>
struct ExtractRefOpRewrite : public OpConversionPattern<quake::ExtractRefOp> {
using OpConversionPattern::OpConversionPattern;
// There are two cases depending on which flavor of QIR is being generated.
// For full QIR, we need to generate calls to QIR functions to select the
// qubit from a QIR array.
// For the profile QIRs, we replace this with a `cc.extract_value` operation,
// which will be canonicalized into a constant.
LogicalResult
matchAndRewrite(quake::ExtractRefOp extract, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto loc = extract.getLoc();
auto veq = adaptor.getVeq();
auto i64Ty = rewriter.getI64Type();
Value index;
if (!adaptor.getIndex()) {
index = rewriter.create<arith::ConstantIntOp>(
loc, extract.getConstantIndex(), 64);
} else {
index = adaptor.getIndex();
if (index.getType().isIntOrFloat()) {
if (cast<IntegerType>(index.getType()).getWidth() < 64)
index = rewriter.create<cudaq::cc::CastOp>(
loc, i64Ty, index, cudaq::cc::CastOpMode::Unsigned);
else if (cast<IntegerType>(index.getType()).getWidth() > 64)
index = rewriter.create<cudaq::cc::CastOp>(loc, i64Ty, index);
}
}
auto qubitTy = M::getQubitType(rewriter.getContext());
if (auto mca =
veq.getDefiningOp<cudaq::codegen::MaterializeConstantArrayOp>()) {
// This is the profile QIR case.
auto ext = rewriter.create<cudaq::cc::ExtractValueOp>(
loc, i64Ty, mca.getConstArray(), index);
rewriter.replaceOpWithNewOp<cudaq::cc::CastOp>(extract, qubitTy, ext);
return success();
}
// Otherwise, this must be full QIR.
auto call = rewriter.create<func::CallOp>(
loc, cudaq::cc::PointerType::get(qubitTy),
cudaq::opt::QIRArrayGetElementPtr1d, ArrayRef<Value>{veq, index});
rewriter.replaceOpWithNewOp<cudaq::cc::LoadOp>(extract, call.getResult(0));
return success();
}
};
struct GetMemberOpRewrite : public OpConversionPattern<quake::GetMemberOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::GetMemberOp member, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto toTy = getTypeConverter()->convertType(member.getType());
std::int32_t position = adaptor.getIndex();
rewriter.replaceOpWithNewOp<cudaq::cc::ExtractValueOp>(
member, toTy, adaptor.getStruq(), position);
return success();
}
};
struct VeqSizeOpRewrite : public OpConversionPattern<quake::VeqSizeOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::VeqSizeOp veqsize, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<func::CallOp>(
veqsize, TypeRange{veqsize.getType()}, cudaq::opt::QIRArrayGetSize,
adaptor.getOperands());
return success();
}
};
struct MakeStruqOpRewrite : public OpConversionPattern<quake::MakeStruqOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::MakeStruqOp mkstruq, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto loc = mkstruq.getLoc();
auto *ctx = rewriter.getContext();
auto toTy = getTypeConverter()->convertType(mkstruq.getType());
Value result = rewriter.create<cudaq::cc::UndefOp>(loc, toTy);
std::int64_t count = 0;
for (auto op : adaptor.getOperands()) {
auto off = DenseI64ArrayAttr::get(ctx, ArrayRef<std::int64_t>{count});
result =
rewriter.create<cudaq::cc::InsertValueOp>(loc, toTy, result, op, off);
count++;
}
rewriter.replaceOp(mkstruq, result);
return success();
}
};
template <typename M>
struct QmemRAIIOpRewrite : public OpConversionPattern<cudaq::codegen::RAIIOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(cudaq::codegen::RAIIOp raii, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto loc = raii.getLoc();
auto arrayTy = M::getArrayType(rewriter.getContext());
// Get the CC Pointer for the state
auto ccState = adaptor.getInitState();
// Inspect the element type of the complex data, need to
// know if its f32 or f64
Type eleTy = raii.getInitElementType();
if (auto elePtrTy = dyn_cast<cudaq::cc::PointerType>(eleTy))
eleTy = elePtrTy.getElementType();
if (auto arrayTy = dyn_cast<cudaq::cc::ArrayType>(eleTy))
eleTy = arrayTy.getElementType();
bool fromComplex = false;
if (auto complexTy = dyn_cast<ComplexType>(eleTy)) {
fromComplex = true;
eleTy = complexTy.getElementType();
}
// Cascade to set functionName.
StringRef functionName;
Type ptrTy;
if (isa<cudaq::cc::StateType>(eleTy)) {
functionName = cudaq::opt::QIRArrayQubitAllocateArrayWithCudaqStatePtr;
ptrTy = cudaq::cc::PointerType::get(
cudaq::cc::StateType::get(rewriter.getContext()));
} else if (eleTy == rewriter.getF64Type()) {
if (fromComplex) {
functionName = cudaq::opt::QIRArrayQubitAllocateArrayWithStateComplex64;
ptrTy = cudaq::cc::PointerType::get(
ComplexType::get(rewriter.getF64Type()));
} else {
functionName = cudaq::opt::QIRArrayQubitAllocateArrayWithStateFP64;
ptrTy = cudaq::cc::PointerType::get(rewriter.getF64Type());
}
} else if (eleTy == rewriter.getF32Type()) {
if (fromComplex) {
functionName = cudaq::opt::QIRArrayQubitAllocateArrayWithStateComplex32;
ptrTy = cudaq::cc::PointerType::get(
ComplexType::get(rewriter.getF32Type()));
} else {
functionName = cudaq::opt::QIRArrayQubitAllocateArrayWithStateFP32;
ptrTy = cudaq::cc::PointerType::get(rewriter.getF32Type());
}
}
if (functionName.empty())
return raii.emitOpError("initialize state has an invalid element type.");
assert(ptrTy && "argument pointer type must be set");
// Get the size of the qubit register
Type allocTy = adaptor.getAllocType();
auto i64Ty = rewriter.getI64Type();
Value sizeOperand;
if (!adaptor.getAllocSize()) {
auto type = cast<quake::VeqType>(allocTy);
auto constantSize = type.getSize();
sizeOperand =
rewriter.create<arith::ConstantIntOp>(loc, constantSize, 64);
} else {
sizeOperand = adaptor.getAllocSize();
auto sizeTy = cast<IntegerType>(sizeOperand.getType());
if (sizeTy.getWidth() < 64)
sizeOperand = rewriter.create<cudaq::cc::CastOp>(
loc, i64Ty, sizeOperand, cudaq::cc::CastOpMode::Unsigned);
else if (sizeTy.getWidth() > 64)
sizeOperand =
rewriter.create<cudaq::cc::CastOp>(loc, i64Ty, sizeOperand);
}
// Call the allocation function
Value casted = rewriter.create<cudaq::cc::CastOp>(loc, ptrTy, ccState);
rewriter.replaceOpWithNewOp<func::CallOp>(
raii, arrayTy, functionName, ArrayRef<Value>{sizeOperand, casted});
return success();
}
};
struct RelaxSizeOpErase : public OpConversionPattern<quake::RelaxSizeOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::RelaxSizeOp relax, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOp(relax, relax.getInputVec());
return success();
}
};
template <typename M>
struct SubveqOpRewrite : public OpConversionPattern<quake::SubVeqOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::SubVeqOp subveq, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto loc = subveq.getLoc();
auto lowArg = [&]() -> Value {
if (!adaptor.getLower())
return rewriter.create<arith::ConstantIntOp>(loc, adaptor.getRawLower(),
64);
return adaptor.getLower();
}();
auto highArg = [&]() -> Value {
if (!adaptor.getUpper())
return rewriter.create<arith::ConstantIntOp>(loc, adaptor.getRawUpper(),
64);
return adaptor.getUpper();
}();
auto i64Ty = rewriter.getI64Type();
auto extend = [&](Value &v) -> Value {
if (auto intTy = dyn_cast<IntegerType>(v.getType())) {
if (intTy.getWidth() < 64)
return rewriter.create<cudaq::cc::CastOp>(
loc, i64Ty, v, cudaq::cc::CastOpMode::Unsigned);
if (intTy.getWidth() > 64)
return rewriter.create<cudaq::cc::CastOp>(loc, i64Ty, v);
}
return v;
};
lowArg = extend(lowArg);
highArg = extend(highArg);
Value inArr = adaptor.getVeq();
auto i32Ty = rewriter.getI32Type();
Value one32 = rewriter.create<arith::ConstantIntOp>(loc, 1, i32Ty);
Value one64 = rewriter.create<arith::ConstantIntOp>(loc, 1, i64Ty);
auto arrayTy = M::getArrayType(rewriter.getContext());
rewriter.replaceOpWithNewOp<func::CallOp>(
subveq, arrayTy, cudaq::opt::QIRArraySlice,
ArrayRef<Value>{inArr, one32, lowArg, one64, highArg});
return success();
}
};
//===----------------------------------------------------------------------===//
// Custom handing of irregular quantum gates.
//===----------------------------------------------------------------------===//
template <typename M>
struct CustomUnitaryOpPattern
: public QubitHelperConversionPattern<M, quake::CustomUnitarySymbolOp> {
using Base = QubitHelperConversionPattern<M, quake::CustomUnitarySymbolOp>;
using Base::Base;
LogicalResult
matchAndRewrite(quake::CustomUnitarySymbolOp unitary, Base::OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
if (!unitary.getParameters().empty())
return unitary.emitOpError(
"Parameterized custom operations not yet supported.");
auto loc = unitary.getLoc();
auto arrayTy = M::getArrayType(rewriter.getContext());
if (adaptor.getTargets().empty())
return unitary.emitOpError("Custom operations must have targets.");
// Concat all the targets into an array.
auto targetArray =
Base::wrapQubitAsArray(loc, rewriter, adaptor.getTargets().front());
for (auto next : adaptor.getTargets().drop_front()) {
auto wrapNext = Base::wrapQubitAsArray(loc, rewriter, next);
auto result = rewriter.create<func::CallOp>(
loc, arrayTy, cudaq::opt::QIRArrayConcatArray,
ArrayRef<Value>{targetArray, wrapNext});
targetArray = result.getResult(0);
}
// Concat all the controls (if any) into an array.
Value controlArray;
if (adaptor.getControls().empty()) {
// Use a nullptr for when 0 control qubits are present.
Value zero = rewriter.create<arith::ConstantIntOp>(loc, 0, 64);
controlArray = rewriter.create<cudaq::cc::CastOp>(loc, arrayTy, zero);
} else {
controlArray =
Base::wrapQubitAsArray(loc, rewriter, adaptor.getControls().front());
for (auto next : adaptor.getControls().drop_front()) {
auto wrapNext = Base::wrapQubitAsArray(loc, rewriter, next);
auto result = rewriter.create<func::CallOp>(
loc, arrayTy, cudaq::opt::QIRArrayConcatArray,
ArrayRef<Value>{controlArray, wrapNext});
controlArray = result.getResult(0);
}
}
// Fetch the unitary matrix generator for this custom operation
auto generatorSym = unitary.getGenerator();
StringRef generatorName = generatorSym.getRootReference();
const auto customOpName = extractCustomNamePart(generatorName);
// Create a global string for the unitary name.
auto nameOp = createGlobalCString(unitary, loc, rewriter, customOpName);
auto complex64Ty = ComplexType::get(rewriter.getF64Type());
auto complex64PtrTy = cudaq::cc::PointerType::get(complex64Ty);
auto globalObj = cast<cudaq::cc::GlobalOp>(
unitary->getParentOfType<ModuleOp>().lookupSymbol(generatorName));
auto addrOp = rewriter.create<cudaq::cc::AddressOfOp>(
loc, globalObj.getType(), generatorName);
auto unitaryData =
rewriter.create<cudaq::cc::CastOp>(loc, complex64PtrTy, addrOp);
StringRef functionName =
unitary.isAdj() ? cudaq::opt::QIRCustomAdjOp : cudaq::opt::QIRCustomOp;
rewriter.replaceOpWithNewOp<func::CallOp>(
unitary, TypeRange{}, functionName,
ArrayRef<Value>{unitaryData, controlArray, targetArray, nameOp});
return success();
}
// IMPORTANT: this must match the logic to generate global data globalName =
// f'{nvqppPrefix}{opName}_generator_{numTargets}.rodata'
std::string extractCustomNamePart(StringRef generatorName) const {
auto globalName = generatorName.str();
if (globalName.starts_with(cudaq::runtime::cudaqGenPrefixName)) {
globalName = globalName.substr(cudaq::runtime::cudaqGenPrefixLength);
const size_t pos = globalName.find("_generator");
if (pos != std::string::npos)
return globalName.substr(0, pos);
}
return {};
}
};
struct ExpPauliOpPattern : public OpConversionPattern<quake::ExpPauliOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::ExpPauliOp pauli, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto loc = pauli.getLoc();
SmallVector<Value> operands = adaptor.getOperands();
// First need to check the type of the Pauli word. We expect
// a pauli_word directly `{i8*,i64}` or a string literal
// `ptr<i8>`. If it is a string literal, we need to map it to
// a pauli word.
auto pauliWord = operands.back();
auto i8PtrTy = cudaq::cc::PointerType::get(rewriter.getI8Type());
if (auto ptrTy = dyn_cast<cudaq::cc::PointerType>(pauliWord.getType())) {
// Make sure we have the right types to extract the
// length of the string literal
auto arrayTy = dyn_cast<cudaq::cc::ArrayType>(ptrTy.getElementType());
if (!arrayTy)
return pauli.emitOpError(
"exp_pauli string literal must have ptr<array<i8 x N> type.");
if (!arrayTy.getSize())
return pauli.emitOpError("string literal may not be empty.");
// We must create the {i8*, i64} struct from the string literal
SmallVector<Type> structTys{i8PtrTy, rewriter.getI64Type()};
auto structTy =
cudaq::cc::StructType::get(rewriter.getContext(), structTys);
// Allocate the char span struct
Value alloca =
cudaq::opt::factory::createTemporary(loc, rewriter, structTy);
// Convert the number of elements to a constant op.
auto size =
rewriter.create<arith::ConstantIntOp>(loc, arrayTy.getSize() - 1, 64);
// Set the string literal data
auto castedPauli =
rewriter.create<cudaq::cc::CastOp>(loc, i8PtrTy, pauliWord);
auto strPtr = rewriter.create<cudaq::cc::ComputePtrOp>(
loc, cudaq::cc::PointerType::get(i8PtrTy), alloca,
ArrayRef<cudaq::cc::ComputePtrArg>{0, 0});
rewriter.create<cudaq::cc::StoreOp>(loc, castedPauli, strPtr);
// Set the integer length
auto intPtr = rewriter.create<cudaq::cc::ComputePtrOp>(
loc, cudaq::cc::PointerType::get(rewriter.getI64Type()), alloca,
ArrayRef<cudaq::cc::ComputePtrArg>{0, 1});
rewriter.create<cudaq::cc::StoreOp>(loc, size, intPtr);
// Cast to raw opaque pointer
auto castedStore =
rewriter.create<cudaq::cc::CastOp>(loc, i8PtrTy, alloca);
operands.back() = castedStore;
rewriter.replaceOpWithNewOp<func::CallOp>(
pauli, TypeRange{}, cudaq::opt::QIRExpPauli, operands);
return success();
}
// Here we know we have a pauli word expressed as `{i8*, i64}`.
// Allocate a stack slot for it and store what we have to that pointer,
// pass the pointer to NVQIR
auto newPauliWord = adaptor.getOperands().back();
auto newPauliWordTy = newPauliWord.getType();
Value alloca =
cudaq::opt::factory::createTemporary(loc, rewriter, newPauliWordTy);
auto castedVar = rewriter.create<cudaq::cc::CastOp>(
loc, cudaq::cc::PointerType::get(newPauliWordTy), alloca);
rewriter.create<cudaq::cc::StoreOp>(loc, newPauliWord, castedVar);
auto castedPauli = rewriter.create<cudaq::cc::CastOp>(loc, i8PtrTy, alloca);
operands.back() = castedPauli;
rewriter.replaceOpWithNewOp<func::CallOp>(
pauli, TypeRange{}, cudaq::opt::QIRExpPauli, operands);
return success();
}
};
template <typename M>
struct MeasurementOpPattern : public OpConversionPattern<quake::MzOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::MzOp mz, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto loc = mz.getLoc();
auto regNameAttr = dyn_cast<StringAttr>(mz.getRegisterNameAttr());
if (!regNameAttr)
return mz.emitOpError("mz operation must have a name.");
if (regNameAttr.getValue().empty())
return mz.emitOpError("mz name may not be an empty string.");
SmallVector<Value> args;
args.append(adaptor.getTargets().begin(), adaptor.getTargets().end());
auto functionName = M::getQIRMeasure();
// Are we using the measurement that returns a result?
if constexpr (M::mzReturnsResultType) {
// Yes, the measurement results the result, so we can use a
// straightforward codegen pattern. Use either the mz or the
// mz_to_register call (with the name as an extra argument) and forward
// the result of the call as the result.
if (mz->getAttr(cudaq::opt::MzAssignedNameAttrName)) {
functionName = cudaq::opt::QIRMeasureToRegister;
auto cstringGlobal =
createGlobalCString(mz, loc, rewriter, regNameAttr.getValue());
args.push_back(cstringGlobal);
}
auto resultTy = M::getResultType(rewriter.getContext());
auto call = rewriter.replaceOpWithNewOp<func::CallOp>(mz, resultTy,
functionName, args);
call->setAttr(cudaq::opt::QIRRegisterNameAttr, regNameAttr);
} else {
// No, the measurement doesn't return any result so use a much more
// convoluted pattern.
// 1. Cast an integer to the result and append it to the mz call. This
// will be the token to identify the result. The value will have been
// attached to the MzOp in preprocessing.
// 2. Call the mz function.
// 3. Call the result_record_output to bind the name, which is not folded
// into the mz call. There is always a name in this case.
auto resultAttr = mz->getAttr(cudaq::opt::ResultIndexAttrName);
std::int64_t annInt = cast<IntegerAttr>(resultAttr).getInt();
Value intVal = rewriter.create<arith::ConstantIntOp>(loc, annInt, 64);
auto resultTy = M::getResultType(rewriter.getContext());
Value res = rewriter.create<cudaq::cc::CastOp>(loc, resultTy, intVal);
args.push_back(res);
auto call =
rewriter.create<func::CallOp>(loc, TypeRange{}, functionName, args);
call->setAttr(cudaq::opt::QIRRegisterNameAttr, regNameAttr);
auto cstringGlobal =
createGlobalCString(mz, loc, rewriter, regNameAttr.getValue());
if constexpr (!M::discriminateToClassical) {
// These QIR profile variants force all record output calls to appear at
// the end. In these variants, control-flow isn't allowed in the final
// LLVM. Therefore, a single basic block is assumed but unchecked here
// as the verifier will raise an error.
rewriter.setInsertionPoint(rewriter.getBlock()->getTerminator());
}
auto recOut = rewriter.create<func::CallOp>(
loc, TypeRange{}, cudaq::opt::QIRRecordOutput,
ArrayRef<Value>{res, cstringGlobal});
recOut->setAttr(cudaq::opt::ResultIndexAttrName, resultAttr);
recOut->setAttr(cudaq::opt::QIRRegisterNameAttr, regNameAttr);
rewriter.replaceOp(mz, res);
}
return success();
}
};
template <typename M>
struct ResetOpPattern : public OpConversionPattern<quake::ResetOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(quake::ResetOp reset, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// Get the reset QIR function name
auto qirFunctionName = M::getQIRReset();
// Replace the quake op with the new call op.
rewriter.replaceOpWithNewOp<func::CallOp>(
reset, TypeRange{}, qirFunctionName, adaptor.getOperands());
return success();
}
};
struct AnnotateKernelsWithMeasurementStringsPattern
: public OpConversionPattern<func::FuncOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(func::FuncOp func, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
constexpr const char PassthroughAttr[] = "passthrough";
if (!func->hasAttr(cudaq::kernelAttrName))
return failure();
if (!func->hasAttr(PassthroughAttr))
return failure();
auto passthru = cast<ArrayAttr>(func->getAttr(PassthroughAttr));
for (auto a : passthru) {
if (auto strArrAttr = dyn_cast<ArrayAttr>(a)) {
auto strAttr = dyn_cast<StringAttr>(strArrAttr[0]);
if (!strAttr)
continue;
if (strAttr.getValue() == cudaq::opt::QIROutputNamesAttrName)
return failure();
}
}
// Lambda to help recover an integer value (the QIR qubit or result as an
// integer).
auto recoverIntValue = [&](Value v) -> std::optional<std::size_t> {
auto cast = v.getDefiningOp<cudaq::cc::CastOp>();
if (!cast)
return {};
return cudaq::opt::factory::maybeValueOfIntConstant(cast.getValue());
};
// If we're here, then `func` is a kernel, it has a passthrough attribute,
// and the passthrough attribute does *not* have an output names entry.
//
// OUTPUT-NAME-MAP: At this point, we will try to heroically generate the
// output names attribute for the QIR consumer. The content of the attribute
// is a map from results back to pairs of qubits and names. The map is
// encoded in a JSON string. The map is appended to the passthrough
// attribute array.
std::map<std::size_t, std::size_t> measMap;
std::map<std::size_t, std::pair<std::size_t, std::string>> nameMap;
func.walk([&](func::CallOp call) {
auto calleeName = call.getCallee();
if (calleeName == cudaq::opt::QIRMeasureBody) {
auto qubit = recoverIntValue(call.getOperand(0));
auto meas = recoverIntValue(call.getOperand(1));
if (qubit && meas)
measMap[*meas] = *qubit;
} else if (calleeName == cudaq::opt::QIRRecordOutput) {
auto resAttr = call->getAttr(cudaq::opt::ResultIndexAttrName);
std::size_t res = cast<IntegerAttr>(resAttr).getInt();
auto regNameAttr = call->getAttr(cudaq::opt::QIRRegisterNameAttr);
std::string regName = cast<StringAttr>(regNameAttr).getValue().str();
if (measMap.count(res)) {
std::size_t qubit = measMap[res];
nameMap[res] = std::pair{qubit, regName};
}
}
});