forked from NVIDIA/cuda-quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast_bridge.py
More file actions
4153 lines (3626 loc) · 181 KB
/
ast_bridge.py
File metadata and controls
4153 lines (3626 loc) · 181 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. #
# ============================================================================ #
import ast
import hashlib
import graphlib
import sys, os
from typing import Callable
from collections import deque
import numpy as np
from .analysis import FindDepKernelsVisitor
from .utils import globalAstRegistry, globalKernelRegistry, globalRegisteredOperations, nvqppPrefix, mlirTypeFromAnnotation, mlirTypeFromPyType, Color, mlirTypeToPyType, globalRegisteredTypes
from ..mlir.ir import *
from ..mlir.passmanager import *
from ..mlir.dialects import quake, cc
from ..mlir.dialects import builtin, func, arith, math, complex
from ..mlir._mlir_libs._quakeDialects import cudaq_runtime, load_intrinsic, register_all_dialects, gen_vector_of_complex_constant
from .captured_data import CapturedDataStorage
State = cudaq_runtime.State
# This file implements the CUDA-Q Python AST to MLIR conversion.
# It provides a `PyASTBridge` class that implements the `ast.NodeVisitor` type
# to walk the Python AST for a `cudaq.kernel` annotated function and generate
# valid MLIR code using `Quake`, `CC`, `Arith`, and `Math` dialects.
# CC Dialect `ComputePtrOp` in C++ sets the
# dynamic index as `std::numeric_limits<int32_t>::min()`
# (see CCOps.tc line 898). We'll duplicate that
# here by just setting it manually
kDynamicPtrIndex: int = -2147483648
class PyScopedSymbolTable(object):
def __init__(self):
self.symbolTable = deque()
def pushScope(self):
self.symbolTable.append({})
def popScope(self):
self.symbolTable.pop()
def numLevels(self):
return len(self.symbolTable)
def add(self, symbol, value, level=-1):
"""
Add a symbol to the scoped symbol table at any scope level.
"""
self.symbolTable[level][symbol] = value
def __contains__(self, symbol):
for st in reversed(self.symbolTable):
if symbol in st:
return True
return False
def __setitem__(self, symbol, value):
# default to nearest surrounding scope
self.add(symbol, value)
return
def __getitem__(self, symbol):
for st in reversed(self.symbolTable):
if symbol in st:
return st[symbol]
raise RuntimeError(
f"{symbol} is not a valid variable name in this scope.")
def clear(self):
while len(self.symbolTable):
self.symbolTable.pop()
return
class CompilerError(RuntimeError):
"""
Custom exception class for improved error diagnostics.
"""
def __init__(self, *args, **kwargs):
RuntimeError.__init__(self, *args, **kwargs)
class PyASTBridge(ast.NodeVisitor):
"""
The `PyASTBridge` class implements the `ast.NodeVisitor` type to convert a
python function definition (annotated with cudaq.kernel) to an MLIR `ModuleOp`
containing a `func.FuncOp` representative of the original python function but leveraging
the Quake and CC dialects provided by CUDA-Q. This class keeps track of a
MLIR Value stack that is pushed to and popped from during visitation of the
function AST nodes. We leverage the auto-generated MLIR Python bindings for the internal
C++ CUDA-Q dialects to build up the MLIR code.
For kernels that call other kernels, we require that the `ModuleOp` contain the
kernel being called. This is enabled via the `FindDepKernelsVisitor` in the local
analysis module, and is handled by the below `compile_to_mlir` function. For
callable block arguments, we leverage runtime-known callable argument function names
and synthesize them away with an internal C++ MLIR pass.
"""
def __init__(self, capturedDataStorage: CapturedDataStorage, **kwargs):
"""
The constructor. Initializes the `mlir.Value` stack, the `mlir.Context`, and the
`mlir.Module` that we will be building upon. This class keeps track of a
symbol table, which maps variable names to constructed `mlir.Values`.
"""
self.valueStack = deque()
self.knownResultType = kwargs[
'knownResultType'] if 'knownResultType' in kwargs else None
if 'existingModule' in kwargs:
self.module = kwargs['existingModule']
self.ctx = self.module.context
self.loc = Location.unknown(context=self.ctx)
else:
self.ctx = Context()
register_all_dialects(self.ctx)
quake.register_dialect(self.ctx)
cc.register_dialect(self.ctx)
cudaq_runtime.registerLLVMDialectTranslation(self.ctx)
self.loc = Location.unknown(context=self.ctx)
self.module = Module.create(loc=self.loc)
# Create a new captured data storage or use the existing one
# passed from the current kernel decorator.
self.capturedDataStorage = capturedDataStorage
if (self.capturedDataStorage == None):
self.capturedDataStorage = CapturedDataStorage(ctx=self.ctx,
loc=self.loc,
name=None,
module=self.module)
else:
self.capturedDataStorage.setKernelContext(ctx=self.ctx,
loc=self.loc,
name=None,
module=self.module)
# If the driver of this AST bridge instance has indicated
# that there is a return type from analysis on the Python AST,
# then we want to set the known result type so that the
# FuncOp can have it.
if 'returnTypeIsFromPython' in kwargs and kwargs[
'returnTypeIsFromPython'] and self.knownResultType is not None:
self.knownResultType = mlirTypeFromPyType(self.knownResultType,
self.ctx)
self.capturedVars = kwargs[
'capturedVariables'] if 'capturedVariables' in kwargs else {}
self.dependentCaptureVars = {}
self.locationOffset = kwargs[
'locationOffset'] if 'locationOffset' in kwargs else ('', 0)
self.disableEntryPointTag = kwargs[
'disableEntryPointTag'] if 'disableEntryPointTag' in kwargs else False
self.disableNvqppPrefix = kwargs[
'disableNvqppPrefix'] if 'disableNvqppPrefix' in kwargs else False
self.symbolTable = PyScopedSymbolTable()
self.increment = 0
self.buildingEntryPoint = False
self.inForBodyStack = deque()
self.inIfStmtBlockStack = deque()
self.currentAssignVariableName = None
self.walkingReturnNode = False
self.controlNegations = []
self.subscriptPushPointerValue = False
self.verbose = 'verbose' in kwargs and kwargs['verbose']
self.currentNode = None
def emitWarning(self, msg, astNode=None):
"""
Emit a warning, providing the user with source file information and
the offending code.
"""
codeFile = os.path.basename(self.locationOffset[0])
if astNode == None:
astNode = self.currentNode
lineNumber = '' if astNode == None else astNode.lineno + self.locationOffset[
1] - 1
print(Color.BOLD, end='')
msg = codeFile + ":" + str(
lineNumber
) + ": " + Color.YELLOW + "warning: " + Color.END + Color.BOLD + msg + (
"\n\t (offending source -> " + ast.unparse(astNode) + ")" if
hasattr(ast, 'unparse') and astNode is not None else '') + Color.END
print(msg)
def emitFatalError(self, msg, astNode=None):
"""
Emit a fatal error, providing the user with source file information and
the offending code.
"""
codeFile = os.path.basename(self.locationOffset[0])
if astNode == None:
astNode = self.currentNode
lineNumber = '' if astNode == None else astNode.lineno + self.locationOffset[
1] - 1
print(Color.BOLD, end='')
msg = codeFile + ":" + str(
lineNumber
) + ": " + Color.RED + "error: " + Color.END + Color.BOLD + msg + (
"\n\t (offending source -> " + ast.unparse(astNode) + ")" if
hasattr(ast, 'unparse') and astNode is not None else '') + Color.END
raise CompilerError(msg)
def validateArgumentAnnotations(self, astModule):
"""
Utility function for quickly validating that we have
all arguments annotated.
"""
class ValidateArgumentAnnotations(ast.NodeVisitor):
"""
Utility visitor for finding argument annotations
"""
def __init__(self, bridge):
self.bridge = bridge
def visit_FunctionDef(self, node):
for arg in node.args.args:
if arg.annotation == None:
self.bridge.emitFatalError(
'cudaq.kernel functions must have argument type annotations.',
arg)
ValidateArgumentAnnotations(self).visit(astModule)
def getVeqType(self, size=None):
"""
Return a `quake.VeqType`. Pass the size of the `quake.veq` if known.
"""
if size == None:
return quake.VeqType.get(self.ctx)
return quake.VeqType.get(self.ctx, size)
def getRefType(self):
"""
Return a `quake.RefType`.
"""
return quake.RefType.get(self.ctx)
def isQuantumType(self, ty):
"""
Return True if the given type is quantum (is a `VeqType` or `RefType`).
Return False otherwise.
"""
return quake.RefType.isinstance(ty) or quake.VeqType.isinstance(
ty) or quake.StruqType.isinstance(ty)
def isMeasureResultType(self, ty, value):
"""
Return true if the given type is a qubit measurement result type (an i1 type).
"""
if hasattr(value, 'owner') and hasattr(
value.owner,
'name') and not 'quake.discriminate' == value.owner.name:
return False
return IntegerType.isinstance(ty) and ty == IntegerType.get_signless(1)
def getIntegerType(self, width=64):
"""
Return an MLIR `IntegerType` of the given bit width (defaults to 64 bits).
"""
return IntegerType.get_signless(width)
def getIntegerAttr(self, type, value):
"""
Return an MLIR Integer Attribute of the given `IntegerType`.
"""
return IntegerAttr.get(type, value)
def getFloatType(self, width=64):
"""
Return an MLIR float type (single or double precision).
"""
# Note:
# `numpy.float64` is the same as `float` type, with width of 64 bit.
# `numpy.float32` type has width of 32 bit.
return F64Type.get() if width == 64 else F32Type.get()
def getFloatAttr(self, type, value):
"""
Return an MLIR float attribute (single or double precision).
"""
return FloatAttr.get(type, value)
def getConstantFloat(self, value, width=64):
"""
Create a constant float operation and return its MLIR result Value.
Takes as input the concrete float value.
"""
ty = self.getFloatType(width=width)
return self.getConstantFloatWithType(value, ty)
def getConstantFloatWithType(self, value, ty):
"""
Create a constant float operation and return its MLIR result Value.
Takes as input the concrete float value.
"""
return arith.ConstantOp(ty, self.getFloatAttr(ty, value)).result
def getComplexType(self, width=64):
"""
Return an MLIR complex type (single or double precision).
"""
# Note:
# `numpy.complex128` is the same as `complex` type,
# with element width of 64bit (`np.complex64` and `float`)
# `numpy.complex64` type has element type of `np.float32`.
return self.getComplexTypeWithElementType(
self.getFloatType(width=width))
def getComplexTypeWithElementType(self, eTy):
"""
Return an MLIR complex type (single or double precision).
"""
return ComplexType.get(eTy)
def getConstantComplex(self, value, width=64):
"""
Create a constant complex operation and return its MLIR result Value.
Takes as input the concrete complex value.
"""
ty = self.getComplexType(width=width)
return complex.CreateOp(ty,
self.getConstantFloat(value.real, width=width),
self.getConstantFloat(value.imag,
width=width)).result
def getConstantComplexWithElementType(self, value, eTy):
"""
Create a constant complex operation and return its MLIR result Value.
Takes as input the concrete complex value.
"""
ty = self.getComplexTypeWithElementType(eTy)
return complex.CreateOp(ty,
self.getConstantFloatWithType(value.real, eTy),
self.getConstantFloatWithType(value.imag,
eTy)).result
def getConstantInt(self, value, width=64):
"""
Create a constant integer operation and return its MLIR result Value.
Takes as input the concrete integer value. Can specify the integer bit width.
"""
ty = self.getIntegerType(width)
return arith.ConstantOp(ty, self.getIntegerAttr(ty, value)).result
def promoteOperandType(self, ty, operand):
if ComplexType.isinstance(ty):
complexType = ComplexType(ty)
floatType = complexType.element_type
if ComplexType.isinstance(operand.type):
otherComplexType = ComplexType(operand.type)
otherFloatType = otherComplexType.element_type
if (floatType != otherFloatType):
real = self.promoteOperandType(floatType,
complex.ReOp(operand).result)
imag = self.promoteOperandType(floatType,
complex.ImOp(operand).result)
operand = complex.CreateOp(complexType, real, imag).result
else:
real = self.promoteOperandType(floatType, operand)
imag = self.getConstantFloatWithType(0.0, floatType)
operand = complex.CreateOp(complexType, real, imag).result
if F64Type.isinstance(ty):
if F32Type.isinstance(operand.type):
operand = arith.ExtFOp(ty, operand).result
if IntegerType.isinstance(operand.type):
operand = arith.SIToFPOp(ty, operand).result
if F32Type.isinstance(ty):
if F64Type.isinstance(operand.type):
operand = arith.TruncFOp(ty, operand).result
if IntegerType.isinstance(operand.type):
operand = arith.SIToFPOp(ty, operand).result
return operand
def simulationPrecision(self):
"""
Return precision for the current simulation backend,
see `cudaq_runtime.SimulationPrecision`.
"""
target = cudaq_runtime.get_target()
return target.get_precision()
def simulationDType(self):
"""
Return the data type for the current simulation backend,
either `numpy.complex128` or `numpy.complex64`.
"""
if self.simulationPrecision() == cudaq_runtime.SimulationPrecision.fp64:
return self.getComplexType(width=64)
return self.getComplexType(width=32)
def pushValue(self, value):
"""
Push an MLIR Value onto the stack for usage in a subsequent AST node visit method.
"""
if self.verbose:
print('{}push {}'.format(self.increment * ' ', value))
self.increment += 2
self.valueStack.append(value)
def popValue(self):
"""
Pop an MLIR Value from the stack.
"""
val = self.valueStack.pop()
self.increment -= 2
if self.verbose:
print('{}pop {}'.format(self.increment * ' ', val))
return val
def pushForBodyStack(self, bodyBlockArgs):
"""
Indicate that we are entering a for loop body block.
"""
self.inForBodyStack.append(bodyBlockArgs)
def popForBodyStack(self):
"""
Indicate that we have left a for loop body block.
"""
self.inForBodyStack.pop()
def pushIfStmtBlockStack(self):
"""
Indicate that we are entering an if statement then or else block.
"""
self.inIfStmtBlockStack.append(0)
def popIfStmtBlockStack(self):
"""
Indicate that we have just left an if statement then
or else block.
"""
self.inIfStmtBlockStack.pop()
def isInForBody(self):
"""
Return True if the current insertion point is within
a for body block.
"""
return len(self.inForBodyStack) > 0
def isInIfStmtBlock(self):
"""
Return True if the current insertion point is within
an if statement then or else block.
"""
return len(self.inIfStmtBlockStack) > 0
def hasTerminator(self, block):
"""
Return True if the given Block has a Terminator operation.
"""
if len(block.operations) > 0:
return cudaq_runtime.isTerminator(
block.operations[len(block.operations) - 1])
return False
def isArithmeticType(self, type):
"""
Return True if the given type is an integer, float, or complex type.
"""
return IntegerType.isinstance(type) or F64Type.isinstance(
type) or F32Type.isinstance(type) or ComplexType.isinstance(type)
def ifPointerThenLoad(self, value):
"""
If the given value is of pointer type, load the pointer
and return that new value.
"""
if cc.PointerType.isinstance(value.type):
return cc.LoadOp(value).result
return value
def ifNotPointerThenStore(self, value):
"""
If the given value is not of a pointer type, allocate a
slot on the stack, store the the value in the slot, and
return the slot address.
"""
if not cc.PointerType.isinstance(value.type):
slot = cc.AllocaOp(cc.PointerType.get(self.ctx, value.type),
TypeAttr.get(value.type)).result
cc.StoreOp(value, slot)
return slot
return value
def __createStdvecWithKnownValues(self, size, listElementValues):
# Turn this List into a StdVec<T>
arrSize = self.getConstantInt(size)
arrTy = cc.ArrayType.get(self.ctx, listElementValues[0].type)
alloca = cc.AllocaOp(cc.PointerType.get(self.ctx, arrTy),
TypeAttr.get(listElementValues[0].type),
seqSize=arrSize).result
for i, v in enumerate(listElementValues):
eleAddr = cc.ComputePtrOp(
cc.PointerType.get(self.ctx, listElementValues[0].type), alloca,
[self.getConstantInt(i)],
DenseI32ArrayAttr.get([kDynamicPtrIndex],
context=self.ctx)).result
cc.StoreOp(v, eleAddr)
vecTy = listElementValues[0].type
if cc.PointerType.isinstance(vecTy):
vecTy = cc.PointerType.getElementType(vecTy)
return cc.StdvecInitOp(cc.StdvecType.get(self.ctx, vecTy), alloca,
arrSize).result
def getStructMemberIdx(self, memberName, structTy):
"""
For the given struct type and member variable name, return
the index of the variable in the struct and the specific
MLIR type for the variable.
"""
if cc.StructType.isinstance(structTy):
structName = cc.StructType.getName(structTy)
else:
structName = quake.StruqType.getName(structTy)
structIdx = None
_, userType = globalRegisteredTypes[structName]
for i, (k, _) in enumerate(userType.items()):
if k == memberName:
structIdx = i
break
if structIdx == None:
self.emitFatalError(
f'Invalid struct member: {structName}.{memberName} (members={[k for k,_ in userType.items()]})'
)
return structIdx, mlirTypeFromPyType(userType[memberName], self.ctx)
# Create a new vector with source elements converted to the target element type if needed.
def __copyVectorAndCastElements(self, source, targetEleType):
if not cc.PointerType.isinstance(source.type):
if cc.StdvecType.isinstance(source.type):
# Exit early if no copy is needed to avoid an unneeded store.
sourceEleType = cc.StdvecType.getElementType(source.type)
if (sourceEleType == targetEleType):
return source
sourcePtr = source
if not cc.PointerType.isinstance(sourcePtr.type):
sourcePtr = self.ifNotPointerThenStore(sourcePtr)
sourceType = cc.PointerType.getElementType(sourcePtr.type)
if not cc.StdvecType.isinstance(sourceType):
raise RuntimeError(
f"expected vector type in __copyVectorAndCastElements but received {sourceType}"
)
sourceEleType = cc.StdvecType.getElementType(sourceType)
if (sourceEleType == targetEleType):
return sourcePtr
sourceArrType = cc.ArrayType.get(self.ctx, sourceEleType)
sourceElePtrTy = cc.PointerType.get(self.ctx, sourceEleType)
sourceArrElePtrTy = cc.PointerType.get(self.ctx, sourceArrType)
sourceValue = self.ifPointerThenLoad(sourcePtr)
sourceDataPtr = cc.StdvecDataOp(sourceArrElePtrTy, sourceValue).result
sourceSize = cc.StdvecSizeOp(self.getIntegerType(), sourceValue).result
targetElePtrType = cc.PointerType.get(self.ctx, targetEleType)
targetTy = cc.ArrayType.get(self.ctx, targetEleType)
targetArrElePtrTy = cc.PointerType.get(self.ctx, targetTy)
targetVecTy = cc.StdvecType.get(self.ctx, targetEleType)
targetPtr = cc.AllocaOp(targetArrElePtrTy,
TypeAttr.get(targetEleType),
seqSize=sourceSize).result
rawIndex = DenseI32ArrayAttr.get([kDynamicPtrIndex], context=self.ctx)
def bodyBuilder(iterVar):
eleAddr = cc.ComputePtrOp(sourceElePtrTy, sourceDataPtr, [iterVar],
rawIndex).result
loadedEle = cc.LoadOp(eleAddr).result
castedEle = self.promoteOperandType(targetEleType, loadedEle)
targetEleAddr = cc.ComputePtrOp(targetElePtrType, targetPtr,
[iterVar], rawIndex).result
cc.StoreOp(castedEle, targetEleAddr)
self.createInvariantForLoop(sourceSize, bodyBuilder)
return cc.StdvecInitOp(targetVecTy, targetPtr, sourceSize).result
def __insertDbgStmt(self, value, dbgStmt):
"""
Insert a debug print out statement if the programmer requested. Handles
statements like `cudaq.dbg.ast.print_i64(i)`.
"""
value = self.ifPointerThenLoad(value)
printFunc = None
printStr = '[cudaq-ast-dbg] '
argsTy = [cc.PointerType.get(self.ctx, self.getIntegerType(8))]
if dbgStmt == 'print_i64':
if not IntegerType.isinstance(value.type):
self.emitFatalError(
f"print_i64 requested, but value is not of integer type (type was {value.type})."
)
currentST = SymbolTable(self.module.operation)
argsTy += [self.getIntegerType()]
# If `printf` is not in the module, or if it is but the last argument type is not an integer
# then we have to add it
if not 'print_i64' in currentST or not IntegerType.isinstance(
currentST['print_i64'].type.inputs[-1]):
with InsertionPoint(self.module.body):
printOp = func.FuncOp('print_i64', (argsTy, []))
printOp.sym_visibility = StringAttr.get("private")
currentST = SymbolTable(self.module.operation)
printFunc = currentST['print_i64']
printStr += '%ld\n'
elif dbgStmt == 'print_f64':
if not F64Type.isinstance(value.type):
self.emitFatalError(
f"print_f64 requested, but value is not of float type (type was {value.type})."
)
currentST = SymbolTable(self.module.operation)
argsTy += [self.getFloatType()]
# If `printf` is not in the module, or if it is but the last argument type is not an float
# then we have to add it
if not 'print_f64' in currentST or not F64Type.isinstance(
currentST['print_f64'].type.inputs[-1]):
with InsertionPoint(self.module.body):
printOp = func.FuncOp('print_f64', (argsTy, []))
printOp.sym_visibility = StringAttr.get("private")
currentST = SymbolTable(self.module.operation)
printFunc = currentST['print_f64']
printStr += '%.12lf\n'
else:
raise self.emitFatalError(
f"Invalid cudaq.dbg.ast statement - {dbgStmt}")
strLitTy = cc.PointerType.get(
self.ctx,
cc.ArrayType.get(self.ctx, self.getIntegerType(8),
len(printStr) + 1))
strLit = cc.CreateStringLiteralOp(strLitTy,
StringAttr.get(printStr)).result
strLit = cc.CastOp(cc.PointerType.get(self.ctx, self.getIntegerType(8)),
strLit).result
func.CallOp(printFunc, [strLit, value])
return
def convertArithmeticToSuperiorType(self, values, type):
"""
Assuming all values provided are arithmetic, convert each one to the
provided superior type. Float is superior to integer and complex is
superior to float (superior implies the inferior type can can be converted to the
superior type)
"""
retValues = []
for v in values:
retValues.append(self.promoteOperandType(type, v))
return retValues
def isQuantumStructType(self, ty):
"""
Return True if the given struct type has only quantum member variables.
"""
return quake.StruqType.isinstance(ty)
def mlirTypeFromAnnotation(self, annotation):
"""
Return the MLIR Type corresponding to the given kernel function argument type annotation.
Throws an exception if the programmer did not annotate function argument types.
"""
msg = None
try:
return mlirTypeFromAnnotation(annotation, self.ctx, raiseError=True)
except RuntimeError as e:
msg = str(e)
if msg is not None:
self.emitFatalError(msg, annotation)
def argumentsValidForFunction(self, values, functionTy):
return False not in [
ty == values[i].type
for i, ty in enumerate(FunctionType(functionTy).inputs)
]
def checkControlAndTargetTypes(self, controls, targets):
"""
Loop through the provided control and target qubit values and
assert that they are of quantum type. Emit a fatal error if not.
"""
[
self.emitFatalError(f'control operand {i} is not of quantum type.')
if not self.isQuantumType(control.type) else None
for i, control in enumerate(controls)
]
[
self.emitFatalError(f'target operand {i} is not of quantum type.')
if not self.isQuantumType(target.type) else None
for i, target in enumerate(targets)
]
def createInvariantForLoop(self,
endVal,
bodyBuilder,
startVal=None,
stepVal=None,
isDecrementing=False):
"""
Create an invariant loop using the CC dialect.
"""
startVal = self.getConstantInt(0) if startVal == None else startVal
stepVal = self.getConstantInt(1) if stepVal == None else stepVal
iTy = self.getIntegerType()
inputs = [startVal]
resultTys = [iTy]
loop = cc.LoopOp(resultTys, inputs, BoolAttr.get(False))
whileBlock = Block.create_at_start(loop.whileRegion, [iTy])
with InsertionPoint(whileBlock):
condPred = IntegerAttr.get(
iTy, 2) if not isDecrementing else IntegerAttr.get(iTy, 4)
cc.ConditionOp(
arith.CmpIOp(condPred, whileBlock.arguments[0], endVal).result,
whileBlock.arguments)
bodyBlock = Block.create_at_start(loop.bodyRegion, [iTy])
with InsertionPoint(bodyBlock):
self.symbolTable.pushScope()
self.pushForBodyStack(bodyBlock.arguments)
bodyBuilder(bodyBlock.arguments[0])
if not self.hasTerminator(bodyBlock):
cc.ContinueOp(bodyBlock.arguments)
self.popForBodyStack()
self.symbolTable.popScope()
stepBlock = Block.create_at_start(loop.stepRegion, [iTy])
with InsertionPoint(stepBlock):
incr = arith.AddIOp(stepBlock.arguments[0], stepVal).result
cc.ContinueOp([incr])
loop.attributes.__setitem__('invariant', UnitAttr.get())
return
def __applyQuantumOperation(self, opName, parameters, targets):
opCtor = getattr(quake, '{}Op'.format(opName.title()))
for quantumValue in targets:
if quake.VeqType.isinstance(quantumValue.type):
def bodyBuilder(iterVal):
q = quake.ExtractRefOp(self.getRefType(),
quantumValue,
-1,
index=iterVal).result
opCtor([], parameters, [], [q])
veqSize = quake.VeqSizeOp(self.getIntegerType(),
quantumValue).result
self.createInvariantForLoop(veqSize, bodyBuilder)
elif quake.RefType.isinstance(quantumValue.type):
opCtor([], parameters, [], [quantumValue])
else:
self.emitFatalError(
f'quantum operation {opName} on incorrect quantum type {quantumValue.type}.'
)
return
def __processRangeLoopIterationBounds(self, argumentNodes):
"""
Analyze `range(...)` bounds and return the start, end,
and step values, as well as whether or not this a decrementing range.
"""
iTy = self.getIntegerType(64)
zero = arith.ConstantOp(iTy, IntegerAttr.get(iTy, 0))
one = arith.ConstantOp(iTy, IntegerAttr.get(iTy, 1))
isDecrementing = False
if len(argumentNodes) == 3:
# Find the step val and we need to
# know if its decrementing
# can be incrementing or decrementing
stepVal = self.popValue()
if isinstance(argumentNodes[2], ast.UnaryOp):
if isinstance(argumentNodes[2].op, ast.USub):
if isinstance(argumentNodes[2].operand, ast.Constant):
if argumentNodes[2].operand.value > 0:
isDecrementing = True
else:
self.emitFatalError(
'CUDA-Q requires step value on range() to be a constant.'
)
# exclusive end
endVal = self.popValue()
# inclusive start
startVal = self.popValue()
elif len(argumentNodes) == 2:
stepVal = one
endVal = self.popValue()
startVal = self.popValue()
else:
stepVal = one
endVal = self.popValue()
startVal = zero
startVal = self.ifPointerThenLoad(startVal)
endVal = self.ifPointerThenLoad(endVal)
stepVal = self.ifPointerThenLoad(stepVal)
# Range expects integers
if F64Type.isinstance(startVal.type):
startVal = arith.FPToSIOp(self.getIntegerType(), startVal).result
if F64Type.isinstance(endVal.type):
endVal = arith.FPToSIOp(self.getIntegerType(), endVal).result
if F64Type.isinstance(stepVal.type):
stepVal = arith.FPToSIOp(self.getIntegerType(), stepVal).result
return startVal, endVal, stepVal, isDecrementing
def needsStackSlot(self, type):
"""
Return true if this is a type that has been "passed by value" and
needs a stack slot created (i.e. a `cc.alloca`) for use throughout the
function.
"""
# FIXME add more as we need them
return ComplexType.isinstance(type) or F64Type.isinstance(
type) or F32Type.isinstance(type) or IntegerType.isinstance(
type) or cc.StructType.isinstance(type)
def generic_visit(self, node):
for field, value in reversed(list(ast.iter_fields(node))):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
self.visit(item)
elif isinstance(value, ast.AST):
self.visit(value)
def visit_FunctionDef(self, node):
"""
Create an MLIR `func.FuncOp` for the given FunctionDef AST node. For the top-level
FunctionDef, this will add the `FuncOp` to the `ModuleOp` body, annotate the `FuncOp` with
`cudaq-entrypoint` if it is an Entry Point CUDA-Q kernel, and visit the rest of the
FunctionDef body. If this is an inner FunctionDef, this will treat the function as a CC
lambda function and add the cc.callable-typed value to the symbol table, keyed on the
FunctionDef name.
We keep track of the top-level function name as well as its internal MLIR name, prefixed
with the __nvqpp__mlirgen__ prefix.
"""
if self.buildingEntryPoint:
# This is an inner function def, we will
# treat it as a cc.callable (cc.create_lambda)
if self.verbose:
print("Visiting inner FunctionDef {}".format(node.name))
arguments = node.args.args
if len(arguments):
self.emitFatalError(
"inner function definitions cannot have arguments.", node)
ty = cc.CallableType.get(self.ctx, [])
createLambda = cc.CreateLambdaOp(ty)
initRegion = createLambda.initRegion
initBlock = Block.create_at_start(initRegion, [])
# TODO: process all captured variables in the main function
# definition first to avoid reusing code not defined in the
# same or parent scope of the produced MLIR.
with InsertionPoint(initBlock):
[self.visit(n) for n in node.body]
cc.ReturnOp([])
self.symbolTable[node.name] = createLambda.result
return
with self.ctx, InsertionPoint(self.module.body), self.loc:
# Get the potential documentation string
self.docstring = ast.get_docstring(node)
# Get the argument types and argument names
# this will throw an error if the types aren't annotated
self.argTypes = [
self.mlirTypeFromAnnotation(arg.annotation)
for arg in node.args.args
]
parentResultType = self.knownResultType
if node.returns != None:
self.knownResultType = self.mlirTypeFromAnnotation(node.returns)
# Get the argument names
argNames = [arg.arg for arg in node.args.args]
self.name = node.name
self.capturedDataStorage.name = self.name
# the full function name in MLIR is `__nvqpp__mlirgen__` + the function name
if not self.disableNvqppPrefix:
fullName = nvqppPrefix + node.name
else:
fullName = node.name
# Create the FuncOp
f = func.FuncOp(fullName, (self.argTypes, [] if self.knownResultType
== None else [self.knownResultType]),
loc=self.loc)
self.kernelFuncOp = f
# Set this kernel as an entry point if the argument types are classical only
def isQuantumTy(ty):
return quake.RefType.isinstance(ty) or quake.VeqType.isinstance(
ty) or quake.StruqType.isinstance(ty)
areQuantumTypes = [isQuantumTy(ty) for ty in self.argTypes]
f.attributes.__setitem__('cudaq-kernel', UnitAttr.get())
if True not in areQuantumTypes and not self.disableEntryPointTag:
f.attributes.__setitem__('cudaq-entrypoint', UnitAttr.get())
# Create the entry block
self.entry = f.add_entry_block()
# Set the insertion point to the start of the entry block
with InsertionPoint(self.entry):
self.buildingEntryPoint = True
self.symbolTable.pushScope()
# Add the block arguments to the symbol table,
# create a stack slot for value arguments
blockArgs = self.entry.arguments
for i, b in enumerate(blockArgs):
if self.needsStackSlot(b.type):
stackSlot = cc.AllocaOp(
cc.PointerType.get(self.ctx, b.type),
TypeAttr.get(b.type)).result
cc.StoreOp(b, stackSlot)
self.symbolTable[argNames[i]] = stackSlot
else:
self.symbolTable[argNames[i]] = b
# Visit the function
startIdx = 0
# Search for the potential documentation string, and
# if found, start the body visitation after it.
if len(node.body) and isinstance(node.body[0], ast.Expr):
expr = node.body[0]
if hasattr(expr, 'value') and isinstance(
expr.value, ast.Constant):
constant = expr.value
if isinstance(constant.value, str):
startIdx = 1
[self.visit(n) for n in node.body[startIdx:]]
# Add the return operation
if not self.hasTerminator(self.entry):
ret = func.ReturnOp([])
self.buildingEntryPoint = False
self.symbolTable.popScope()
if True not in areQuantumTypes:
attr = DictAttr.get(
{
fullName:
StringAttr.get(
fullName + '_PyKernelEntryPointRewrite',
context=self.ctx)
},
context=self.ctx)
self.module.operation.attributes.__setitem__(
'quake.mangled_name_map', attr)
globalKernelRegistry[node.name] = f
self.symbolTable.clear()
self.valueStack.clear()
self.knownResultType = parentResultType
def visit_Expr(self, node):
"""
Implement `ast.Expr` visitation to screen out all
multi-line `docstrings`. These are differentiated from other strings
at the node-type level. Strings we may care about will have been
assigned to a variable (hence `ast.Assign` nodes), while other strings will exist
as standalone expressions with no uses.
"""