-
Notifications
You must be signed in to change notification settings - Fork 66
/
optimize.jl
2698 lines (2532 loc) · 95.1 KB
/
optimize.jl
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
struct PipelineConfig
Speedup::Cint
Size::Cint
lower_intrinsics::Cint
dump_native::Cint
external_use::Cint
llvm_only::Cint
always_inline::Cint
enable_early_simplifications::Cint
enable_early_optimizations::Cint
enable_scalar_optimizations::Cint
enable_loop_optimizations::Cint
enable_vector_pipeline::Cint
remove_ni::Cint
cleanup::Cint
end
const RunAttributor = Ref(true)
function pipeline_options(;
lower_intrinsics = true,
dump_native = false,
external_use = false,
llvm_only = false,
always_inline = true,
enable_early_simplifications = true,
enable_early_optimizations = true,
enable_scalar_optimizations = true,
enable_loop_optimizations = true,
enable_vector_pipeline = true,
remove_ni = true,
cleanup = true,
Size = 0,
Speedup = 3,
)
return PipelineConfig(
Speedup,
Size,
lower_intrinsics,
dump_native,
external_use,
llvm_only,
always_inline,
enable_early_simplifications,
enable_early_optimizations,
enable_scalar_optimizations,
enable_loop_optimizations,
enable_vector_pipeline,
remove_ni,
cleanup,
)
end
function run_jl_pipeline(pm, tm; kwargs...)
config = Ref(pipeline_options(; kwargs...))
function jl_pipeline(m)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
@ccall jl_build_newpm_pipeline(
mpm.ref::Ptr{Cvoid},
pb.ref::Ptr{Cvoid},
config::Ptr{PipelineConfig},
)::Cvoid
end
LLVM.run!(mpm, m, tm)
end
return true
end
add!(pm, ModulePass("JLPipeline", jl_pipeline))
end
@static if VERSION < v"1.11.0-DEV.428"
else
barrier_noop!(pm) = nothing
end
@static if VERSION < v"1.11-"
function gc_invariant_verifier_tm!(pm, tm, cond)
gc_invariant_verifier!(pm, cond)
end
else
function gc_invariant_verifier_tm!(pm, tm, cond)
function gc_invariant_verifier(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, GCInvariantVerifierPass(; strong = cond))
end
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("GCInvariantVerifier", gc_invariant_verifier))
end
end
@static if VERSION < v"1.11-"
function propagate_julia_addrsp_tm!(pm, tm)
propagate_julia_addrsp!(pm)
end
else
function propagate_julia_addrsp_tm!(pm, tm)
function prop_julia_addr(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, PropagateJuliaAddrspacesPass())
end
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("PropagateJuliaAddrSpace", prop_julia_addr))
end
end
@static if VERSION < v"1.11-"
function alloc_opt_tm!(pm, tm)
alloc_opt!(pm)
end
else
function alloc_opt_tm!(pm, tm)
function alloc_opt(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, AllocOptPass())
end
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("AllocOpt", alloc_opt))
end
end
@static if VERSION < v"1.11-"
function remove_ni_tm!(pm, tm)
remove_ni!(pm)
end
else
function remove_ni_tm!(pm, tm)
function remove_ni(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, RemoveNIPass())
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("RemoveNI", remove_ni))
end
end
@static if VERSION < v"1.11-"
function julia_licm_tm!(pm, tm)
julia_licm!(pm)
end
else
function julia_licm_tm!(pm, tm)
function julia_licm(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, NewPMLoopPassManager()) do lpm
add!(lpm, JuliaLICMPass())
end
end
end
run!(pb, mod)
end
return true
end
# really looppass
add!(pm, ModulePass("JuliaLICM", julia_licm))
end
end
@static if VERSION < v"1.11-"
function lower_simdloop_tm!(pm, tm)
lower_simdloop!(pm)
end
else
function lower_simdloop_tm!(pm, tm)
function lower_simdloop(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, NewPMLoopPassManager()) do lpm
add!(lpm, LowerSIMDLoopPass())
end
end
end
run!(pb, mod)
end
return true
end
# really looppass
add!(pm, ModulePass("LowerSIMDLoop", lower_simdloop))
end
end
function loop_optimizations_tm!(pm, tm)
@static if true || VERSION < v"1.11-"
lower_simdloop_tm!(pm, tm)
licm!(pm)
if LLVM.version() >= v"15"
simple_loop_unswitch_legacy!(pm)
else
loop_unswitch!(pm)
end
else
run_jl_pipeline(
pm,
tm;
lower_intrinsics = false,
dump_native = false,
external_use = false,
llvm_only = false,
always_inline = false,
enable_early_simplifications = false,
enable_early_optimizations = false,
enable_scalar_optimizations = false,
enable_loop_optimizations = true,
enable_vector_pipeline = false,
remove_ni = false,
cleanup = false,
)
end
end
function more_loop_optimizations_tm!(pm, tm)
@static if true || VERSION < v"1.11-"
loop_rotate!(pm)
# moving IndVarSimplify here prevented removing the loop in perf_sumcartesian(10:-1:1)
loop_idiom!(pm)
# LoopRotate strips metadata from terminator, so run LowerSIMD afterwards
lower_simdloop_tm!(pm, tm) # Annotate loop marked with "loopinfo" as LLVM parallel loop
licm!(pm)
julia_licm_tm!(pm, tm)
# Subsequent passes not stripping metadata from terminator
instruction_combining!(pm) # TODO: createInstSimplifyLegacy
jl_inst_simplify!(pm)
ind_var_simplify!(pm)
loop_deletion!(pm)
loop_unroll!(pm) # TODO: in Julia createSimpleLoopUnroll
else
# LowerSIMDLoopPass
# LoopRotatePass [opt >= 2]
# LICMPass
# JuliaLICMPass
# SimpleLoopUnswitchPass
# LICMPass
# JuliaLICMPass
# IRCEPass
# LoopInstSimplifyPass
# - in ours this is instcombine with jlinstsimplify
# LoopIdiomRecognizePass
# IndVarSimplifyPass
# LoopDeletionPass
# LoopFullUnrollPass
run_jl_pipeline(
pm,
tm;
lower_intrinsics = false,
dump_native = false,
external_use = false,
llvm_only = false,
always_inline = false,
enable_early_simplifications = false,
enable_early_optimizations = false,
enable_scalar_optimizations = false,
enable_loop_optimizations = true,
enable_vector_pipeline = false,
remove_ni = false,
cleanup = false,
)
end
end
@static if VERSION < v"1.11-"
function demote_float16_tm!(pm, tm)
demote_float16!(pm)
end
else
function demote_float16_tm!(pm, tm)
function demote_float16(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, DemoteFloat16Pass())
end
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("DemoteFloat16", demote_float16))
end
end
@static if VERSION < v"1.11-"
function lower_exc_handlers_tm!(pm, tm)
lower_exc_handlers!(pm)
end
else
function lower_exc_handlers_tm!(pm, tm)
function lower_exc_handlers(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, LowerExcHandlersPass())
end
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("LowerExcHandlers", lower_exc_handlers))
end
end
@static if VERSION < v"1.11-"
function lower_ptls_tm!(pm, tm, dump_native)
lower_ptls!(pm, dump_native)
end
else
function lower_ptls_tm!(pm, tm, dump_native)
function lower_ptls(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, LowerPTLSPass())
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("LowerPTLS", lower_ptls))
end
end
@static if VERSION < v"1.11-"
function combine_mul_add_tm!(pm, tm)
combine_mul_add!(pm)
end
else
function combine_mul_add_tm!(pm, tm)
function combine_mul_add(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, CombineMulAddPass())
end
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("CombineMulAdd", combine_mul_add))
end
end
@static if VERSION < v"1.11-"
function late_lower_gc_frame_tm!(pm, tm)
late_lower_gc_frame!(pm)
end
else
function late_lower_gc_frame_tm!(pm, tm)
function late_lower_gc_frame(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, LateLowerGCPass())
end
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("LateLowerGCFrame", late_lower_gc_frame))
end
end
@static if VERSION < v"1.11-"
function final_lower_gc_tm!(pm, tm)
final_lower_gc!(pm)
end
else
function final_lower_gc_tm!(pm, tm)
function final_lower_gc(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, NewPMFunctionPassManager()) do fpm
add!(fpm, FinalLowerGCPass())
end
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("FinalLowerGCFrame", final_lower_gc))
end
end
@static if VERSION < v"1.11-"
function cpu_features_tm!(pm, tm)
@static if isdefined(LLVM.Interop, :cpu_features!)
LLVM.Interop.cpu_features!(pm)
else
@static if isdefined(GPUCompiler, :cpu_features!)
GPUCompiler.cpu_features!(pm)
end
end
end
else
function cpu_features_tm!(pm, tm)
function cpu_features(mod)
@dispose pb = NewPMPassBuilder() begin
add!(pb, NewPMModulePassManager()) do mpm
add!(mpm, CPUFeaturesPass())
end
run!(pb, mod)
end
return true
end
add!(pm, ModulePass("CPUFeatures", cpu_features))
end
end
function addNA(inst, node::LLVM.Metadata, MD)
md = metadata(inst)
next = nothing
if haskey(md, MD)
next = LLVM.MDNode(Metadata[node, operands(md[MD])...])
else
next = LLVM.MDNode(Metadata[node])
end
setindex!(md, next, MD)
end
function addr13NoAlias(mod::LLVM.Module)
ctx = LLVM.context(mod)
dom = API.EnzymeAnonymousAliasScopeDomain("addr13", ctx)
scope = API.EnzymeAnonymousAliasScope(dom, "na_addr13")
aliasscope = noalias = scope
for f in functions(mod), bb in blocks(f), inst in instructions(bb)
if isa(inst, LLVM.StoreInst)
addNA(inst, noalias, LLVM.MD_noalias)
elseif isa(inst, LLVM.CallInst)
fn = LLVM.called_operand(inst)
if isa(fn, LLVM.Function)
name = LLVM.name(fn)
if startswith(name, "llvm.memcpy") || startswith(name, "llvm.memmove")
addNA(inst, noalias, LLVM.MD_noalias)
end
end
elseif isa(inst, LLVM.LoadInst)
ty = value_type(inst)
if isa(ty, LLVM.PointerType)
if addrspace(ty) == 13
addNA(inst, aliasscope, LLVM.MD_alias_scope)
end
end
end
end
end
function source_elem(v)
@static if LLVM.version() >= v"15"
LLVM.LLVMType(LLVM.API.LLVMGetGEPSourceElementType(v))
else
eltype(value_type(operands(v)[1]))
end
end
## given code like
# % a = alloca
# ...
# memref(cast(%a), %b, constant size == sizeof(a))
#
# turn this into load/store, as this is more
# amenable to caching analysis infrastructure
function memcpy_alloca_to_loadstore(mod::LLVM.Module)
dl = datalayout(mod)
for f in functions(mod)
if length(blocks(f)) != 0
bb = first(blocks(f))
todel = Set{LLVM.Instruction}()
for alloca in instructions(bb)
if !isa(alloca, LLVM.AllocaInst)
continue
end
todo = Tuple{LLVM.Instruction,LLVM.Value}[(alloca, alloca)]
copy = nothing
legal = true
elty = LLVM.LLVMType(LLVM.API.LLVMGetAllocatedType(alloca))
lifetimestarts = LLVM.Instruction[]
while length(todo) > 0
cur, prev = pop!(todo)
if isa(cur, LLVM.AllocaInst) ||
isa(cur, LLVM.AddrSpaceCastInst) ||
isa(cur, LLVM.BitCastInst)
for u in LLVM.uses(cur)
u = LLVM.user(u)
push!(todo, (u, cur))
end
continue
end
if isa(cur, LLVM.CallInst) &&
isa(LLVM.called_operand(cur), LLVM.Function)
intr = LLVM.API.LLVMGetIntrinsicID(LLVM.called_operand(cur))
if intr == LLVM.Intrinsic("llvm.lifetime.start").id
push!(lifetimestarts, cur)
continue
end
if intr == LLVM.Intrinsic("llvm.lifetime.end").id
continue
end
if intr == LLVM.Intrinsic("llvm.memcpy").id
sz = operands(cur)[3]
if operands(cur)[1] == prev &&
isa(sz, LLVM.ConstantInt) &&
convert(Int, sz) == sizeof(dl, elty)
if copy === nothing || copy == cur
copy = cur
continue
end
end
end
end
# read only insts of arg, don't matter
if isa(cur, LLVM.LoadInst)
continue
end
if isa(cur, LLVM.CallInst) &&
isa(LLVM.called_operand(cur), LLVM.Function)
legalc = true
for (i, ci) in enumerate(operands(cur)[1:end-1])
if ci == prev
nocapture = false
readonly = false
for a in collect(
parameter_attributes(LLVM.called_operand(cur), i),
)
if kind(a) == kind(EnumAttribute("readonly"))
readonly = true
end
if kind(a) == kind(EnumAttribute("readnone"))
readonly = true
end
if kind(a) == kind(EnumAttribute("nocapture"))
nocapture = true
end
end
if !nocapture || !readonly
legalc = false
break
end
end
end
if legalc
continue
end
end
legal = false
break
end
if legal && copy !== nothing
B = LLVM.IRBuilder()
position!(B, copy)
dst = operands(copy)[1]
src = operands(copy)[2]
dst0 = bitcast!(
B,
dst,
LLVM.PointerType(LLVM.IntType(8), addrspace(value_type(dst))),
)
dst =
bitcast!(B, dst, LLVM.PointerType(elty, addrspace(value_type(dst))))
src =
bitcast!(B, src, LLVM.PointerType(elty, addrspace(value_type(src))))
src = load!(B, elty, src)
FT = LLVM.FunctionType(
LLVM.VoidType(),
[LLVM.IntType(64), value_type(dst0)],
)
lifetimestart, _ = get_function!(mod, "llvm.lifetime.start.p0i8", FT)
call!(
B,
FT,
lifetimestart,
LLVM.Value[LLVM.ConstantInt(Int64(sizeof(dl, elty))), dst0],
)
store!(B, src, dst)
push!(todel, copy)
end
for lt in lifetimestarts
push!(todel, lt)
end
end
for inst in todel
eraseInst(LLVM.parent(inst), inst)
end
end
end
end
# If there is a phi node of a decayed value, Enzyme may need to cache it
# Here we force all decayed pointer phis to first addrspace from 10
function nodecayed_phis!(mod::LLVM.Module)
# Simple handler to fix addrspace 11
#complex handler for addrspace 13, which itself comes from a load of an
# addrspace 10
for f in functions(mod)
guaranteedInactive = false
for attr in collect(function_attributes(f))
if !isa(attr, LLVM.StringAttribute)
continue
end
if kind(attr) == "enzyme_inactive"
guaranteedInactive = true
break
end
end
if guaranteedInactive
continue
end
entry_ft = LLVM.function_type(f)
RT = LLVM.return_type(entry_ft)
inactiveRet = RT == LLVM.VoidType()
for attr in collect(return_attributes(f))
if !isa(attr, LLVM.StringAttribute)
continue
end
if kind(attr) == "enzyme_inactive"
inactiveRet = true
break
end
end
if inactiveRet
for idx in length(collect(parameters(f)))
inactiveParm = false
for attr in collect(parameter_attributes(f, idx))
if !isa(attr, LLVM.StringAttribute)
continue
end
if kind(attr) == "enzyme_inactive"
inactiveParm = true
break
end
end
if !inactiveParm
inactiveRet = false
break
end
end
if inactiveRet
continue
end
end
offty = LLVM.IntType(8 * sizeof(Int))
i8 = LLVM.IntType(8)
for addr in (11, 13)
nextvs = Dict{LLVM.PHIInst,LLVM.PHIInst}()
mtodo = Vector{LLVM.PHIInst}[]
goffsets = Dict{LLVM.PHIInst,LLVM.PHIInst}()
nonphis = LLVM.Instruction[]
anyV = false
for bb in blocks(f)
todo = LLVM.PHIInst[]
nonphi = nothing
for inst in instructions(bb)
if !isa(inst, LLVM.PHIInst)
nonphi = inst
break
end
ty = value_type(inst)
if !isa(ty, LLVM.PointerType)
continue
end
if addrspace(ty) != addr
continue
end
if addr == 11
all_args = true
addrtodo = Value[inst]
seen = Set{LLVM.Value}()
while length(addrtodo) != 0
v = pop!(addrtodo)
base = get_base_object(v)
if in(base, seen)
continue
end
push!(seen, base)
if isa(base, LLVM.Argument) && addrspace(value_type(base)) == 11
continue
end
if isa(base, LLVM.PHIInst)
for (v, _) in LLVM.incoming(base)
push!(addrtodo, v)
end
continue
end
all_args = false
break
end
if all_args
continue
end
end
push!(todo, inst)
nb = IRBuilder()
position!(nb, inst)
el_ty = if addr == 11
eltype(ty)
else
LLVM.StructType(LLVM.LLVMType[])
end
nphi = phi!(
nb,
LLVM.PointerType(el_ty, 10),
"nodecayed." * LLVM.name(inst),
)
nextvs[inst] = nphi
anyV = true
goffsets[inst] = phi!(nb, offty, "nodecayedoff." * LLVM.name(inst))
end
push!(mtodo, todo)
push!(nonphis, nonphi)
end
for (bb, todo, nonphi) in zip(blocks(f), mtodo, nonphis)
for inst in todo
ty = value_type(inst)
el_ty = if addr == 11
eltype(ty)
else
LLVM.StructType(LLVM.LLVMType[])
end
nvs = Tuple{LLVM.Value,LLVM.BasicBlock}[]
offsets = Tuple{LLVM.Value,LLVM.BasicBlock}[]
for (v, pb) in LLVM.incoming(inst)
done = false
for ((nv, pb0), (offset, pb1)) in zip(nvs, offsets)
if pb0 == pb
push!(nvs, (nv, pb))
push!(offsets, (offset, pb))
done = true
break
end
end
if done
continue
end
b = IRBuilder()
position!(b, terminator(pb))
v0 = v
@inline function getparent(v, offset, hasload)
if addr == 11 && addrspace(value_type(v)) == 10
return v, offset, hasload
end
if addr == 13 && hasload && addrspace(value_type(v)) == 10
return v, offset, hasload
end
if addr == 13 && isa(v, LLVM.LoadInst) && !hasload
return getparent(operands(v)[1], offset, true)
end
if addr == 13 && isa(v, LLVM.ConstantExpr)
if opcode(v) == LLVM.API.LLVMAddrSpaceCast
v2 = operands(v)[1]
if addrspace(value_type(v2)) == 0
if addr == 13 && isa(v, LLVM.ConstantExpr)
v2 = const_addrspacecast(
operands(v)[1],
LLVM.PointerType(eltype(value_type(v)), 10),
)
return v2, offset, hasload
end
end
end
end
if addr == 11 && isa(v, LLVM.ConstantExpr)
if opcode(v) == LLVM.API.LLVMAddrSpaceCast
v2 = operands(v)[1]
if addrspace(value_type(v2)) == 10
return v2, offset, hasload
end
if addrspace(value_type(v2)) == 0
if addr == 11
v2 = const_addrspacecast(
v2,
LLVM.PointerType(eltype(value_type(v)), 10),
)
return v2, offset, hasload
end
end
if LLVM.isnull(v2)
v2 = const_addrspacecast(
v2,
LLVM.PointerType(eltype(value_type(v)), 10),
)
return v2, offset, hasload
end
end
end
if isa(v, LLVM.AddrSpaceCastInst)
if addrspace(value_type(operands(v)[1])) == 0
v2 = addrspacecast!(
b,
operands(v)[1],
LLVM.PointerType(eltype(value_type(v)), 10),
)
return v2, offset, hasload
end
nv, noffset, nhasload =
getparent(operands(v)[1], offset, hasload)
if eltype(value_type(nv)) != eltype(value_type(v))
nv = bitcast!(
b,
nv,
LLVM.PointerType(
eltype(value_type(v)),
addrspace(value_type(nv)),
),
)
end
return nv, noffset, nhasload
end
if isa(v, LLVM.BitCastInst)
v2, offset, skipload =
getparent(operands(v)[1], offset, hasload)
v2 = bitcast!(
b,
v2,
LLVM.PointerType(
eltype(value_type(v)),
addrspace(value_type(v2)),
),
)
@assert eltype(value_type(v2)) == eltype(value_type(v))
return v2, offset, skipload
end
if isa(v, LLVM.GetElementPtrInst) && all(
x -> (isa(x, LLVM.ConstantInt) && convert(Int, x) == 0),
operands(v)[2:end],
)
v2, offset, skipload =
getparent(operands(v)[1], offset, hasload)
v2 = bitcast!(
b,
v2,
LLVM.PointerType(
eltype(value_type(v)),
addrspace(value_type(v2)),
),
)
@assert eltype(value_type(v2)) == eltype(value_type(v))
return v2, offset, skipload
end
if isa(v, LLVM.GetElementPtrInst) && !hasload
v2, offset, skipload =
getparent(operands(v)[1], offset, hasload)
offset = nuwadd!(
b,
offset,
API.EnzymeComputeByteOffsetOfGEP(b, v, offty),
)
v2 = bitcast!(
b,
v2,
LLVM.PointerType(
eltype(value_type(v)),
addrspace(value_type(v2)),
),
)
@assert eltype(value_type(v2)) == eltype(value_type(v))
return v2, offset, skipload
end
if isa(v, LLVM.ConstantExpr) &&
opcode(v) == LLVM.API.LLVMGetElementPtr &&
!hasload
v2, offset, skipload =
getparent(operands(v)[1], offset, hasload)
offset = nuwadd!(
b,
offset,
API.EnzymeComputeByteOffsetOfGEP(b, v, offty),
)
v2 = bitcast!(
b,
v2,
LLVM.PointerType(
eltype(value_type(v)),
addrspace(value_type(v2)),
),
)
@assert eltype(value_type(v2)) == eltype(value_type(v))
return v2, offset, skipload
end
undeforpoison = isa(v, LLVM.UndefValue)
@static if LLVM.version() >= v"12"
undeforpoison |= isa(v, LLVM.PoisonValue)
end
if undeforpoison
return LLVM.UndefValue(
LLVM.PointerType(eltype(value_type(v)), 10),
),
offset,
addr == 13
end
if isa(v, LLVM.PHIInst) && !hasload && haskey(goffsets, v)
offset = nuwadd!(b, offset, goffsets[v])
nv = nextvs[v]
return nv, offset, addr == 13
end
if isa(v, LLVM.SelectInst)
lhs_v, lhs_offset, lhs_skipload =
getparent(operands(v)[2], offset, hasload)
rhs_v, rhs_offset, rhs_skipload =
getparent(operands(v)[3], offset, hasload)
if value_type(lhs_v) != value_type(rhs_v) ||
value_type(lhs_offset) != value_type(rhs_offset) ||
lhs_skipload != rhs_skipload
msg = sprint() do io
println(
io,
"Could not analyze [select] garbage collection behavior of",
)
println(io, " v0: ", string(v0))
println(io, " v: ", string(v))
println(io, " offset: ", string(offset))
println(io, " hasload: ", string(hasload))
println(io, " lhs_v", lhs_v)
println(io, " rhs_v", rhs_v)
println(io, " lhs_offset", lhs_offset)
println(io, " rhs_offset", rhs_offset)
println(io, " lhs_skipload", lhs_skipload)
println(io, " rhs_skipload", rhs_skipload)
end
bt = GPUCompiler.backtrace(inst)
throw(EnzymeInternalError(msg, string(f), bt))
end
return select!(b, operands(v)[1], lhs_v, rhs_v),
select!(b, operands(v)[1], lhs_offset, rhs_offset),
lhs_skipload
end
msg = sprint() do io
println(io, "Could not analyze garbage collection behavior of")
println(io, " inst: ", string(inst))
println(io, " v0: ", string(v0))
println(io, " v: ", string(v))
println(io, " offset: ", string(offset))
println(io, " hasload: ", string(hasload))
end
bt = GPUCompiler.backtrace(inst)
throw(EnzymeInternalError(msg, string(f), bt))
end
v, offset, hadload = getparent(v, LLVM.ConstantInt(offty, 0), false)