-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
passes.jl
2528 lines (2347 loc) Β· 100 KB
/
passes.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
# This file is a part of Julia. License is MIT: https://julialang.org/license
function is_known_call(@nospecialize(x), @nospecialize(func), ir::Union{IRCode,IncrementalCompact})
isexpr(x, :call) || return false
ft = argextype(x.args[1], ir)
return singleton_type(ft) === func
end
function is_known_invoke_or_call(@nospecialize(x), @nospecialize(func), ir::Union{IRCode,IncrementalCompact})
isinvoke = isexpr(x, :invoke)
(isinvoke || isexpr(x, :call)) || return false
ft = argextype(x.args[isinvoke ? 2 : 1], ir)
return singleton_type(ft) === func
end
struct SSAUse
kind::Symbol
idx::Int
end
GetfieldUse(idx::Int) = SSAUse(:getfield, idx)
PreserveUse(idx::Int) = SSAUse(:preserve, idx)
NoPreserve() = SSAUse(:nopreserve, 0)
IsdefinedUse(idx::Int) = SSAUse(:isdefined, idx)
FinalizerUse(idx::Int) = SSAUse(:finalizer, idx)
"""
du::SSADefUse
This struct keeps track of all uses of some mutable struct allocated in the current function:
- `du.uses::Vector{SSAUse}` are some "usages" (like `getfield`) of the struct
- `du.defs::Vector{Int}` are all instances of `setfield!` on the struct
The terminology refers to the uses/defs of the "slot bundle" that the mutable struct represents.
`du.uses` tracks all instances of `getfield` and `isdefined` calls on the struct.
Additionally it also tracks all instances of a `:foreigncall` that preserves of this mutable
struct. Somewhat counterintuitively, we don't actually need to make sure that the struct
itself is live (or even allocated) at a `ccall` site. If there are no other places where
the struct escapes (and thus e.g. where its address is taken), it need not be allocated.
We do however, need to make sure to preserve any elements of this struct.
"""
struct SSADefUse
uses::Vector{SSAUse}
defs::Vector{Int}
end
SSADefUse() = SSADefUse(SSAUse[], Int[])
function compute_live_ins(cfg::CFG, du::SSADefUse)
uses = Int[]
for use in du.uses
use.kind === :isdefined && continue # filter out `isdefined` usages
push!(uses, use.idx)
end
compute_live_ins(cfg, sort!(du.defs), uses)
end
function try_compute_field(ir::Union{IncrementalCompact,IRCode}, @nospecialize(field))
# fields are usually literals, handle them manually
if isa(field, QuoteNode)
field = field.value
elseif isa(field, Int) || isa(field, Symbol)
else
# try to resolve other constants, e.g. global reference
field = argextype(field, ir)
if isa(field, Const)
field = field.val
else
return nothing
end
end
return isa(field, Union{Int, Symbol}) ? field : nothing
end
# assume `stmt` is a call of `getfield`/`setfield!`/`isdefined`
function try_compute_fieldidx_stmt(ir::Union{IncrementalCompact,IRCode}, stmt::Expr, @nospecialize(typ))
field = try_compute_field(ir, stmt.args[3])
return try_compute_fieldidx(typ, field)
end
function find_curblock(domtree::DomTree, allblocks::BitSet, curblock::Int)
# TODO: This can be much faster by looking at current level and only
# searching for those blocks in a sorted order
while !(curblock in allblocks) && curblock !== 0
curblock = domtree.idoms_bb[curblock]
end
return curblock
end
function val_for_def_expr(ir::IRCode, def::Int, fidx::Int)
ex = ir[SSAValue(def)][:stmt]
if isexpr(ex, :new)
return ex.args[1+fidx]
else
@assert is_known_call(ex, setfield!, ir)
return ex.args[4]
end
end
function compute_value_for_block(ir::IRCode, domtree::DomTree, allblocks::BitSet, du::SSADefUse, phinodes::IdDict{Int, SSAValue}, fidx::Int, curblock::Int)
curblock = find_curblock(domtree, allblocks, curblock)
def = 0
for stmt in du.defs
if block_for_inst(ir.cfg, stmt) == curblock
def = max(def, stmt)
end
end
def == 0 ? phinodes[curblock] : val_for_def_expr(ir, def, fidx)
end
function compute_value_for_use(ir::IRCode, domtree::DomTree, allblocks::BitSet,
du::SSADefUse, phinodes::IdDict{Int, SSAValue}, fidx::Int, use::Int)
def, useblock, curblock = find_def_for_use(ir, domtree, allblocks, du, use)
if def == 0
if !haskey(phinodes, curblock)
# If this happens, we need to search the predecessors for defs. Which
# one doesn't matter - if it did, we'd have had a phinode
return compute_value_for_block(ir, domtree, allblocks, du, phinodes, fidx, first(ir.cfg.blocks[useblock].preds))
end
# The use is the phinode
return phinodes[curblock]
else
return val_for_def_expr(ir, def, fidx)
end
end
# even when the allocation contains an uninitialized field, we try an extra effort to check
# if this load at `idx` have any "safe" `setfield!` calls that define the field
function has_safe_def(
ir::IRCode, domtree::DomTree, allblocks::BitSet, du::SSADefUse,
newidx::Int, idx::Int)
def, _, _ = find_def_for_use(ir, domtree, allblocks, du, idx)
# will throw since we already checked this `:new` site doesn't define this field
def == newidx && return false
# found a "safe" definition
def β 0 && return true
# we may still be able to replace this load with `PhiNode`
# examine if all predecessors of `block` have any "safe" definition
block = block_for_inst(ir, idx)
seen = BitSet(block)
worklist = BitSet(ir.cfg.blocks[block].preds)
isempty(worklist) && return false
while !isempty(worklist)
pred = pop!(worklist)
# if this block has already been examined, bail out to avoid infinite cycles
pred in seen && return false
idx = last(ir.cfg.blocks[pred].stmts)
# NOTE `idx` isn't a load, thus we can use inclusive condition within the `find_def_for_use`
def, _, _ = find_def_for_use(ir, domtree, allblocks, du, idx, true)
# will throw since we already checked this `:new` site doesn't define this field
def == newidx && return false
push!(seen, pred)
# found a "safe" definition for this predecessor
def β 0 && continue
# check for the predecessors of this predecessor
for newpred in ir.cfg.blocks[pred].preds
push!(worklist, newpred)
end
end
return true
end
# find the first dominating def for the given use
function find_def_for_use(
ir::IRCode, domtree::DomTree, allblocks::BitSet, du::SSADefUse, use::Int, inclusive::Bool=false)
useblock = block_for_inst(ir.cfg, use)
curblock = find_curblock(domtree, allblocks, useblock)
local def = 0
for idx in du.defs
if block_for_inst(ir.cfg, idx) == curblock
if curblock != useblock
# Find the last def in this block
def = max(def, idx)
else
# Find the last def before our use
if inclusive
def = max(def, idx β€ use ? idx : 0)
else
def = max(def, idx < use ? idx : 0)
end
end
end
end
return def, useblock, curblock
end
function collect_leaves(compact::IncrementalCompact, @nospecialize(val), @nospecialize(typeconstraint), πβ::AbstractLattice,
predecessors = ((@nospecialize(def), compact::IncrementalCompact) -> isa(def, PhiNode) ? def.values : nothing))
if isa(val, Union{OldSSAValue, SSAValue})
val, typeconstraint = simple_walk_constraint(compact, val, typeconstraint)
end
return walk_to_defs(compact, val, typeconstraint, predecessors, πβ)
end
function trivial_walker(@nospecialize(pi), @nospecialize(idx))
return nothing
end
function pi_walker(@nospecialize(pi), @nospecialize(idx))
if isa(pi, PiNode)
return LiftedValue(pi.val)
end
return nothing
end
function simple_walk(compact::IncrementalCompact, @nospecialize(defssa#=::AnySSAValue=#), callback=trivial_walker)
while true
if isa(defssa, OldSSAValue)
if already_inserted(compact, defssa)
rename = compact.ssa_rename[defssa.id]
if isa(rename, Refined)
rename = rename.val
end
if isa(rename, AnySSAValue)
defssa = rename
continue
end
return rename
end
end
def = compact[defssa][:stmt]
if isa(def, AnySSAValue)
callback(def, defssa)
if isa(def, SSAValue)
is_old(compact, defssa) && (def = OldSSAValue(def.id))
end
defssa = def
elseif isa(def, Union{PhiNode, PhiCNode, GlobalRef})
return defssa
else
new_def = callback(def, defssa)
if new_def === nothing
return defssa
end
new_def = new_def.val
if !isa(new_def, AnySSAValue)
return new_def
elseif isa(new_def, SSAValue)
is_old(compact, defssa) && (new_def = OldSSAValue(new_def.id))
end
defssa = new_def
end
end
end
function simple_walk_constraint(compact::IncrementalCompact, @nospecialize(defssa#=::AnySSAValue=#),
@nospecialize(typeconstraint))
callback = function (@nospecialize(pi), @nospecialize(idx))
if isa(pi, PiNode)
typeconstraint = typeintersect(typeconstraint, widenconst(pi.typ))
return LiftedValue(pi.val)
end
return nothing
end
def = simple_walk(compact, defssa, callback)
return Pair{Any, Any}(def, typeconstraint)
end
"""
walk_to_defs(compact, val, typeconstraint, predecessors)
Starting at `val` walk use-def chains to get all the leaves feeding into this `val`
(pruning those leaves ruled out by path conditions).
`predecessors(def, compact)` is a callback which should return the set of possible
predecessors for a "phi-like" node (PhiNode or Core.ifelse) or `nothing` otherwise.
"""
function walk_to_defs(compact::IncrementalCompact, @nospecialize(defssa), @nospecialize(typeconstraint), predecessors, πβ::AbstractLattice)
visited_philikes = AnySSAValue[]
isa(defssa, AnySSAValue) || return Any[defssa], visited_philikes
def = compact[defssa][:stmt]
if predecessors(def, compact) === nothing
return Any[defssa], visited_philikes
end
visited_constraints = IdDict{AnySSAValue, Any}()
worklist_defs = AnySSAValue[]
worklist_constraints = Any[]
leaves = Any[]
push!(worklist_defs, defssa)
push!(worklist_constraints, typeconstraint)
while !isempty(worklist_defs)
defssa = pop!(worklist_defs)
typeconstraint = pop!(worklist_constraints)
visited_constraints[defssa] = typeconstraint
def = compact[defssa][:stmt]
values = predecessors(def, compact)
if values !== nothing
if isa(def, PhiNode) || length(values) > 1
push!(visited_philikes, defssa)
end
possible_predecessors = Int[]
for n in 1:length(values)
isassigned(values, n) || continue
val = values[n]
if is_old(compact, defssa) && isa(val, SSAValue)
val = OldSSAValue(val.id)
end
edge_typ = widenconst(argextype(val, compact))
hasintersect(edge_typ, typeconstraint) || continue
push!(possible_predecessors, n)
end
for n in possible_predecessors
val = values[n]
if is_old(compact, defssa) && isa(val, SSAValue)
val = OldSSAValue(val.id)
end
if isa(val, AnySSAValue)
new_def, new_constraint = simple_walk_constraint(compact, val, typeconstraint)
if isa(new_def, AnySSAValue)
if !haskey(visited_constraints, new_def)
push!(worklist_defs, new_def)
push!(worklist_constraints, new_constraint)
elseif !(new_constraint <: visited_constraints[new_def])
# We have reached the same definition via a different
# path, with a different type constraint. We may have
# to redo some work here with the wider typeconstraint
push!(worklist_defs, new_def)
push!(worklist_constraints, tmerge(πβ, new_constraint, visited_constraints[new_def]))
end
continue
end
val = new_def
end
if def === val
# This shouldn't really ever happen, but
# patterns like this can occur in dead code,
# so bail out.
break
else
push!(leaves, val)
end
continue
end
else
push!(leaves, defssa)
end
end
return leaves, visited_philikes
end
function record_immutable_preserve!(new_preserves::Vector{Any}, def::Expr, compact::IncrementalCompact)
args = isexpr(def, :new) ? def.args : def.args[2:end]
for i = 1:length(args)
arg = args[i]
if !isbitstype(widenconst(argextype(arg, compact)))
push!(new_preserves, arg)
end
end
end
function already_inserted(compact::IncrementalCompact, old::OldSSAValue)
id = old.id
if id < length(compact.ir.stmts)
return id < compact.idx
end
id -= length(compact.ir.stmts)
if id < length(compact.ir.new_nodes)
return already_inserted(compact, OldSSAValue(compact.ir.new_nodes.info[id].pos))
end
id -= length(compact.ir.new_nodes)
@assert id <= length(compact.pending_nodes)
return !(id in compact.pending_perm)
end
function is_pending(compact::IncrementalCompact, old::OldSSAValue)
return old.id > length(compact.ir.stmts) + length(compact.ir.new_nodes)
end
function is_getfield_captures(@nospecialize(def), compact::IncrementalCompact, πβ::AbstractLattice)
isa(def, Expr) || return false
length(def.args) >= 3 || return false
is_known_call(def, getfield, compact) || return false
which = argextype(def.args[3], compact)
isa(which, Const) || return false
which.val === :captures || return false
oc = argextype(def.args[2], compact)
return β(πβ, oc, Core.OpaqueClosure)
end
struct LiftedValue
val
LiftedValue(@nospecialize val) = new(val)
end
const LiftedLeaves = IdDict{Any, Union{Nothing,LiftedValue}}
const LiftedDefs = IdDict{Any, Bool}
# try to compute lifted values that can replace `getfield(x, field)` call
# where `x` is an immutable struct that are defined at any of `leaves`
function lift_leaves(compact::IncrementalCompact, field::Int,
leaves::Vector{Any}, πβ::AbstractLattice)
# For every leaf, the lifted value
lifted_leaves = LiftedLeaves()
maybe_undef = false
for i = 1:length(leaves)
leaf = leaves[i]
cache_key = leaf
if isa(leaf, AnySSAValue)
(def, leaf) = walk_to_def(compact, leaf)
if is_known_call(def, tuple, compact) && 1 β€ field < length(def.args)
lift_arg!(compact, leaf, cache_key, def, 1+field, lifted_leaves)
continue
elseif isexpr(def, :new)
typ = unwrap_unionall(widenconst(types(compact)[leaf]))
(isa(typ, DataType) && !isabstracttype(typ)) || return nothing
if ismutabletype(typ)
isconst(typ, field) || return nothing
end
if length(def.args) < 1+field
if field > fieldcount(typ)
return nothing
end
ftyp = fieldtype(typ, field)
if !isbitstype(ftyp)
# On this branch, this will be a guaranteed UndefRefError.
# We use the regular undef mechanic to lift this to a boolean slot
maybe_undef = true
lifted_leaves[cache_key] = nothing
continue
end
return nothing
end
lift_arg!(compact, leaf, cache_key, def, 1+field, lifted_leaves)
continue
# NOTE we can enable this, but most `:splatnew` expressions are transformed into
# `:new` expressions by the inlinear
# elseif isexpr(def, :splatnew) && length(def.args) == 2 && isa(def.args[2], AnySSAValue)
# tplssa = def.args[2]::AnySSAValue
# tplexpr = compact[tplssa][:stmt]
# if is_known_call(tplexpr, tuple, compact) && 1 β€ field < length(tplexpr.args)
# lift_arg!(compact, tplssa, cache_key, tplexpr, 1+field, lifted_leaves)
# continue
# end
# return nothing
elseif is_getfield_captures(def, compact, πβ)
# Walk to new_opaque_closure
ocleaf = def.args[2]
if isa(ocleaf, AnySSAValue)
ocleaf = simple_walk(compact, ocleaf)
end
ocdef, _ = walk_to_def(compact, ocleaf)
if isexpr(ocdef, :new_opaque_closure) && isa(field, Int) && 1 β€ field β€ length(ocdef.args)-4
lift_arg!(compact, leaf, cache_key, ocdef, 4+field, lifted_leaves)
continue
end
return nothing
else
typ = argextype(leaf, compact)
if !isa(typ, Const)
# TODO: (disabled since #27126)
# If the leaf is an old ssa value, insert a getfield here
# We will revisit this getfield later when compaction gets
# to the appropriate point.
# N.B.: This can be a bit dangerous because it can lead to
# infinite loops if we accidentally insert a node just ahead
# of where we are
return nothing
end
leaf = typ.val
# Fall through to below
end
elseif isa(leaf, QuoteNode)
leaf = leaf.value
elseif isa(leaf, GlobalRef)
mod, name = leaf.mod, leaf.name
if isdefined(mod, name) && isconst(mod, name)
leaf = getglobal(mod, name)
else
return nothing
end
elseif isa(leaf, Argument) || isa(leaf, Expr)
return nothing
end
ismutable(leaf) && return nothing
isdefined(leaf, field) || return nothing
val = getfield(leaf, field)
is_inlineable_constant(val) || return nothing
lifted_leaves[cache_key] = LiftedValue(quoted(val))
end
return lifted_leaves, maybe_undef
end
function lift_arg!(
compact::IncrementalCompact, @nospecialize(leaf), @nospecialize(cache_key),
stmt::Expr, argidx::Int, lifted_leaves::LiftedLeaves)
lifted = stmt.args[argidx]
if is_old(compact, leaf) && isa(lifted, SSAValue)
lifted = OldSSAValue(lifted.id)
if already_inserted(compact, lifted)
new_lifted = compact.ssa_rename[lifted.id]
if isa(new_lifted, Refined)
new_lifted = new_lifted.val
end
# Special case: If lifted happens to be the statement we're currently processing,
# leave it as old SSAValue in case we decide to handle this in the renamer
if !isa(new_lifted, SSAValue) || new_lifted != SSAValue(compact.result_idx-1)
lifted = new_lifted
end
end
end
lifted_leaves[cache_key] = LiftedValue(lifted)
return nothing
end
function walk_to_def(compact::IncrementalCompact, @nospecialize(leaf))
if isa(leaf, OldSSAValue) && already_inserted(compact, leaf)
leaf = compact.ssa_rename[leaf.id]
if isa(leaf, Refined)
leaf = leaf.val
end
if isa(leaf, AnySSAValue)
leaf = simple_walk(compact, leaf)
end
if isa(leaf, AnySSAValue)
def = compact[leaf][:stmt]
else
def = leaf
end
elseif isa(leaf, AnySSAValue)
def = compact[leaf][:stmt]
else
def = leaf
end
return Pair{Any, Any}(def, leaf)
end
"""
lift_comparison!(cmp, compact::IncrementalCompact, idx::Int, stmt::Expr, πβ::AbstractLattice)
Replaces `cmp(Ο(x, y)::Union{X,Y}, constant)` by `Ο(cmp(x, constant), cmp(y, constant))`,
where `cmp(x, constant)` and `cmp(y, constant)` can be replaced with constant `Bool`eans.
It helps codegen avoid generating expensive code for `cmp` with `Union` types.
In particular, this is supposed to improve the performance of the iteration protocol:
```julia
while x !== nothing
x = iterate(...)::Union{Nothing,Tuple{Any,Any}}
end
```
"""
function lift_comparison! end
function lift_comparison!(::typeof(===), compact::IncrementalCompact,
idx::Int, stmt::Expr, πβ::AbstractLattice)
args = stmt.args
length(args) == 3 || return
lhs, rhs = args[2], args[3]
vl = argextype(lhs, compact)
vr = argextype(rhs, compact)
if isa(vl, Const)
isa(vr, Const) && return
val = rhs
cmp = vl
elseif isa(vr, Const)
val = lhs
cmp = vr
else
return
end
lift_comparison_leaves!(egal_tfunc, compact, val, cmp, idx, πβ)
end
function lift_comparison!(::typeof(isa), compact::IncrementalCompact,
idx::Int, stmt::Expr, πβ::AbstractLattice)
args = stmt.args
length(args) == 3 || return
cmp = argextype(args[3], compact)
val = args[2]
lift_comparison_leaves!(isa_tfunc, compact, val, cmp, idx, πβ)
end
function lift_comparison!(::typeof(isdefined), compact::IncrementalCompact,
idx::Int, stmt::Expr, πβ::AbstractLattice)
args = stmt.args
length(args) == 3 || return
cmp = argextype(args[3], compact)
isa(cmp, Const) || return # `isdefined_tfunc` won't return Const
val = args[2]
lift_comparison_leaves!(isdefined_tfunc, compact, val, cmp, idx, πβ)
end
function phi_or_ifelse_predecessors(@nospecialize(def), compact::IncrementalCompact)
isa(def, PhiNode) && return def.values
is_known_call(def, Core.ifelse, compact) && return def.args[3:4]
return nothing
end
function lift_comparison_leaves!(@specialize(tfunc),
compact::IncrementalCompact, @nospecialize(val), @nospecialize(cmp),
idx::Int, πβ::AbstractLattice)
typeconstraint = widenconst(argextype(val, compact))
if isa(val, Union{OldSSAValue, SSAValue})
val, typeconstraint = simple_walk_constraint(compact, val, typeconstraint)
end
isa(typeconstraint, Union) || return # bail out if there won't be a good chance for lifting
leaves, visited_philikes = collect_leaves(compact, val, typeconstraint, πβ, phi_or_ifelse_predecessors)
length(leaves) β€ 1 && return # bail out if we don't have multiple leaves
# check if we can evaluate the comparison for each one of the leaves
lifted_leaves = nothing
for i = 1:length(leaves)
leaf = leaves[i]
result = tfunc(πβ, argextype(leaf, compact), cmp)
if isa(result, Const)
if lifted_leaves === nothing
lifted_leaves = LiftedLeaves()
end
lifted_leaves[leaf] = LiftedValue(result.val)
else
return # TODO In some cases it might be profitable to hoist the comparison here
end
end
# perform lifting
(lifted_val, nest) = perform_lifting!(compact,
visited_philikes, cmp, Bool, lifted_leaves::LiftedLeaves, val, nothing)
compact[idx] = (lifted_val::LiftedValue).val
finish_phi_nest!(compact, nest)
end
struct IfElseCall
call::Expr
end
# An intermediate data structure used for lifting expressions through a
# "phi-like" instruction (either a PhiNode or a call to Core.ifelse)
struct LiftedPhilike
ssa::AnySSAValue
node::Union{PhiNode,IfElseCall}
need_argupdate::Bool
end
struct SkipToken end; const SKIP_TOKEN = SkipToken()
function lifted_value(compact::IncrementalCompact, @nospecialize(old_node_ssa#=::AnySSAValue=#), @nospecialize(old_value),
lifted_philikes::Vector{LiftedPhilike}, lifted_leaves::Union{LiftedLeaves, LiftedDefs}, reverse_mapping::IdDict{AnySSAValue, Int},
walker_callback)
val = old_value
if is_old(compact, old_node_ssa) && isa(val, SSAValue)
val = OldSSAValue(val.id)
end
if isa(val, AnySSAValue)
val = simple_walk(compact, val, def_walker(lifted_leaves, reverse_mapping, walker_callback))
end
if val in keys(lifted_leaves)
lifted_val = lifted_leaves[val]
if isa(lifted_leaves, LiftedDefs)
return lifted_val
end
lifted_val === nothing && return UNDEF_TOKEN
val = lifted_val.val
if isa(val, AnySSAValue)
val = simple_walk(compact, val, pi_walker)
end
return val
elseif isa(val, AnySSAValue) && val in keys(reverse_mapping)
return lifted_philikes[reverse_mapping[val]].ssa
else
return SKIP_TOKEN # Probably ignored by path condition, skip this
end
end
function is_old(compact, @nospecialize(old_node_ssa))
isa(old_node_ssa, OldSSAValue) || return false
is_pending(compact, old_node_ssa) && return false
already_inserted(compact, old_node_ssa) && return false
return true
end
struct PhiNest{C}
visited_philikes::Vector{AnySSAValue}
lifted_philikes::Vector{LiftedPhilike}
lifted_leaves::Union{LiftedLeaves, LiftedDefs}
reverse_mapping::IdDict{AnySSAValue, Int}
walker_callback::C
end
function finish_phi_nest!(compact::IncrementalCompact, nest::PhiNest)
(;visited_philikes, lifted_philikes, lifted_leaves, reverse_mapping, walker_callback) = nest
nphilikes = length(lifted_philikes)
# Fix up arguments
for i = 1:nphilikes
(old_node_ssa, lf) = visited_philikes[i], lifted_philikes[i]
lf.need_argupdate || continue
should_count = !isa(lf.ssa, OldSSAValue) || already_inserted(compact, lf.ssa)
lfnode = lf.node
if isa(lfnode, PhiNode)
old_node = compact[old_node_ssa][:stmt]::PhiNode
new_node = lfnode
for i = 1:length(old_node.values)
isassigned(old_node.values, i) || continue
val = lifted_value(compact, old_node_ssa, old_node.values[i],
lifted_philikes, lifted_leaves, reverse_mapping, walker_callback)
val !== SKIP_TOKEN && push!(new_node.edges, old_node.edges[i])
if val === UNDEF_TOKEN
resize!(new_node.values, length(new_node.values)+1)
elseif val !== SKIP_TOKEN
should_count && _count_added_node!(compact, val)
push!(new_node.values, val)
end
end
elseif isa(lfnode, IfElseCall)
old_node = compact[old_node_ssa][:stmt]::Expr
then_result, else_result = old_node.args[3], old_node.args[4]
then_result = lifted_value(compact, old_node_ssa, then_result,
lifted_philikes, lifted_leaves, reverse_mapping, walker_callback)
else_result = lifted_value(compact, old_node_ssa, else_result,
lifted_philikes, lifted_leaves, reverse_mapping, walker_callback)
# In cases where the Core.ifelse condition is statically-known, e.g., thanks
# to a PiNode from a guarding conditional, replace with the remaining branch.
if then_result === SKIP_TOKEN || else_result === SKIP_TOKEN
only_result = (then_result === SKIP_TOKEN) ? else_result : then_result
# Replace Core.ifelse(%cond, %a, %b) with %a
compact[lf.ssa] = only_result
# Note: Core.ifelse(%cond, %a, %b) has observable effects (!nothrow), but since
# we have not deleted the preceding statement that this was derived from, this
# replacement is safe, i.e. it will not affect the effects observed.
continue
end
@assert then_result !== SKIP_TOKEN && then_result !== UNDEF_TOKEN
@assert else_result !== SKIP_TOKEN && else_result !== UNDEF_TOKEN
if should_count
_count_added_node!(compact, then_result)
_count_added_node!(compact, else_result)
end
push!(lfnode.call.args, then_result)
push!(lfnode.call.args, else_result)
end
end
end
function def_walker(lifted_leaves::Union{LiftedLeaves, LiftedDefs}, reverse_mapping::IdDict{AnySSAValue, Int}, walker_callback)
function (@nospecialize(walk_def), @nospecialize(defssa))
if (defssa in keys(lifted_leaves)) || (isa(defssa, AnySSAValue) && defssa in keys(reverse_mapping))
return nothing
end
isa(walk_def, PiNode) && return LiftedValue(walk_def.val)
return walker_callback(walk_def, defssa)
end
end
function perform_lifting!(compact::IncrementalCompact,
visited_philikes::Vector{AnySSAValue}, @nospecialize(cache_key),
@nospecialize(result_t), lifted_leaves::Union{LiftedLeaves, LiftedDefs}, @nospecialize(stmt_val),
lazydomtree::Union{LazyDomtree,Nothing}, walker_callback = trivial_walker)
reverse_mapping = IdDict{AnySSAValue, Int}()
for id in 1:length(visited_philikes)
reverse_mapping[visited_philikes[id]] = id
end
# Check if all the lifted leaves are the same
local the_leaf
all_same = true
for (_, val) in lifted_leaves
if !@isdefined(the_leaf)
the_leaf = val
continue
end
if val !== the_leaf
all_same = false
end
end
if all_same && isa(the_leaf, LiftedValue)
dominates_all = true
the_leaf_val = the_leaf.val
if isa(the_leaf_val, AnySSAValue)
if lazydomtree === nothing
# Must conservatively assume this
dominates_all = false
else
# This code guards against the possibility of accidentally forwarding a value from a
# previous iteration. Consider for example:
#
# %p = phi(%arg, %t)
# %b = <...>
# %c = getfield(%p, 1)
# %t = tuple(%b)
#
# It would be incorrect to replace `%c` by `%b`, because that would read the value of
# `%b` in the *current* iteration, while the value of `%b` that comes in via `%p` is
# that of the previous iteration.
domtree = get!(lazydomtree)
for item in visited_philikes
if !dominates_ssa(compact, domtree, the_leaf_val, item)
dominates_all = false
break
end
end
end
end
if dominates_all
if isa(the_leaf_val, OldSSAValue)
the_leaf = LiftedValue(simple_walk(compact, the_leaf_val))
end
return Pair{Any, PhiNest}(the_leaf, PhiNest(visited_philikes, Vector{LiftedPhilike}(undef, 0), lifted_leaves, reverse_mapping, walker_callback))
end
end
# Insert PhiNodes
nphilikes = length(visited_philikes)
lifted_philikes = Vector{LiftedPhilike}(undef, nphilikes)
for i = 1:nphilikes
old_ssa = visited_philikes[i]
old_inst = compact[old_ssa]
old_node = old_inst[:stmt]::Union{PhiNode,Expr}
if isa(old_node, PhiNode)
new_node = PhiNode()
ssa = insert_node!(compact, old_ssa, effect_free_and_nothrow(NewInstruction(new_node, result_t)))
lifted_philikes[i] = LiftedPhilike(ssa, new_node, true)
else
@assert is_known_call(old_node, Core.ifelse, compact)
ifelse_func, condition = old_node.args
if is_old(compact, old_ssa) && isa(condition, SSAValue)
condition = OldSSAValue(condition.id)
end
new_node = Expr(:call, ifelse_func, condition) # Renamed then_result, else_result added below
new_inst = NewInstruction(new_node, result_t, NoCallInfo(), old_inst[:line], old_inst[:flag])
ssa = insert_node!(compact, old_ssa, new_inst, #= attach_after =# true)
lifted_philikes[i] = LiftedPhilike(ssa, IfElseCall(new_node), true)
end
end
# Fixup the stmt itself
if isa(stmt_val, Union{SSAValue, OldSSAValue})
stmt_val = simple_walk(compact, stmt_val, def_walker(lifted_leaves, reverse_mapping, walker_callback))
end
if stmt_val in keys(lifted_leaves)
stmt_val = lifted_leaves[stmt_val]
elseif isa(stmt_val, AnySSAValue) && stmt_val in keys(reverse_mapping)
stmt_val = LiftedValue(lifted_philikes[reverse_mapping[stmt_val]].ssa)
else
error()
end
return Pair{Any, PhiNest}(stmt_val, PhiNest(visited_philikes, lifted_philikes, lifted_leaves, reverse_mapping, walker_callback))
end
function lift_svec_ref!(compact::IncrementalCompact, idx::Int, stmt::Expr)
length(stmt.args) != 3 && return
vec = stmt.args[2]
val = stmt.args[3]
valT = argextype(val, compact)
(isa(valT, Const) && isa(valT.val, Int)) || return
valI = valT.val::Int
valI >= 1 || return
if isa(vec, SimpleVector)
valI <= length(vec) || return
compact[idx] = quoted(vec[valI])
elseif isa(vec, SSAValue)
def = compact[vec][:stmt]
if is_known_call(def, Core.svec, compact)
valI <= length(def.args) - 1 || return
compact[idx] = def.args[valI+1]
elseif is_known_call(def, Core._compute_sparams, compact)
valI != 1 && return # TODO generalize this for more values of valI
res = _lift_svec_ref(def, compact)
res === nothing && return
compact[idx] = res.val
end
end
return
end
function lift_leaves_keyvalue(compact::IncrementalCompact, @nospecialize(key),
leaves::Vector{Any}, πβ::AbstractLattice)
# For every leaf, the lifted value
lifted_leaves = LiftedLeaves()
for i = 1:length(leaves)
leaf = leaves[i]
cache_key = leaf
if isa(leaf, AnySSAValue)
(def, leaf) = walk_to_def(compact, leaf)
if is_known_invoke_or_call(def, Core.OptimizedGenerics.KeyValue.set, compact)
@assert isexpr(def, :invoke)
if length(def.args) in (5, 6)
set_key = def.args[end-1]
set_val_idx = length(def.args)
elseif length(def.args) == 4
# Key is deleted
# TODO: Model this
return nothing
elseif length(def.args) == 3
# The whole collection is deleted
# TODO: Model this
return nothing
else
return nothing
end
if set_key === key || (egal_tfunc(πβ, argextype(key, compact), argextype(set_key, compact)) == Const(true))
lift_arg!(compact, leaf, cache_key, def, set_val_idx, lifted_leaves)
continue
end
end
end
return nothing
end
return lifted_leaves
end
function keyvalue_predecessors(@nospecialize(key), πβ::AbstractLattice)
function(@nospecialize(def), compact::IncrementalCompact)
if is_known_invoke_or_call(def, Core.OptimizedGenerics.KeyValue.set, compact)
@assert isexpr(def, :invoke)
if length(def.args) in (5, 6)
collection = def.args[end-2]
set_key = def.args[end-1]
set_val_idx = length(def.args)
elseif length(def.args) == 4
collection = def.args[end-1]
# Key is deleted
# TODO: Model this
return nothing
elseif length(def.args) == 3
collection = def.args[end]
# The whole collection is deleted
# TODO: Model this
return nothing
else
return nothing
end
if set_key === key || (egal_tfunc(πβ, argextype(key, compact), argextype(set_key, compact)) == Const(true))
# This is an actual def
return nothing
end
return Any[collection]
end
return phi_or_ifelse_predecessors(def, compact)
end
end
function lift_keyvalue_get!(compact::IncrementalCompact, idx::Int, stmt::Expr, πβ::AbstractLattice)
collection = stmt.args[end-1]
key = stmt.args[end]
leaves, visited_philikes = collect_leaves(compact, collection, Any, πβ, keyvalue_predecessors(key, πβ))
isempty(leaves) && return
lifted_leaves = lift_leaves_keyvalue(compact, key, leaves, πβ)
lifted_leaves === nothing && return
result_t = Union{}
for v in values(lifted_leaves)
v === nothing && return
result_t = tmerge(πβ, result_t, argextype(v.val, compact))
end
function keyvalue_walker(@nospecialize(def), _)
if is_known_invoke_or_call(def, Core.OptimizedGenerics.KeyValue.set, compact)
@assert length(def.args) in (5, 6)
return LiftedValue(def.args[end-2])
end
return nothing
end
(lifted_val, nest) = perform_lifting!(compact,
visited_philikes, key, result_t, lifted_leaves, collection, nothing,
keyvalue_walker)
compact[idx] = lifted_val === nothing ? nothing : Expr(:call, GlobalRef(Core, :tuple), lifted_val.val)
finish_phi_nest!(compact, nest)
if lifted_val !== nothing
if !β(πβ, compact[SSAValue(idx)][:type], tuple_tfunc(πβ, Any[result_t]))
add_flag!(compact[SSAValue(idx)], IR_FLAG_REFINED)
end
end
return
end
# TODO: We could do the whole lifing machinery here, but really all
# we want to do is clean this up when it got inserted by inlining,
# which always targets simple `svec` call or `_compute_sparams`,
# so this specialized lifting would be enough
@inline function _lift_svec_ref(def::Expr, compact::IncrementalCompact)
length(def.args) >= 3 || return nothing
m = argextype(def.args[2], compact)
isa(m, Const) || return nothing
m = m.val
isa(m, Method) || return nothing
# TODO: More general structural analysis of the intersection
sig = m.sig
isa(sig, UnionAll) || return nothing
tvar = sig.var
sig = sig.body
isa(sig, DataType) || return nothing
sig.name === Tuple.name || return nothing