-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathomp_ir.py
More file actions
2056 lines (1837 loc) · 82.2 KB
/
Copy pathomp_ir.py
File metadata and controls
2056 lines (1837 loc) · 82.2 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
from numba.core import (
ir,
types,
typing,
transforms,
bytecode,
compiler,
typeinfer,
)
from numba.core.ir_utils import (
dprint_func_ir,
find_topo_order,
mk_unique_var,
apply_copy_propagate_extensions,
visit_vars_extensions,
visit_vars_inner,
)
from numba import cuda as numba_cuda
from numba.cuda import descriptor as cuda_descriptor, compiler as cuda_compiler
from numba.core.types.functions import Dispatcher
from numba.core.analysis import ir_extension_usedefs, _use_defs_result
import numba
import llvmlite.ir as lir
import llvmlite.binding as ll
import sys
import os
import copy
import tempfile
import subprocess
import operator
import numpy as np
from pathlib import Path
import types as python_types
from .analysis import (
is_dsa,
typemap_lookup,
is_target_tag,
is_target_arg,
in_openmp_region,
get_blocks_between_start_end,
get_name_var_table,
is_pointer_target_arg,
)
from .tags import (
openmp_tag_list_to_str,
list_vars_from_tags,
get_tags_of_type,
StringLiteral,
openmp_tag,
NameSlice,
)
from .llvmlite_extensions import TokenType, CallInstrWithOperandBundle
from .config import (
libpath,
DEBUG_OPENMP,
DEBUG_OPENMP_LLVM_PASS,
OPENMP_DEVICE_TOOLCHAIN,
)
from .link_utils import link_shared_library
from .llvm_pass import run_intrinsics_openmp_pass
from .compiler import (
OnlyLower,
OnlyLowerCUDA,
OpenmpCPUTargetContext,
OpenmpCUDATargetContext,
CustomAOTCPUCodeLibrary,
CustomCPUCodeLibrary,
CustomContext,
)
unique = 0
def get_unique():
global unique
ret = unique
unique += 1
return ret
def openmp_region_alloca(obj, alloca_instr, typ):
obj.alloca(alloca_instr, typ)
def push_alloca_callback(lowerer, callback, data, builder):
if not hasattr(builder, "_lowerer_push_alloca_callbacks"):
builder._lowerer_push_alloca_callbacks = 0
builder._lowerer_push_alloca_callbacks += 1
def pop_alloca_callback(lowerer, builder):
builder._lowerer_push_alloca_callbacks -= 1
def get_dotted_type(x, typemap, lowerer):
xsplit = x.split("*")
cur_typ = typemap_lookup(typemap, xsplit[0])
# print("xsplit:", xsplit, cur_typ, type(cur_typ))
for field in xsplit[1:]:
dm = lowerer.context.data_model_manager.lookup(cur_typ)
findex = dm._fields.index(field)
cur_typ = dm._members[findex]
# print("dm:", dm, type(dm), dm._members, type(dm._members), dm._fields, type(dm._fields), findex, cur_typ, type(cur_typ))
return cur_typ
class OpenMPCUDACodegen:
def __init__(self, sm=None):
import numba.cuda.api as cudaapi
import numba.cuda.cudadrv.libs as cudalibs
from numba.cuda.codegen import CUDA_TRIPLE
from numba.cuda.cudadrv import driver, enums
# The OpenMP target runtime prefers the blocking sync flag, so we set it
# here before creating the CUDA context.
if sm is None:
driver.driver.cuDevicePrimaryCtxSetFlags(
0, enums.CU_CTX_SCHED_BLOCKING_SYNC
)
self.cc = cudaapi.get_current_device().compute_capability
self.sm = "sm_" + str(self.cc[0]) + str(self.cc[1])
else:
self.sm = sm
# Read the libdevice bitcode for the architecture to link with the module.
self.libdevice_path = cudalibs.get_libdevice()
with open(self.libdevice_path, "rb") as f:
self.libdevice_mod = ll.parse_bitcode(f.read())
# Read the OpenMP device RTL for the architecture to link with the module.
self.libomptarget_arch = libpath / "openmp" / "lib" / "libomptarget-nvptx.bc"
try:
with open(self.libomptarget_arch, "rb") as f:
self.libomptarget_mod = ll.parse_bitcode(f.read())
except FileNotFoundError:
raise RuntimeError(
f"Device RTL for architecture {self.sm} not found. Check compute capability with LLVM version {'.'.join(map(str, ll.llvm_version_info))}."
)
# Initialize asm printers to codegen ptx.
ll.initialize_all_targets()
ll.initialize_all_asmprinters()
target = ll.Target.from_triple(CUDA_TRIPLE)
# We pick opt=2 as a reasonable optimization level for codegen.
self.tm = target.create_target_machine(cpu=self.sm, opt=2)
def _get_target_image(self, mod, filename_prefix, ompx_attrs, use_toolchain=False):
from numba.cuda.cudadrv import driver
from numba.core.llvm_bindings import create_pass_builder
if DEBUG_OPENMP_LLVM_PASS >= 1:
with open(filename_prefix + ".ll", "w") as f:
f.write(str(mod))
# Lower openmp intrinsics.
mod = run_intrinsics_openmp_pass(mod)
if DEBUG_OPENMP_LLVM_PASS >= 1:
with open(filename_prefix + "-intr.ll", "w") as f:
f.write(str(mod))
def _internalize():
# Internalize non-kernel function definitions.
for func in mod.functions:
if func.is_declaration:
continue
if func.linkage != ll.Linkage.external:
continue
if "__omp_offload_numba" in func.name:
continue
func.linkage = "internal"
# Link first libdevice and optimize aggressively with opt=2 as a
# reasonable optimization default.
mod.link_in(self.libdevice_mod, preserve=True)
# Internalize non-kernel function definitions.
_internalize()
# Run passes for optimization, including target-specific passes.
# Run function passes.
with create_pass_builder(
self.tm, opt=2, slp_vectorize=True, loop_vectorize=True
) as pb:
pm = pb.getFunctionPassManager()
for func in mod.functions:
pm.run(func, pb)
# Run module passes.
with create_pass_builder(
self.tm, opt=2, slp_vectorize=True, loop_vectorize=True
) as pb:
pm = pb.getModulePassManager()
pm.run(mod, pb)
if DEBUG_OPENMP_LLVM_PASS >= 1:
mod.verify()
with open(filename_prefix + "-intr-dev.ll", "w") as f:
f.write(str(mod))
# Link in OpenMP device RTL and optimize lightly, with opt=1 to avoid
# aggressive optimization can break openmp execution synchronization for
# target regions.
mod.link_in(self.libomptarget_mod, preserve=True)
# Internalize non-kernel function definitions.
_internalize()
# Run module passes.
with create_pass_builder(
self.tm, opt=1, slp_vectorize=True, loop_vectorize=True
) as pb:
pm = pb.getModulePassManager()
pm.run(mod, pb)
if DEBUG_OPENMP_LLVM_PASS >= 1:
mod.verify()
with open(filename_prefix + "-intr-dev-rtl.ll", "w") as f:
f.write(str(mod))
# Generate ptx assemlby.
ptx = self.tm.emit_assembly(mod)
if use_toolchain:
# ptxas normally does file I/O; prefer piping PTX to stdin to avoid
# writing the .s file unless debug is enabled.
if DEBUG_OPENMP_LLVM_PASS >= 1:
with open(filename_prefix + "-intr-dev-rtl.s", "w") as f:
f.write(ptx)
# Invoke ptxas reading PTX from stdin ('-') and writing output to
# a temporary file so we can capture the object in-memory without
# leaving it in the working directory.
with tempfile.NamedTemporaryFile(suffix=".o", delete=False) as tmpf:
outname = tmpf.name
try:
subprocess.run(
[
"ptxas",
"-m64",
"--gpu-name",
self.sm,
"-",
"-o",
outname,
],
input=ptx.encode(),
check=True,
)
with open(outname, "rb") as f:
cubin = f.read()
# If debug is enabled, also write a named copy for inspection.
if DEBUG_OPENMP_LLVM_PASS >= 1:
with open(
filename_prefix + "-intr-dev-rtl.o",
"wb",
) as f:
f.write(cubin)
finally:
try:
os.remove(outname)
except OSError:
pass
else:
if DEBUG_OPENMP_LLVM_PASS >= 1:
with open(
filename_prefix + "-intr-dev-rtl.s",
"w",
) as f:
f.write(ptx)
linker_kwargs = {}
for x in ompx_attrs:
linker_kwargs[x.arg[0]] = (
tuple(x.arg[1]) if len(x.arg[1]) > 1 else x.arg[1][0]
)
# NOTE: DO NOT set cc, since the linker will always
# compile for the existing GPU context and it is
# incompatible with the launch_bounds ompx_attribute.
linker = driver.Linker.new(**linker_kwargs)
linker.add_ptx(ptx.encode())
cubin = linker.complete()
if DEBUG_OPENMP_LLVM_PASS >= 1:
with open(
filename_prefix + "-intr-dev-rtl.o",
"wb",
) as f:
f.write(cubin)
return cubin
def get_target_image(self, cres, ompx_attrs):
filename_prefix = cres.library.name
allmods = cres.library.modules
linked_mod = ll.parse_assembly(str(allmods[0]))
for mod in allmods[1:]:
linked_mod.link_in(ll.parse_assembly(str(mod)))
if OPENMP_DEVICE_TOOLCHAIN >= 1:
return self._get_target_image(
linked_mod, filename_prefix, ompx_attrs, use_toolchain=True
)
else:
return self._get_target_image(linked_mod, filename_prefix, ompx_attrs)
_omp_cuda_codegen = None
# Accessor for the singleton OpenMPCUDACodegen instance. Initializes the
# instance on first use to ensure a single CUDA context and codegen setup
# per process.
def get_omp_cuda_codegen(arch=None):
global _omp_cuda_codegen
if _omp_cuda_codegen is None:
_omp_cuda_codegen = OpenMPCUDACodegen(sm=arch)
return _omp_cuda_codegen
def copy_one(x, calltypes):
if DEBUG_OPENMP >= 2:
print("copy_one:", x, type(x))
if isinstance(x, ir.Loc):
return copy.copy(x)
elif isinstance(x, ir.Expr):
if x in calltypes:
ctyp = calltypes[x]
else:
ctyp = None
ret = ir.Expr(
copy_one(x.op, calltypes),
copy_one(x.loc, calltypes),
**copy_one(x._kws, calltypes),
)
if ctyp and ret not in calltypes:
calltypes[ret] = ctyp
return ret
elif isinstance(x, dict):
return {k: copy_one(v, calltypes) for k, v in x.items()}
elif isinstance(x, list):
return [copy_one(v, calltypes) for v in x]
elif isinstance(x, tuple):
return tuple([copy_one(v, calltypes) for v in x])
elif isinstance(x, ir.Const):
return ir.Const(
copy_one(x.value, calltypes), copy_one(x.loc, calltypes), x.use_literal_type
)
elif isinstance(
x,
(
int,
float,
str,
ir.Global,
python_types.BuiltinFunctionType,
ir.UndefinedType,
type(None),
types.functions.ExternalFunction,
),
):
return x
elif isinstance(x, ir.Var):
return ir.Var(x.scope, copy_one(x.name, calltypes), copy_one(x.loc, calltypes))
elif isinstance(x, ir.Del):
return ir.Del(copy_one(x.value, calltypes), copy_one(x.loc, calltypes))
elif isinstance(x, ir.Jump):
return ir.Jump(copy_one(x.target, calltypes), copy_one(x.loc, calltypes))
elif isinstance(x, ir.Return):
return ir.Return(copy_one(x.value, calltypes), copy_one(x.loc, calltypes))
elif isinstance(x, ir.Branch):
return ir.Branch(
copy_one(x.cond, calltypes),
copy_one(x.truebr, calltypes),
copy_one(x.falsebr, calltypes),
copy_one(x.loc, calltypes),
)
elif isinstance(x, ir.Print):
ctyp = calltypes[x]
ret = copy.copy(x)
calltypes[ret] = ctyp
return ret
elif isinstance(x, ir.Assign):
return ir.Assign(
copy_one(x.value, calltypes),
copy_one(x.target, calltypes),
copy_one(x.loc, calltypes),
)
elif isinstance(x, ir.Arg):
return ir.Arg(
copy_one(x.name, calltypes),
copy_one(x.index, calltypes),
copy_one(x.loc, calltypes),
)
elif isinstance(x, ir.SetItem):
ctyp = calltypes[x]
ret = ir.SetItem(
copy_one(x.target, calltypes),
copy_one(x.index, calltypes),
copy_one(x.value, calltypes),
copy_one(x.loc, calltypes),
)
calltypes[ret] = ctyp
return ret
elif isinstance(x, ir.StaticSetItem):
ctyp = calltypes[x]
ret = ir.StaticSetItem(
copy_one(x.target, calltypes),
copy_one(x.index, calltypes),
copy_one(x.index_var, calltypes),
copy_one(x.value, calltypes),
copy_one(x.loc, calltypes),
)
calltypes[ret] = ctyp
return ret
elif isinstance(x, ir.FreeVar):
return ir.FreeVar(
copy_one(x.index, calltypes),
copy_one(x.name, calltypes),
copy_one(x.value, calltypes),
copy_one(x.loc, calltypes),
)
elif isinstance(x, slice):
return slice(
copy_one(x.start, calltypes),
copy_one(x.stop, calltypes),
copy_one(x.step, calltypes),
)
elif isinstance(x, ir.PopBlock):
return ir.PopBlock(copy_one(x.loc, calltypes))
elif isinstance(x, ir.SetAttr):
ctyp = calltypes[x]
ret = ir.SetAttr(
copy_one(x.target, calltypes),
copy_one(x.attr, calltypes),
copy_one(x.value, calltypes),
copy_one(x.loc, calltypes),
)
calltypes[ret] = ctyp
return ret
elif isinstance(x, ir.DelAttr):
return ir.DelAttr(
copy_one(x.target, calltypes),
copy_one(x.attr, calltypes),
copy_one(x.loc, calltypes),
)
elif isinstance(x, types.Type):
return x # Don't copy types.
print("Failed to handle the following type when copying target IR.", type(x), x)
assert False
def copy_ir(input_ir, calltypes, depth=1):
assert depth >= 0 and depth <= 1
# This is a depth 0 copy.
cur_ir = input_ir.copy()
if depth == 1:
for blk in cur_ir.blocks.values():
for i in range(len(blk.body)):
if not isinstance(
blk.body[i], (openmp_region_start, openmp_region_end)
):
blk.body[i] = copy_one(blk.body[i], calltypes)
return cur_ir
def replace_np_empty_with_cuda_shared(
outlined_ir, typemap, calltypes, prefix, typingctx
):
if DEBUG_OPENMP >= 2:
print("starting replace_np_empty_with_cuda_shared")
outlined_ir = outlined_ir.blocks
converted_arrays = []
consts = {}
topo_order = find_topo_order(outlined_ir)
mode = 0 # 0 = non-target region, 1 = target region, 2 = teams region, 3 = teams parallel region
# For each block in topological order...
for label in topo_order:
block = outlined_ir[label]
new_block_body = []
blen = len(block.body)
index = 0
# For each statement in the block.
while index < blen:
stmt = block.body[index]
# Adjust mode based on the start of an openmp region.
if isinstance(stmt, openmp_region_start):
if "TARGET" in stmt.tags[0].name:
assert mode == 0
mode = 1
if "TEAMS" in stmt.tags[0].name and mode == 1:
mode = 2
if "PARALLEL" in stmt.tags[0].name and mode == 2:
mode = 3
new_block_body.append(stmt)
# Adjust mode based on the end of an openmp region.
elif isinstance(stmt, openmp_region_end):
if mode == 3 and "PARALLEL" in stmt.tags[0].name:
mode = 2
if mode == 2 and "TEAMS" in stmt.tags[0].name:
mode = 1
if mode == 1 and "TARGET" in stmt.tags[0].name:
mode = 0
new_block_body.append(stmt)
# Fix calltype for the np.empty call to have literal as first
# arg and include explicit dtype.
elif (
isinstance(stmt, ir.Assign)
and isinstance(stmt.value, ir.Expr)
and stmt.value.op == "call"
and stmt.value.func in converted_arrays
):
size = consts[stmt.value.args[0].name]
# The 1D case where the dimension size is directly a const.
if isinstance(size, ir.Const):
size = size.value
signature = calltypes[stmt.value]
signature_args = (
types.scalars.IntegerLiteral(size),
types.functions.NumberClass(signature.return_type.dtype),
)
del calltypes[stmt.value]
calltypes[stmt.value] = typing.templates.Signature(
signature.return_type, signature_args, signature.recvr
)
# The 2D+ case where the dimension sizes are in a tuple.
elif isinstance(size, ir.Expr):
signature = calltypes[stmt.value]
signature_args = (
types.Tuple(
[
types.scalars.IntegerLiteral(consts[x.name].value)
for x in size.items
]
),
types.functions.NumberClass(signature.return_type.dtype),
)
del calltypes[stmt.value]
calltypes[stmt.value] = typing.templates.Signature(
signature.return_type, signature_args, signature.recvr
)
# These lines will force the function to be in the data structures that lowering uses.
afnty = typemap[stmt.value.func.name]
afnty.get_call_type(typingctx, signature_args, {})
if len(stmt.value.args) == 1:
dtype_to_use = signature.return_type.dtype
# If dtype in kwargs then remove it.
if len(stmt.value.kws) > 0:
for kwarg in stmt.value.kws:
if kwarg[0] == "dtype":
stmt.value.kws = list(
filter(lambda x: x[0] != "dtype", stmt.value.kws)
)
break
new_block_body.append(
ir.Assign(
ir.Global("np", np, stmt.loc),
ir.Var(
stmt.target.scope, mk_unique_var(".np_global"), stmt.loc
),
stmt.loc,
)
)
typemap[new_block_body[-1].target.name] = types.Module(np)
new_block_body.append(
ir.Assign(
ir.Expr.getattr(
new_block_body[-1].target, str(dtype_to_use), stmt.loc
),
ir.Var(
stmt.target.scope, mk_unique_var(".np_dtype"), stmt.loc
),
stmt.loc,
)
)
typemap[new_block_body[-1].target.name] = (
types.functions.NumberClass(signature.return_type.dtype)
)
stmt.value.args.append(new_block_body[-1].target)
else:
raise NotImplementedError(
"np.empty having more than shape and dtype arguments not yet supported."
)
new_block_body.append(stmt)
# Keep track of variables assigned from consts or from build_tuples make up exclusively of
# variables assigned from consts.
elif isinstance(stmt, ir.Assign) and (
isinstance(stmt.value, ir.Const)
or (
isinstance(stmt.value, ir.Expr)
and stmt.value.op == "build_tuple"
and all([x.name in consts for x in stmt.value.items])
)
):
consts[stmt.target.name] = stmt.value
new_block_body.append(stmt)
# If we see a global for the numpy module.
elif (
isinstance(stmt, ir.Assign)
and isinstance(stmt.value, ir.Global)
and isinstance(stmt.value.value, python_types.ModuleType)
and stmt.value.value.__name__ == "numpy"
):
lhs = stmt.target
index += 1
next_stmt = block.body[index]
# And the next statement is a getattr for the name "empty" on the numpy module
# and we are in a target region.
if (
isinstance(next_stmt, ir.Assign)
and isinstance(next_stmt.value, ir.Expr)
and next_stmt.value.value == lhs
and next_stmt.value.op == "getattr"
and next_stmt.value.attr == "empty"
and mode > 0
):
# Remember that we are converting this np.empty into a CUDA call.
converted_arrays.append(next_stmt.target)
# Create numba.cuda module variable.
new_block_body.append(
ir.Assign(
ir.Global("numba", numba, lhs.loc),
ir.Var(
lhs.scope, mk_unique_var(".cuda_shared_global"), lhs.loc
),
lhs.loc,
)
)
typemap[new_block_body[-1].target.name] = types.Module(numba)
new_block_body.append(
ir.Assign(
ir.Expr.getattr(new_block_body[-1].target, "cuda", lhs.loc),
ir.Var(
lhs.scope,
mk_unique_var(".cuda_shared_getattr"),
lhs.loc,
),
lhs.loc,
)
)
typemap[new_block_body[-1].target.name] = types.Module(numba.cuda)
if mode == 1:
raise NotImplementedError(
"np.empty used in non-teams or parallel target region"
)
pass
elif mode == 2:
# Create numba.cuda.shared module variable.
new_block_body.append(
ir.Assign(
ir.Expr.getattr(
new_block_body[-1].target, "shared", lhs.loc
),
ir.Var(
lhs.scope,
mk_unique_var(".cuda_shared_getattr"),
lhs.loc,
),
lhs.loc,
)
)
typemap[new_block_body[-1].target.name] = types.Module(
numba.cuda.stubs.shared
)
elif mode == 3:
# Create numba.cuda.local module variable.
new_block_body.append(
ir.Assign(
ir.Expr.getattr(
new_block_body[-1].target, "local", lhs.loc
),
ir.Var(
lhs.scope,
mk_unique_var(".cuda_local_getattr"),
lhs.loc,
),
lhs.loc,
)
)
typemap[new_block_body[-1].target.name] = types.Module(
numba.cuda.stubs.local
)
# Change the typemap for the original function variable for np.empty.
afnty = typingctx.resolve_getattr(
typemap[new_block_body[-1].target.name], "array"
)
del typemap[next_stmt.target.name]
typemap[next_stmt.target.name] = afnty
# Change the variable that previously was assigned np.empty to now be one of
# the CUDA array allocators.
new_block_body.append(
ir.Assign(
ir.Expr.getattr(
new_block_body[-1].target, "array", lhs.loc
),
next_stmt.target,
lhs.loc,
)
)
else:
new_block_body.append(stmt)
new_block_body.append(next_stmt)
else:
new_block_body.append(stmt)
index += 1
block.body = new_block_body
def remove_dels(blocks):
"""remove ir.Del nodes"""
for block in blocks.values():
new_body = []
for stmt in block.body:
if not isinstance(stmt, ir.Del):
new_body.append(stmt)
block.body = new_body
return
def find_target_start_end(func_ir, target_num):
start_block = None
end_block = None
for label, block in func_ir.blocks.items():
if isinstance(block.body[0], openmp_region_start):
block_target_num = block.body[0].has_target()
if target_num == block_target_num:
start_block = label
if start_block is not None and end_block is not None:
return start_block, end_block
elif isinstance(block.body[0], openmp_region_end):
block_target_num = block.body[0].start_region.has_target()
if target_num == block_target_num:
end_block = label
if start_block is not None and end_block is not None:
return start_block, end_block
dprint_func_ir(func_ir, "find_target_start_end")
print("target_num:", target_num)
assert False
class openmp_region_start(ir.Stmt):
def __init__(self, tags, region_number, loc, firstprivate_dead_after=None):
if DEBUG_OPENMP >= 2:
print("region ids openmp_region_start::__init__", id(self))
self.tags = tags
self.region_number = region_number
self.loc = loc
self.omp_region_var = None
self.omp_metadata = None
self.tag_vars = set()
self.normal_iv = None
self.target_copy = False
self.firstprivate_dead_after = (
[] if firstprivate_dead_after is None else firstprivate_dead_after
)
for tag in self.tags:
if isinstance(tag.arg, ir.Var):
self.tag_vars.add(tag.arg.name)
elif isinstance(tag.arg, str):
self.tag_vars.add(tag.arg)
elif isinstance(tag.arg, NameSlice):
self.tag_vars.add(tag.arg.name)
if tag.name == "QUAL.OMP.NORMALIZED.IV":
self.normal_iv = tag.arg
if DEBUG_OPENMP >= 1:
print("tags:", self.tags)
print("tag_vars:", sorted(self.tag_vars))
self.acq_res = False
self.acq_rel = False
self.alloca_queue = []
self.end_region = None
def __getstate__(self):
state = self.__dict__.copy()
return state
def __setstate__(self, state):
self.__dict__.update(state)
def replace_var_names(self, namedict):
for i in range(len(self.tags)):
if isinstance(self.tags[i].arg, ir.Var):
if self.tags[i].arg.name in namedict:
var = self.tags[i].arg
self.tags[i].arg = ir.Var(var.scope, namedict[var.name], var.log)
elif isinstance(self.tags[i].arg, str):
if "*" in self.tags[i].arg:
xsplit = self.tags[i].arg.split("*")
assert len(xsplit) == 2
if xsplit[0] in namedict:
self.tags[i].arg = namedict[xsplit[0]] + "*" + xsplit[1]
else:
if self.tags[i].arg in namedict:
self.tags[i].arg = namedict[self.tags[i].arg]
def add_tag(self, tag):
tag_arg_str = None
if isinstance(tag.arg, ir.Var):
tag_arg_str = tag.arg.name
elif isinstance(tag.arg, str):
tag_arg_str = tag.arg
elif isinstance(tag.arg, lir.instructions.AllocaInstr):
tag_arg_str = tag.arg._get_name()
else:
assert False
if isinstance(tag_arg_str, str):
self.tag_vars.add(tag_arg_str)
self.tags.append(tag)
def get_var_dsa(self, var):
assert isinstance(var, str)
for tag in self.tags:
if is_dsa(tag.name) and tag.var_in(var):
return tag.name
return None
def requires_acquire_release(self):
pass
# self.acq_res = True
def requires_combined_acquire_release(self):
pass
# self.acq_rel = True
def has_target(self):
for t in self.tags:
if is_target_tag(t.name):
return t.arg
return None
def list_vars(self):
return list_vars_from_tags(self.tags)
def update_tags(self):
with self.builder.goto_block(self.block):
cur_instr = -1
while True:
last_instr = self.builder.block.instructions[cur_instr]
if (
isinstance(last_instr, lir.instructions.CallInstr)
and last_instr.tags is not None
and len(last_instr.tags) > 0
):
break
cur_instr -= 1
last_instr.tags = openmp_tag_list_to_str(self.tags, self.lowerer, False)
if DEBUG_OPENMP >= 1:
print("last_tags:", last_instr.tags, type(last_instr.tags))
def alloca(self, alloca_instr, typ):
# We can't process these right away since the processing required can
# lead to infinite recursion. So, we just accumulate them in a queue
# and then process them later at the end_region marker so that the
# variables are guaranteed to exist in their full form so that when we
# process them then they won't lead to infinite recursion.
self.alloca_queue.append((alloca_instr, typ))
def post_lowering_process_alloca_queue(self, enter_directive):
has_update = False
if DEBUG_OPENMP >= 1:
print("starting post_lowering_process_alloca_queue")
for alloca_instr, typ in self.alloca_queue:
has_update = self.process_one_alloca(alloca_instr, typ) or has_update
if has_update:
if DEBUG_OPENMP >= 1:
print(
"post_lowering_process_alloca_queue has update:",
enter_directive.tags,
)
enter_directive.tags = openmp_tag_list_to_str(
self.tags, self.lowerer, False
)
# LLVM IR is doing some string caching and the following line is necessary to
# reset that caching so that the original tag text can be overwritten above.
enter_directive._clear_string_cache()
if DEBUG_OPENMP >= 1:
print(
"post_lowering_process_alloca_queue updated tags:",
enter_directive.tags,
)
self.alloca_queue = []
def process_one_alloca(self, alloca_instr, typ):
avar = alloca_instr.name
if DEBUG_OPENMP >= 1:
print(
"openmp_region_start process_one_alloca:",
id(self),
alloca_instr,
avar,
typ,
type(alloca_instr),
self.tag_vars,
)
has_update = False
if (
self.normal_iv is not None
and avar != self.normal_iv
and avar.startswith(self.normal_iv)
):
for i in range(len(self.tags)):
if DEBUG_OPENMP >= 1:
print("Replacing normalized iv with", avar)
self.tags[i].arg = avar
has_update = True
break
if not self.needs_implicit_vars():
return has_update
if avar not in self.tag_vars:
if DEBUG_OPENMP >= 1:
print(
f"LLVM variable {avar} didn't previously exist in the list of vars so adding as private."
)
self.add_tag(
openmp_tag("QUAL.OMP.PRIVATE", alloca_instr)
) # is FIRSTPRIVATE right here?
has_update = True
return has_update
def needs_implicit_vars(self):
first_tag = self.tags[0]
if (
first_tag.name == "DIR.OMP.PARALLEL"
or first_tag.name == "DIR.OMP.PARALLEL.LOOP"
or first_tag.name == "DIR.OMP.TASK"
):
return True
return False
def update_context(self, context, builder):
cctyp = type(context.call_conv)
if (
not hasattr(cctyp, "pyomp_patch_installed")
or not cctyp.pyomp_patch_installed
):
cctyp.pyomp_patch_installed = True
# print("update_context", "id(cctyp.return_user_exec)", id(cctyp.return_user_exc), "id(context)", id(context))
setattr(cctyp, "orig_return_user_exc", cctyp.return_user_exc)
def pyomp_return_user_exc(self, builder, *args, **kwargs):
# print("pyomp_return_user_exc")
# Handle exceptions in OpenMP regions by emitting a trap and an
# unreachable terminator.
if in_openmp_region(builder):
fnty = lir.types.FunctionType(lir.types.VoidType(), [])
fn = builder.module.declare_intrinsic("llvm.trap", (), fnty)
builder.call(fn, [])
builder.unreachable()
return
self.orig_return_user_exc(builder, *args, **kwargs)
setattr(cctyp, "return_user_exc", pyomp_return_user_exc)
setattr(
cctyp, "orig_return_status_propagate", cctyp.return_status_propagate
)
def pyomp_return_status_propagate(self, builder, *args, **kwargs):
if in_openmp_region(builder):
return
self.orig_return_status_propagate(builder, *args, **kwargs)
setattr(cctyp, "return_status_propagate", pyomp_return_status_propagate)
cemtyp = type(context.error_model)
if (
not hasattr(cemtyp, "pyomp_patch_installed")
or not cemtyp.pyomp_patch_installed
):
cemtyp.pyomp_patch_installed = True
setattr(cemtyp, "orig_fp_zero_division", cemtyp.fp_zero_division)
def pyomp_fp_zero_division(self, builder, *args, **kwargs):
# print("pyomp_fp_zero_division")
if in_openmp_region(builder):
return False
return self.orig_fp_zero_division(builder, *args, **kwargs)
setattr(cemtyp, "fp_zero_division", pyomp_fp_zero_division)
# print("after", id(pyomp_fp_zero_division), id(cemtyp.fp_zero_division))
pyapi = context.get_python_api(builder)
ptyp = type(pyapi)
if not hasattr(ptyp, "pyomp_patch_installed") or not ptyp.pyomp_patch_installed:
ptyp.pyomp_patch_installed = True
# print("update_context", "id(ptyp.emit_environment_sentry)", id(ptyp.emit_environment_sentry), "id(context)", id(context))
setattr(ptyp, "orig_emit_environment_sentry", ptyp.emit_environment_sentry)