-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
optimize.jl
1470 lines (1363 loc) · 56.7 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
# This file is a part of Julia. License is MIT: https://julialang.org/license
#############
# constants #
#############
# The slot has uses that are not statically dominated by any assignment
# This is implied by `SLOT_USEDUNDEF`.
# If this is not set, all the uses are (statically) dominated by the defs.
# In particular, if a slot has `AssignedOnce && !StaticUndef`, it is an SSA.
const SLOT_STATICUNDEF = 1 # slot might be used before it is defined (structurally)
const SLOT_ASSIGNEDONCE = 16 # slot is assigned to only once
const SLOT_USEDUNDEF = 32 # slot has uses that might raise UndefVarError
# const SLOT_CALLED = 64
# NOTE make sure to sync the flag definitions below with julia.h and `jl_code_info_set_ir` in method.c
const IR_FLAG_NULL = zero(UInt32)
# This statement is marked as @inbounds by user.
# Ff replaced by inlining, any contained boundschecks may be removed.
const IR_FLAG_INBOUNDS = one(UInt32) << 0
# This statement is marked as @inline by user
const IR_FLAG_INLINE = one(UInt32) << 1
# This statement is marked as @noinline by user
const IR_FLAG_NOINLINE = one(UInt32) << 2
# This statement is on a code path that eventually `throw`s.
const IR_FLAG_THROW_BLOCK = one(UInt32) << 3
# An optimization pass has updated this statement in a way that may
# have exposed information that inference did not see. Re-running
# inference on this statement may be profitable.
const IR_FLAG_REFINED = one(UInt32) << 4
# This statement is proven :consistent
const IR_FLAG_CONSISTENT = one(UInt32) << 5
# This statement is proven :effect_free
const IR_FLAG_EFFECT_FREE = one(UInt32) << 6
# This statement is proven :nothrow
const IR_FLAG_NOTHROW = one(UInt32) << 7
# This statement is proven :terminates
const IR_FLAG_TERMINATES = one(UInt32) << 8
# This statement is proven :noub
const IR_FLAG_NOUB = one(UInt32) << 9
# TODO: Both of these should eventually go away once
# This statement is :effect_free == EFFECT_FREE_IF_INACCESSIBLEMEMONLY
const IR_FLAG_EFIIMO = one(UInt32) << 10
# This statement is :inaccessiblememonly == INACCESSIBLEMEM_OR_ARGMEMONLY
const IR_FLAG_INACCESSIBLEMEM_OR_ARGMEM = one(UInt32) << 11
const NUM_IR_FLAGS = 12 # sync with julia.h
const IR_FLAGS_EFFECTS =
IR_FLAG_CONSISTENT | IR_FLAG_EFFECT_FREE | IR_FLAG_NOTHROW | IR_FLAG_NOUB
const IR_FLAGS_REMOVABLE = IR_FLAG_EFFECT_FREE | IR_FLAG_NOTHROW
const IR_FLAGS_NEEDS_EA = IR_FLAG_EFIIMO | IR_FLAG_INACCESSIBLEMEM_OR_ARGMEM
has_flag(curr::UInt32, flag::UInt32) = (curr & flag) == flag
function flags_for_effects(effects::Effects)
flags = zero(UInt32)
if is_consistent(effects)
flags |= IR_FLAG_CONSISTENT
end
if is_effect_free(effects)
flags |= IR_FLAG_EFFECT_FREE
elseif is_effect_free_if_inaccessiblememonly(effects)
flags |= IR_FLAG_EFIIMO
end
if is_nothrow(effects)
flags |= IR_FLAG_NOTHROW
end
if is_inaccessiblemem_or_argmemonly(effects)
flags |= IR_FLAG_INACCESSIBLEMEM_OR_ARGMEM
end
if is_noub(effects)
flags |= IR_FLAG_NOUB
end
return flags
end
const TOP_TUPLE = GlobalRef(Core, :tuple)
# This corresponds to the type of `CodeInfo`'s `inlining_cost` field
const InlineCostType = UInt16
const MAX_INLINE_COST = typemax(InlineCostType)
const MIN_INLINE_COST = InlineCostType(10)
const MaybeCompressed = Union{CodeInfo, String}
is_inlineable(@nospecialize src::MaybeCompressed) =
ccall(:jl_ir_inlining_cost, InlineCostType, (Any,), src) != MAX_INLINE_COST
set_inlineable!(src::CodeInfo, val::Bool) =
src.inlining_cost = (val ? MIN_INLINE_COST : MAX_INLINE_COST)
function inline_cost_clamp(x::Int)
x > MAX_INLINE_COST && return MAX_INLINE_COST
x < MIN_INLINE_COST && return MIN_INLINE_COST
return convert(InlineCostType, x)
end
is_declared_inline(@nospecialize src::MaybeCompressed) =
ccall(:jl_ir_flag_inlining, UInt8, (Any,), src) == 1
is_declared_noinline(@nospecialize src::MaybeCompressed) =
ccall(:jl_ir_flag_inlining, UInt8, (Any,), src) == 2
#####################
# OptimizationState #
#####################
# return whether this src should be inlined. If so, retrieve_ir_for_inlining must return an IRCode from it
function src_inlining_policy(interp::AbstractInterpreter,
@nospecialize(src), @nospecialize(info::CallInfo), stmt_flag::UInt32)
if isa(src, MaybeCompressed)
src_inlineable = is_stmt_inline(stmt_flag) || is_inlineable(src)
return src_inlineable
elseif isa(src, IRCode)
return true
elseif isa(src, SemiConcreteResult)
return true
end
@assert !isa(src, CodeInstance) # handled by caller
return false
end
function inlining_policy end # deprecated legacy name used by Cthulhu
struct InliningState{Interp<:AbstractInterpreter}
edges::Vector{Any}
world::UInt
interp::Interp
end
function InliningState(sv::InferenceState, interp::AbstractInterpreter)
edges = sv.stmt_edges[1]::Vector{Any}
return InliningState(edges, sv.world, interp)
end
function InliningState(interp::AbstractInterpreter)
return InliningState(Any[], get_inference_world(interp), interp)
end
# get `code_cache(::AbstractInterpreter)` from `state::InliningState`
code_cache(state::InliningState) = WorldView(code_cache(state.interp), state.world)
mutable struct OptimizationState{Interp<:AbstractInterpreter}
linfo::MethodInstance
src::CodeInfo
ir::Union{Nothing, IRCode}
stmt_info::Vector{CallInfo}
mod::Module
sptypes::Vector{VarState}
slottypes::Vector{Any}
inlining::InliningState{Interp}
cfg::CFG
unreachable::BitSet
bb_vartables::Vector{Union{Nothing,VarTable}}
insert_coverage::Bool
end
function OptimizationState(sv::InferenceState, interp::AbstractInterpreter)
inlining = InliningState(sv, interp)
return OptimizationState(sv.linfo, sv.src, nothing, sv.stmt_info, sv.mod,
sv.sptypes, sv.slottypes, inlining, sv.cfg,
sv.unreachable, sv.bb_vartables, sv.insert_coverage)
end
function OptimizationState(linfo::MethodInstance, src::CodeInfo, interp::AbstractInterpreter)
# prepare src for running optimization passes if it isn't already
nssavalues = src.ssavaluetypes
if nssavalues isa Int
src.ssavaluetypes = Any[ Any for i = 1:nssavalues ]
else
nssavalues = length(src.ssavaluetypes::Vector{Any})
end
sptypes = sptypes_from_meth_instance(linfo)
nslots = length(src.slotflags)
slottypes = src.slottypes
if slottypes === nothing
slottypes = Any[ Any for i = 1:nslots ]
end
stmt_info = CallInfo[ NoCallInfo() for i = 1:nssavalues ]
# cache some useful state computations
def = linfo.def
mod = isa(def, Method) ? def.module : def
# Allow using the global MI cache, but don't track edges.
# This method is mostly used for unit testing the optimizer
inlining = InliningState(interp)
cfg = compute_basic_blocks(src.code)
unreachable = BitSet()
bb_vartables = Union{VarTable,Nothing}[]
for block = 1:length(cfg.blocks)
push!(bb_vartables, VarState[
VarState(slottypes[slot], src.slotflags[slot] & SLOT_USEDUNDEF != 0)
for slot = 1:nslots
])
end
return OptimizationState(linfo, src, nothing, stmt_info, mod, sptypes, slottypes, inlining, cfg, unreachable, bb_vartables, false)
end
function OptimizationState(linfo::MethodInstance, interp::AbstractInterpreter)
world = get_inference_world(interp)
src = retrieve_code_info(linfo, world)
src === nothing && return nothing
return OptimizationState(linfo, src, interp)
end
function argextype end # imported by EscapeAnalysis
function try_compute_field end # imported by EscapeAnalysis
include("compiler/ssair/heap.jl")
include("compiler/ssair/slot2ssa.jl")
include("compiler/ssair/inlining.jl")
include("compiler/ssair/verify.jl")
include("compiler/ssair/legacy.jl")
include("compiler/ssair/EscapeAnalysis/EscapeAnalysis.jl")
include("compiler/ssair/passes.jl")
include("compiler/ssair/irinterp.jl")
function ir_to_codeinf!(opt::OptimizationState)
(; linfo, src) = opt
src = ir_to_codeinf!(src, opt.ir::IRCode)
opt.ir = nothing
maybe_validate_code(linfo, src, "optimized")
return src
end
function ir_to_codeinf!(src::CodeInfo, ir::IRCode)
replace_code_newstyle!(src, ir)
widen_all_consts!(src)
return src
end
# widen all Const elements in type annotations
function widen_all_consts!(src::CodeInfo)
ssavaluetypes = src.ssavaluetypes::Vector{Any}
for i = 1:length(ssavaluetypes)
ssavaluetypes[i] = widenconst(ssavaluetypes[i])
end
for i = 1:length(src.code)
x = src.code[i]
if isa(x, PiNode)
src.code[i] = PiNode(x.val, widenconst(x.typ))
end
end
return src
end
#########
# logic #
#########
_topmod(sv::OptimizationState) = _topmod(sv.mod)
is_stmt_inline(stmt_flag::UInt32) = has_flag(stmt_flag, IR_FLAG_INLINE)
is_stmt_noinline(stmt_flag::UInt32) = has_flag(stmt_flag, IR_FLAG_NOINLINE)
is_stmt_throw_block(stmt_flag::UInt32) = has_flag(stmt_flag, IR_FLAG_THROW_BLOCK)
function new_expr_effect_flags(𝕃ₒ::AbstractLattice, args::Vector{Any}, src::Union{IRCode,IncrementalCompact}, pattern_match=nothing)
Targ = args[1]
atyp = argextype(Targ, src)
# `Expr(:new)` of unknown type could raise arbitrary TypeError.
typ, isexact = instanceof_tfunc(atyp, true)
if !isexact
atyp = unwrap_unionall(widenconst(atyp))
if isType(atyp) && isTypeDataType(atyp.parameters[1])
typ = atyp.parameters[1]
else
return (false, false, false)
end
isabstracttype(typ) && return (false, false, false)
else
isconcretedispatch(typ) || return (false, false, false)
end
typ = typ::DataType
fcount = datatype_fieldcount(typ)
fcount === nothing && return (false, false, false)
fcount >= length(args) - 1 || return (false, false, false)
for fidx in 1:(length(args) - 1)
farg = args[fidx + 1]
eT = argextype(farg, src)
fT = fieldtype(typ, fidx)
if !isexact && has_free_typevars(fT)
if pattern_match !== nothing && pattern_match(src, typ, fidx, Targ, farg)
continue
end
return (false, false, false)
end
⊑(𝕃ₒ, eT, fT) || return (false, false, false)
end
return (false, true, true)
end
"""
stmt_effect_flags(stmt, rt, src::Union{IRCode,IncrementalCompact}) ->
(consistent::Bool, removable::Bool, nothrow::Bool)
Returns a tuple of `(:consistent, :removable, :nothrow)` flags for a given statement.
"""
function stmt_effect_flags(𝕃ₒ::AbstractLattice, @nospecialize(stmt), @nospecialize(rt), src::Union{IRCode,IncrementalCompact})
# TODO: We're duplicating analysis from inference here.
isa(stmt, PiNode) && return (true, true, true)
isa(stmt, PhiNode) && return (true, true, true)
isa(stmt, ReturnNode) && return (true, false, true)
isa(stmt, EnterNode) && return (true, false, true)
isa(stmt, GotoNode) && return (true, false, true)
isa(stmt, GotoIfNot) && return (true, false, ⊑(𝕃ₒ, argextype(stmt.cond, src), Bool))
if isa(stmt, GlobalRef)
nothrow = isdefined(stmt.mod, stmt.name)
consistent = nothrow && isconst(stmt.mod, stmt.name)
return (consistent, nothrow, nothrow)
elseif isa(stmt, Expr)
(; head, args) = stmt
if head === :static_parameter
# if we aren't certain enough about the type, it might be an UndefVarError at runtime
sptypes = isa(src, IRCode) ? src.sptypes : src.ir.sptypes
nothrow = !sptypes[args[1]::Int].undef
return (true, nothrow, nothrow)
end
if head === :call
f = argextype(args[1], src)
f = singleton_type(f)
f === nothing && return (false, false, false)
if f === UnionAll
# TODO: This is a weird special case - should be determined in inference
argtypes = Any[argextype(args[arg], src) for arg in 2:length(args)]
nothrow = _builtin_nothrow(𝕃ₒ, f, argtypes, rt)
return (true, nothrow, nothrow)
end
if f === Intrinsics.cglobal || f === Intrinsics.llvmcall
# TODO: these are not yet linearized
return (false, false, false)
end
isa(f, Builtin) || return (false, false, false)
# Needs to be handled in inlining to look at the callee effects
f === Core._apply_iterate && return (false, false, false)
argtypes = Any[argextype(args[arg], src) for arg in 2:length(args)]
effects = builtin_effects(𝕃ₒ, f, argtypes, rt)
consistent = is_consistent(effects)
effect_free = is_effect_free(effects)
nothrow = is_nothrow(effects)
removable = effect_free & nothrow
return (consistent, removable, nothrow)
elseif head === :new
return new_expr_effect_flags(𝕃ₒ, args, src)
elseif head === :foreigncall
effects = foreigncall_effects(stmt) do @nospecialize x
argextype(x, src)
end
consistent = is_consistent(effects)
effect_free = is_effect_free(effects)
nothrow = is_nothrow(effects)
removable = effect_free & nothrow
return (consistent, removable, nothrow)
elseif head === :new_opaque_closure
length(args) < 4 && return (false, false, false)
typ = argextype(args[1], src)
typ, isexact = instanceof_tfunc(typ, true)
isexact || return (false, false, false)
⊑(𝕃ₒ, typ, Tuple) || return (false, false, false)
rt_lb = argextype(args[2], src)
rt_ub = argextype(args[3], src)
source = argextype(args[4], src)
if !(⊑(𝕃ₒ, rt_lb, Type) && ⊑(𝕃ₒ, rt_ub, Type) && ⊑(𝕃ₒ, source, Method))
return (false, false, false)
end
return (false, true, true)
elseif head === :inbounds
return (true, true, true)
elseif head === :boundscheck || head === :isdefined || head === :the_exception || head === :copyast
return (false, true, true)
else
# e.g. :loopinfo
return (false, false, false)
end
end
isa(stmt, SlotNumber) && error("unexpected IR elements")
return (true, true, true)
end
function recompute_effects_flags(𝕃ₒ::AbstractLattice, @nospecialize(stmt), @nospecialize(rt),
src::Union{IRCode,IncrementalCompact})
flag = IR_FLAG_NULL
(consistent, removable, nothrow) = stmt_effect_flags(𝕃ₒ, stmt, rt, src)
if consistent
flag |= IR_FLAG_CONSISTENT
end
if removable
flag |= IR_FLAGS_REMOVABLE
elseif nothrow
flag |= IR_FLAG_NOTHROW
end
if !(isexpr(stmt, :call) || isexpr(stmt, :invoke))
# There is a bit of a subtle point here, which is that some non-call
# statements (e.g. PiNode) can be UB:, however, we consider it
# illegal to introduce such statements that actually cause UB (for any
# input). Ideally that'd be handled at insertion time (TODO), but for
# the time being just do that here.
flag |= IR_FLAG_NOUB
end
return flag
end
"""
argextype(x, src::Union{IRCode,IncrementalCompact}) -> t
argextype(x, src::CodeInfo, sptypes::Vector{VarState}) -> t
Return the type of value `x` in the context of inferred source `src`.
Note that `t` might be an extended lattice element.
Use `widenconst(t)` to get the native Julia type of `x`.
"""
argextype(@nospecialize(x), ir::IRCode, sptypes::Vector{VarState} = ir.sptypes) =
argextype(x, ir, sptypes, ir.argtypes)
function argextype(@nospecialize(x), compact::IncrementalCompact, sptypes::Vector{VarState} = compact.ir.sptypes)
isa(x, AnySSAValue) && return types(compact)[x]
return argextype(x, compact, sptypes, compact.ir.argtypes)
end
argextype(@nospecialize(x), src::CodeInfo, sptypes::Vector{VarState}) = argextype(x, src, sptypes, src.slottypes::Vector{Any})
function argextype(
@nospecialize(x), src::Union{IRCode,IncrementalCompact,CodeInfo},
sptypes::Vector{VarState}, slottypes::Vector{Any})
if isa(x, Expr)
if x.head === :static_parameter
return sptypes[x.args[1]::Int].typ
elseif x.head === :boundscheck
return Bool
elseif x.head === :copyast
return argextype(x.args[1], src, sptypes, slottypes)
end
Core.println("argextype called on Expr with head ", x.head,
" which is not valid for IR in argument-position.")
@assert false
elseif isa(x, SlotNumber)
return slottypes[x.id]
elseif isa(x, SSAValue)
return abstract_eval_ssavalue(x, src)
elseif isa(x, Argument)
return slottypes[x.n]
elseif isa(x, QuoteNode)
return Const(x.value)
elseif isa(x, GlobalRef)
return abstract_eval_globalref_type(x)
elseif isa(x, PhiNode) || isa(x, PhiCNode) || isa(x, UpsilonNode)
return Any
elseif isa(x, PiNode)
return x.typ
else
return Const(x)
end
end
abstract_eval_ssavalue(s::SSAValue, src::CodeInfo) = abstract_eval_ssavalue(s, src.ssavaluetypes::Vector{Any})
abstract_eval_ssavalue(s::SSAValue, src::Union{IRCode,IncrementalCompact}) = types(src)[s]
"""
finish(interp::AbstractInterpreter, opt::OptimizationState,
ir::IRCode, caller::InferenceResult)
Post-process information derived by Julia-level optimizations for later use.
In particular, this function determines the inlineability of the optimized code.
"""
function finish(interp::AbstractInterpreter, opt::OptimizationState,
ir::IRCode, caller::InferenceResult)
(; src, linfo) = opt
(; def, specTypes) = linfo
force_noinline = is_declared_noinline(src)
# compute inlining and other related optimizations
result = caller.result
@assert !(result isa LimitedAccuracy)
result = widenslotwrapper(result)
opt.ir = ir
# determine and cache inlineability
if !force_noinline
sig = unwrap_unionall(specTypes)
if !(isa(sig, DataType) && sig.name === Tuple.name)
force_noinline = true
end
if !is_declared_inline(src) && result === Bottom
force_noinline = true
end
end
if force_noinline
set_inlineable!(src, false)
elseif isa(def, Method)
if is_declared_inline(src) && isdispatchtuple(specTypes)
# obey @inline declaration if a dispatch barrier would not help
set_inlineable!(src, true)
else
# compute the cost (size) of inlining this code
params = OptimizationParams(interp)
cost_threshold = default = params.inline_cost_threshold
if ⊑(optimizer_lattice(interp), result, Tuple) && !isconcretetype(widenconst(result))
cost_threshold += params.inline_tupleret_bonus
end
# if the method is declared as `@inline`, increase the cost threshold 20x
if is_declared_inline(src)
cost_threshold += 19*default
end
# a few functions get special treatment
if def.module === _topmod(def.module)
name = def.name
if name === :iterate || name === :unsafe_convert || name === :cconvert
cost_threshold += 4*default
end
end
src.inlining_cost = inline_cost(ir, params, cost_threshold)
end
end
return nothing
end
function visit_bb_phis!(callback, ir::IRCode, bb::Int)
stmts = ir.cfg.blocks[bb].stmts
for idx in stmts
stmt = ir[SSAValue(idx)][:stmt]
if !isa(stmt, PhiNode)
if !is_valid_phiblock_stmt(stmt)
return
end
else
callback(idx)
end
end
end
function any_stmt_may_throw(ir::IRCode, bb::Int)
for idx in ir.cfg.blocks[bb].stmts
if !has_flag(ir[SSAValue(idx)], IR_FLAG_NOTHROW)
return true
end
end
return false
end
function conditional_successors_may_throw(lazypostdomtree::LazyPostDomtree, ir::IRCode, bb::Int)
visited = BitSet((bb,))
worklist = Int[bb]
while !isempty(worklist)
thisbb = pop!(worklist)
for succ in ir.cfg.blocks[thisbb].succs
succ in visited && continue
push!(visited, succ)
postdominates(get!(lazypostdomtree), succ, thisbb) && continue
any_stmt_may_throw(ir, succ) && return true
push!(worklist, succ)
end
end
return false
end
struct AugmentedDomtree
cfg::CFG
domtree::DomTree
end
mutable struct LazyAugmentedDomtree
const ir::IRCode
agdomtree::AugmentedDomtree
LazyAugmentedDomtree(ir::IRCode) = new(ir)
end
function get!(lazyagdomtree::LazyAugmentedDomtree)
isdefined(lazyagdomtree, :agdomtree) && return lazyagdomtree.agdomtree
ir = lazyagdomtree.ir
cfg = copy(ir.cfg)
# Add a virtual basic block to represent the exit
push!(cfg.blocks, BasicBlock(StmtRange(0:-1)))
for bb = 1:(length(cfg.blocks)-1)
terminator = ir[SSAValue(last(cfg.blocks[bb].stmts))][:stmt]
if isa(terminator, ReturnNode) && isdefined(terminator, :val)
cfg_insert_edge!(cfg, bb, length(cfg.blocks))
end
end
domtree = construct_domtree(cfg.blocks)
return lazyagdomtree.agdomtree = AugmentedDomtree(cfg, domtree)
end
mutable struct PostOptAnalysisState
const result::InferenceResult
const ir::IRCode
const inconsistent::BitSetBoundedMinPrioritySet
const tpdum::TwoPhaseDefUseMap
const lazypostdomtree::LazyPostDomtree
const lazyagdomtree::LazyAugmentedDomtree
const ea_analysis_pending::Vector{Int}
all_retpaths_consistent::Bool
all_effect_free::Bool
effect_free_if_argmem_only::Union{Nothing,Bool}
all_nothrow::Bool
all_noub::Bool
any_conditional_ub::Bool
function PostOptAnalysisState(result::InferenceResult, ir::IRCode)
inconsistent = BitSetBoundedMinPrioritySet(length(ir.stmts))
tpdum = TwoPhaseDefUseMap(length(ir.stmts))
lazypostdomtree = LazyPostDomtree(ir)
lazyagdomtree = LazyAugmentedDomtree(ir)
return new(result, ir, inconsistent, tpdum, lazypostdomtree, lazyagdomtree, Int[],
true, true, nothing, true, true, false)
end
end
give_up_refinements!(sv::PostOptAnalysisState) =
sv.all_retpaths_consistent = sv.all_effect_free = sv.effect_free_if_argmem_only =
sv.all_nothrow = sv.all_noub = false
function any_refinable(sv::PostOptAnalysisState)
effects = sv.result.ipo_effects
return ((!is_consistent(effects) & sv.all_retpaths_consistent) |
(!is_effect_free(effects) & sv.all_effect_free) |
(!is_nothrow(effects) & sv.all_nothrow) |
(!is_noub(effects) & sv.all_noub))
end
struct GetNativeEscapeCache{CodeCache}
code_cache::CodeCache
GetNativeEscapeCache(code_cache::CodeCache) where CodeCache = new{CodeCache}(code_cache)
end
GetNativeEscapeCache(interp::AbstractInterpreter) = GetNativeEscapeCache(code_cache(interp))
function ((; code_cache)::GetNativeEscapeCache)(mi::MethodInstance)
codeinst = get(code_cache, mi, nothing)
codeinst isa CodeInstance || return false
argescapes = traverse_analysis_results(codeinst) do @nospecialize result
return result isa EscapeAnalysis.ArgEscapeCache ? result : nothing
end
if argescapes !== nothing
return argescapes
end
effects = decode_effects(codeinst.ipo_purity_bits)
if is_effect_free(effects) && is_inaccessiblememonly(effects)
# We might not have run EA on simple frames without any escapes (e.g. when optimization
# is skipped when result is constant-folded by abstract interpretation). If those
# frames aren't inlined, the accuracy of EA for caller context takes a big hit.
# This is a HACK to avoid that, but obviously, a more comprehensive fix would be ideal.
return true
end
return false
end
function refine_effects!(interp::AbstractInterpreter, sv::PostOptAnalysisState)
if !is_effect_free(sv.result.ipo_effects) && sv.all_effect_free && !isempty(sv.ea_analysis_pending)
ir = sv.ir
nargs = length(ir.argtypes)
estate = EscapeAnalysis.analyze_escapes(ir, nargs, optimizer_lattice(interp), GetNativeEscapeCache(interp))
argescapes = EscapeAnalysis.ArgEscapeCache(estate)
stack_analysis_result!(sv.result, argescapes)
validate_mutable_arg_escapes!(estate, sv)
end
any_refinable(sv) || return false
effects = sv.result.ipo_effects
sv.result.ipo_effects = Effects(effects;
consistent = sv.all_retpaths_consistent ? ALWAYS_TRUE : effects.consistent,
effect_free = sv.all_effect_free ? ALWAYS_TRUE :
sv.effect_free_if_argmem_only === true ? EFFECT_FREE_IF_INACCESSIBLEMEMONLY : effects.effect_free,
nothrow = sv.all_nothrow ? true : effects.nothrow,
noub = sv.all_noub ? (sv.any_conditional_ub ? NOUB_IF_NOINBOUNDS : ALWAYS_TRUE) : effects.noub)
return true
end
function is_ipo_dataflow_analysis_profitable(effects::Effects)
return !(is_consistent(effects) && is_effect_free(effects) &&
is_nothrow(effects) && is_noub(effects))
end
function iscall_with_boundscheck(@nospecialize(stmt), sv::PostOptAnalysisState)
isexpr(stmt, :call) || return false
ft = argextype(stmt.args[1], sv.ir)
f = singleton_type(ft)
f === nothing && return false
if f === getfield
nargs = 4
elseif f === memoryref || f === memoryrefget || f === memoryref_isassigned
nargs = 4
elseif f === memoryrefset!
nargs = 5
else
return false
end
length(stmt.args) < nargs && return false
boundscheck = stmt.args[end]
argextype(boundscheck, sv.ir) === Bool || return false
isa(boundscheck, SSAValue) || return false
return true
end
function check_all_args_noescape!(sv::PostOptAnalysisState, ir::IRCode, @nospecialize(stmt),
estate::EscapeAnalysis.EscapeState)
stmt isa Expr || return false
if isexpr(stmt, :invoke)
startidx = 2
elseif isexpr(stmt, :new)
startidx = 1
else
return false
end
for i = startidx:length(stmt.args)
arg = stmt.args[i]
argt = argextype(arg, ir)
if is_mutation_free_argtype(argt)
continue
end
# See if we can find the allocation
if isa(arg, Argument)
if EscapeAnalysis.has_no_escape(EscapeAnalysis.ignore_argescape(estate[arg]))
# Even if we prove everything else effect_free, the best we can
# say is :effect_free_if_argmem_only
if sv.effect_free_if_argmem_only === nothing
sv.effect_free_if_argmem_only = true
end
else
sv.effect_free_if_argmem_only = false
end
return false
elseif isa(arg, SSAValue)
EscapeAnalysis.has_no_escape(estate[arg]) || return false
check_all_args_noescape!(sv, ir, ir[arg][:stmt], estate) || return false
else
return false
end
end
return true
end
function validate_mutable_arg_escapes!(estate::EscapeAnalysis.EscapeState, sv::PostOptAnalysisState)
ir = sv.ir
for idx in sv.ea_analysis_pending
# See if any mutable memory was allocated in this function and determined
# not to escape.
inst = ir[SSAValue(idx)]
stmt = inst[:stmt]
if !check_all_args_noescape!(sv, ir, stmt, estate)
return sv.all_effect_free = false
end
end
return true
end
function is_conditional_noub(inst::Instruction, sv::PostOptAnalysisState)
stmt = inst[:stmt]
iscall_with_boundscheck(stmt, sv) || return false
barg = stmt.args[end]::SSAValue
bstmt = sv.ir[barg][:stmt]
isexpr(bstmt, :boundscheck) || return false
# If IR_FLAG_INBOUNDS is already set, no more conditional ub
(!isempty(bstmt.args) && bstmt.args[1] === false) && return false
return true
end
function scan_non_dataflow_flags!(inst::Instruction, sv::PostOptAnalysisState)
flag = inst[:flag]
# If we can prove that the argmem does not escape the current function, we can
# refine this to :effect_free.
needs_ea_validation = has_flag(flag, IR_FLAGS_NEEDS_EA)
stmt = inst[:stmt]
if !needs_ea_validation
if !isterminator(stmt) && stmt !== nothing
# ignore control flow node – they are not removable on their own and thus not
# have `IR_FLAG_EFFECT_FREE` but still do not taint `:effect_free`-ness of
# the whole method invocation
sv.all_effect_free &= has_flag(flag, IR_FLAG_EFFECT_FREE)
end
elseif sv.all_effect_free
if (isexpr(stmt, :invoke) || isexpr(stmt, :new) ||
# HACK for performance: limit the scope of EA to code with object field access only,
# since its abilities to reason about e.g. arrays are currently very limited anyways.
is_known_call(stmt, setfield!, sv.ir))
push!(sv.ea_analysis_pending, inst.idx)
else
sv.all_effect_free = false
end
end
sv.all_nothrow &= has_flag(flag, IR_FLAG_NOTHROW)
if !has_flag(flag, IR_FLAG_NOUB)
# Special case: `:boundscheck` into `getfield` or memory operations is `:noub_if_noinbounds`
if is_conditional_noub(inst, sv)
sv.any_conditional_ub = true
else
sv.all_noub = false
end
end
end
function scan_inconsistency!(inst::Instruction, sv::PostOptAnalysisState)
flag = inst[:flag]
stmt_inconsistent = !has_flag(flag, IR_FLAG_CONSISTENT)
stmt = inst[:stmt]
# Special case: For `getfield` and memory operations, we allow inconsistency of the :boundscheck argument
(; inconsistent, tpdum) = sv
if iscall_with_boundscheck(stmt, sv)
for i = 1:(length(stmt.args)-1)
val = stmt.args[i]
if isa(val, SSAValue)
stmt_inconsistent |= val.id in inconsistent
count!(tpdum, val)
end
end
else
for ur in userefs(stmt)
val = ur[]
if isa(val, SSAValue)
stmt_inconsistent |= val.id in inconsistent
count!(tpdum, val)
end
end
end
stmt_inconsistent && push!(inconsistent, inst.idx)
return stmt_inconsistent
end
struct ScanStmt
sv::PostOptAnalysisState
end
function ((; sv)::ScanStmt)(inst::Instruction, lstmt::Int, bb::Int)
stmt = inst[:stmt]
if isa(stmt, EnterNode)
# try/catch not yet modeled
give_up_refinements!(sv)
return nothing
end
scan_non_dataflow_flags!(inst, sv)
stmt_inconsistent = scan_inconsistency!(inst, sv)
if stmt_inconsistent && inst.idx == lstmt
if isa(stmt, ReturnNode) && isdefined(stmt, :val)
sv.all_retpaths_consistent = false
elseif isa(stmt, GotoIfNot)
# Conditional Branch with inconsistent condition.
# If we do not know this function terminates, taint consistency, now,
# :consistent requires consistent termination. TODO: Just look at the
# inconsistent region.
if !sv.result.ipo_effects.terminates
sv.all_retpaths_consistent = false
elseif conditional_successors_may_throw(sv.lazypostdomtree, sv.ir, bb)
# Check if there are potential throws that require
sv.all_retpaths_consistent = false
else
(; cfg, domtree) = get!(sv.lazyagdomtree)
for succ in iterated_dominance_frontier(cfg, BlockLiveness(sv.ir.cfg.blocks[bb].succs, nothing), domtree)
if succ == length(cfg.blocks)
# Phi node in the virtual exit -> We have a conditional
# return. TODO: Check if all the retvals are egal.
sv.all_retpaths_consistent = false
else
visit_bb_phis!(sv.ir, succ) do phiidx::Int
push!(sv.inconsistent, phiidx)
end
end
end
end
end
end
# bail out early if there are no possibilities to refine the effects
if !any_refinable(sv)
return nothing
end
return true
end
function check_inconsistentcy!(sv::PostOptAnalysisState, scanner::BBScanner)
(; ir, inconsistent, tpdum) = sv
scan!(ScanStmt(sv), scanner, false)
complete!(tpdum); push!(scanner.bb_ip, 1)
populate_def_use_map!(tpdum, scanner)
stmt_ip = BitSetBoundedMinPrioritySet(length(ir.stmts))
for def in inconsistent
for use in tpdum[def]
if !(use in inconsistent)
push!(inconsistent, use)
append!(stmt_ip, tpdum[use])
end
end
end
lazydomtree = LazyDomtree(ir)
while !isempty(stmt_ip)
idx = popfirst!(stmt_ip)
inst = ir[SSAValue(idx)]
stmt = inst[:stmt]
if iscall_with_boundscheck(stmt, sv)
any_non_boundscheck_inconsistent = false
for i = 1:(length(stmt.args)-1)
val = stmt.args[i]
if isa(val, SSAValue)
any_non_boundscheck_inconsistent |= val.id in inconsistent
any_non_boundscheck_inconsistent && break
end
end
any_non_boundscheck_inconsistent || continue
elseif isa(stmt, ReturnNode)
sv.all_retpaths_consistent = false
elseif isa(stmt, GotoIfNot)
bb = block_for_inst(ir, idx)
cfg = ir.cfg
blockliveness = BlockLiveness(cfg.blocks[bb].succs, nothing)
for succ in iterated_dominance_frontier(cfg, blockliveness, get!(lazydomtree))
visit_bb_phis!(ir, succ) do phiidx::Int
push!(inconsistent, phiidx)
push!(stmt_ip, phiidx)
end
end
end
sv.all_retpaths_consistent || break
append!(inconsistent, tpdum[idx])
append!(stmt_ip, tpdum[idx])
end
end
function ipo_dataflow_analysis!(interp::AbstractInterpreter, ir::IRCode, result::InferenceResult)
if !is_ipo_dataflow_analysis_profitable(result.ipo_effects)
return false
end
@assert isempty(ir.new_nodes) "IRCode should be compacted before post-opt analysis"
sv = PostOptAnalysisState(result, ir)
scanner = BBScanner(ir)
completed_scan = scan!(ScanStmt(sv), scanner, true)
if !completed_scan
if sv.all_retpaths_consistent
check_inconsistentcy!(sv, scanner)
else
# No longer any dataflow concerns, just scan the flags
scan!(scanner, false) do inst::Instruction, lstmt::Int, bb::Int
scan_non_dataflow_flags!(inst, sv)
# bail out early if there are no possibilities to refine the effects
if !any_refinable(sv)
return nothing
end
return true
end
end
end
return refine_effects!(interp, sv)
end
# run the optimization work
function optimize(interp::AbstractInterpreter, opt::OptimizationState, caller::InferenceResult)
@timeit "optimizer" ir = run_passes_ipo_safe(opt.src, opt, caller)
ipo_dataflow_analysis!(interp, ir, caller)
return finish(interp, opt, ir, caller)
end
macro pass(name, expr)
optimize_until = esc(:optimize_until)
stage = esc(:__stage__)
macrocall = :(@timeit $(esc(name)) $(esc(expr)))
macrocall.args[2] = __source__ # `@timeit` may want to use it
quote
$macrocall
matchpass($optimize_until, ($stage += 1), $(esc(name))) && $(esc(:(@goto __done__)))
end
end
matchpass(optimize_until::Int, stage, _) = optimize_until == stage
matchpass(optimize_until::String, _, name) = optimize_until == name
matchpass(::Nothing, _, _) = false
function run_passes_ipo_safe(
ci::CodeInfo,
sv::OptimizationState,
caller::InferenceResult,
optimize_until = nothing, # run all passes by default
)
__stage__ = 0 # used by @pass
# NOTE: The pass name MUST be unique for `optimize_until::AbstractString` to work
@pass "convert" ir = convert_to_ircode(ci, sv)
@pass "slot2reg" ir = slot2reg(ir, ci, sv)
# TODO: Domsorting can produce an updated domtree - no need to recompute here
@pass "compact 1" ir = compact!(ir)
@pass "Inlining" ir = ssa_inlining_pass!(ir, sv.inlining, ci.propagate_inbounds)
# @timeit "verify 2" verify_ir(ir)
@pass "compact 2" ir = compact!(ir)
@pass "SROA" ir = sroa_pass!(ir, sv.inlining)
@pass "ADCE" (ir, made_changes) = adce_pass!(ir, sv.inlining)
if made_changes
@pass "compact 3" ir = compact!(ir, true)
end
if is_asserts()
@timeit "verify 3" begin
verify_ir(ir, true, false, optimizer_lattice(sv.inlining.interp))
verify_linetable(ir.linetable)
end
end
@label __done__ # used by @pass
return ir
end
function convert_to_ircode(ci::CodeInfo, sv::OptimizationState)
linetable = ci.linetable
if !isa(linetable, Vector{LineInfoNode})
linetable = collect(LineInfoNode, linetable::Vector{Any})::Vector{LineInfoNode}