-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathir.jl
1705 lines (1587 loc) · 63.2 KB
/
ir.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
Core.PhiNode() = Core.PhiNode(Int32[], Any[])
isterminator(@nospecialize(stmt)) = isa(stmt, GotoNode) || isa(stmt, GotoIfNot) || isa(stmt, ReturnNode)
struct CFG
blocks::Vector{BasicBlock}
index::Vector{Int} # map from instruction => basic-block number
# TODO: make this O(1) instead of O(log(n_blocks))?
end
copy(c::CFG) = CFG(BasicBlock[copy(b) for b in c.blocks], copy(c.index))
function cfg_insert_edge!(cfg::CFG, from::Int, to::Int)
# Assumes that this edge does not already exist
push!(cfg.blocks[to].preds, from)
push!(cfg.blocks[from].succs, to)
nothing
end
function cfg_delete_edge!(cfg::CFG, from::Int, to::Int)
preds = cfg.blocks[to].preds
succs = cfg.blocks[from].succs
# Assumes that blocks appear at most once in preds and succs
deleteat!(preds, findfirst(x->x === from, preds)::Int)
deleteat!(succs, findfirst(x->x === to, succs)::Int)
nothing
end
function bb_ordering()
lt=(<=)
by=x->first(x.stmts)
ord(lt, by, nothing, Forward)
end
function block_for_inst(index::Vector{Int}, inst::Int)
return searchsortedfirst(index, inst, lt=(<=))
end
function block_for_inst(index::Vector{BasicBlock}, inst::Int)
return searchsortedfirst(index, BasicBlock(StmtRange(inst, inst)), bb_ordering())-1
end
block_for_inst(cfg::CFG, inst::Int) = block_for_inst(cfg.index, inst)
@inline function basic_blocks_starts(stmts::Vector{Any})
jump_dests = BitSet()
push!(jump_dests, 1) # function entry point
# First go through and compute jump destinations
for idx in 1:length(stmts)
stmt = stmts[idx]
# Terminators
if isa(stmt, GotoIfNot)
push!(jump_dests, idx+1)
push!(jump_dests, stmt.dest)
elseif isa(stmt, ReturnNode)
idx < length(stmts) && push!(jump_dests, idx+1)
elseif isa(stmt, GotoNode)
# This is a fake dest to force the next stmt to start a bb
idx < length(stmts) && push!(jump_dests, idx+1)
push!(jump_dests, stmt.label)
elseif isa(stmt, Expr)
if stmt.head === :leave
# :leave terminates a BB
push!(jump_dests, idx+1)
elseif stmt.head === :enter
# :enter starts/ends a BB
push!(jump_dests, idx)
push!(jump_dests, idx+1)
# The catch block is a jump dest
push!(jump_dests, stmt.args[1]::Int)
end
end
if isa(stmt, PhiNode)
for edge in stmt.edges
if edge == idx - 1
push!(jump_dests, idx)
end
end
end
end
# and add add one more basic block start after the last statement
for i = length(stmts):-1:1
if stmts[i] !== nothing
push!(jump_dests, i+1)
break
end
end
return jump_dests
end
function compute_basic_blocks(stmts::Vector{Any})
# Compute ranges
bb_starts = basic_blocks_starts(stmts) # ::BitSet and already sorted
pop!(bb_starts, 1)
basic_block_index = Int[bb for bb in bb_starts]
blocks = Vector{BasicBlock}(undef, length(basic_block_index))
let first = 1
for (i, last) in enumerate(basic_block_index)
blocks[i] = BasicBlock(StmtRange(first, last - 1))
first = last
end
end
# Compute successors/predecessors
for (num, b) in enumerate(blocks)
terminator = stmts[last(b.stmts)]
if isa(terminator, ReturnNode)
# return never has any successors
continue
end
if isa(terminator, GotoNode)
block′ = block_for_inst(basic_block_index, terminator.label)
push!(blocks[block′].preds, num)
push!(b.succs, block′)
continue
end
# Conditional Branch
if isa(terminator, GotoIfNot)
block′ = block_for_inst(basic_block_index, terminator.dest)
if block′ == num + 1
# This GotoIfNot acts like a noop - treat it as such.
# We will drop it during SSA renaming
else
push!(blocks[block′].preds, num)
push!(b.succs, block′)
end
elseif isexpr(terminator, :enter)
# :enter gets a virtual edge to the exception handler and
# the exception handler gets a virtual edge from outside
# the function.
block′ = block_for_inst(basic_block_index, terminator.args[1]::Int)
push!(blocks[block′].preds, num)
push!(blocks[block′].preds, 0)
push!(b.succs, block′)
end
# statement fall-through
if num + 1 <= length(blocks)
push!(blocks[num + 1].preds, num)
push!(b.succs, num + 1)
end
end
return CFG(blocks, basic_block_index)
end
# this function assumes insert position exists
function first_insert_for_bb(code, cfg::CFG, block::Int)
for idx in cfg.blocks[block].stmts
stmt = code[idx]
if !isa(stmt, PhiNode)
return idx
end
end
error("any insert position isn't found")
end
# SSA values that need renaming
struct OldSSAValue
id::Int
end
## TODO: This description currently omits the use of NewSSAValue during slot2ssa,
## which doesn't use IncrementalCompact, but does something similar and also uses
## NewSSAValue to refer to new_nodes. Ideally that use of NewSSAValue would go away
## during a refactor.
"""
struct NewSSAValue
`NewSSAValue`s occur in the context of IncrementalCompact. Their meaning depends
on where they appear:
1. In already-compacted nodes,
i. a `NewSSAValue` with positive `id` has the same meaning as a regular SSAValue.
ii. a `NewSSAValue` with negative `id` refers to post-compaction `new_node` node.
2. In non-compacted nodes,
i. a `NewSSAValue` with positive `id` refers to the index of an already-compacted instructions.
ii. a `NewSSAValue` with negative `id` has the same meaning as in compacted nodes.
"""
struct NewSSAValue
id::Int
end
const AnySSAValue = Union{SSAValue, OldSSAValue, NewSSAValue}
# SSA-indexed nodes
struct InstructionStream
inst::Vector{Any}
type::Vector{Any}
info::Vector{Any}
line::Vector{Int32}
flag::Vector{UInt8}
end
function InstructionStream(len::Int)
insts = Array{Any}(undef, len)
types = Array{Any}(undef, len)
info = Array{Any}(undef, len)
fill!(info, nothing)
lines = fill(Int32(0), len)
flags = fill(IR_FLAG_NULL, len)
return InstructionStream(insts, types, info, lines, flags)
end
InstructionStream() = InstructionStream(0)
length(is::InstructionStream) = length(is.inst)
isempty(is::InstructionStream) = isempty(is.inst)
function add!(is::InstructionStream)
ninst = length(is) + 1
resize!(is, ninst)
return ninst
end
function copy(is::InstructionStream)
return InstructionStream(
copy_exprargs(is.inst),
copy(is.type),
copy(is.info),
copy(is.line),
copy(is.flag))
end
function resize!(stmts::InstructionStream, len)
old_length = length(stmts)
resize!(stmts.inst, len)
resize!(stmts.type, len)
resize!(stmts.info, len)
resize!(stmts.line, len)
resize!(stmts.flag, len)
for i in (old_length + 1):len
stmts.line[i] = 0
stmts.flag[i] = IR_FLAG_NULL
stmts.info[i] = nothing
end
return stmts
end
struct Instruction
data::InstructionStream
idx::Int
end
Instruction(is::InstructionStream) = Instruction(is, add!(is))
@inline function getindex(node::Instruction, fld::Symbol)
isdefined(node, fld) && return getfield(node, fld)
return getfield(getfield(node, :data), fld)[getfield(node, :idx)]
end
@inline function setindex!(node::Instruction, @nospecialize(val), fld::Symbol)
getfield(getfield(node, :data), fld)[getfield(node, :idx)] = val
return node
end
@inline getindex(is::InstructionStream, idx::Int) = Instruction(is, idx)
function setindex!(is::InstructionStream, newval::Instruction, idx::Int)
is.inst[idx] = newval[:inst]
is.type[idx] = newval[:type]
is.info[idx] = newval[:info]
is.line[idx] = newval[:line]
is.flag[idx] = newval[:flag]
return is
end
function setindex!(is::InstructionStream, newval::Union{AnySSAValue, Nothing}, idx::Int)
is.inst[idx] = newval
return is
end
function setindex!(node::Instruction, newval::Instruction)
node.data[node.idx] = newval
return node
end
struct NewNodeInfo
# Insertion position (interpretation depends on which array this is in)
pos::Int
# Place the new instruction after this instruction (but in the same BB if this is an implicit terminator)
attach_after::Bool
end
struct NewNodeStream
stmts::InstructionStream
info::Vector{NewNodeInfo}
end
NewNodeStream(len::Int=0) = NewNodeStream(InstructionStream(len), fill(NewNodeInfo(0, false), len))
length(new::NewNodeStream) = length(new.stmts)
isempty(new::NewNodeStream) = isempty(new.stmts)
function add!(new::NewNodeStream, pos::Int, attach_after::Bool)
push!(new.info, NewNodeInfo(pos, attach_after))
return Instruction(new.stmts)
end
copy(nns::NewNodeStream) = NewNodeStream(copy(nns.stmts), copy(nns.info))
struct NewInstruction
stmt::Any
type::Any
info::Any
# If nothing, copy the line from previous statement
# in the insertion location
line::Union{Int32, Nothing}
flag::UInt8
## Insertion options
# The IR_FLAG_EFFECT_FREE flag has already been computed (or forced).
# Don't bother redoing so on insertion.
effect_free_computed::Bool
NewInstruction(@nospecialize(stmt), @nospecialize(type), @nospecialize(info),
line::Union{Int32, Nothing}, flag::UInt8, effect_free_computed::Bool) =
new(stmt, type, info, line, flag, effect_free_computed)
end
NewInstruction(@nospecialize(stmt), @nospecialize(type)) =
NewInstruction(stmt, type, nothing)
NewInstruction(@nospecialize(stmt), @nospecialize(type), line::Union{Nothing, Int32}) =
NewInstruction(stmt, type, nothing, line, IR_FLAG_NULL, false)
NewInstruction(@nospecialize(stmt), meta::Instruction; line::Union{Int32, Nothing}=nothing) =
NewInstruction(stmt, meta[:type], meta[:info], line === nothing ? meta[:line] : line, meta[:flag], true)
effect_free(inst::NewInstruction) =
NewInstruction(inst.stmt, inst.type, inst.info, inst.line, inst.flag | IR_FLAG_EFFECT_FREE, true)
non_effect_free(inst::NewInstruction) =
NewInstruction(inst.stmt, inst.type, inst.info, inst.line, inst.flag & ~IR_FLAG_EFFECT_FREE, true)
with_flags(inst::NewInstruction, flags::UInt8) =
NewInstruction(inst.stmt, inst.type, inst.info, inst.line, inst.flag | flags, true)
struct IRCode
stmts::InstructionStream
argtypes::Vector{Any}
sptypes::Vector{Any}
linetable::Vector{LineInfoNode}
cfg::CFG
new_nodes::NewNodeStream
meta::Vector{Expr}
function IRCode(stmts::InstructionStream, cfg::CFG, linetable::Vector{LineInfoNode}, argtypes::Vector{Any}, meta::Vector{Expr}, sptypes::Vector{Any})
return new(stmts, argtypes, sptypes, linetable, cfg, NewNodeStream(), meta)
end
function IRCode(ir::IRCode, stmts::InstructionStream, cfg::CFG, new_nodes::NewNodeStream)
return new(stmts, ir.argtypes, ir.sptypes, ir.linetable, cfg, new_nodes, ir.meta)
end
global copy
copy(ir::IRCode) = new(copy(ir.stmts), copy(ir.argtypes), copy(ir.sptypes),
copy(ir.linetable), copy(ir.cfg), copy(ir.new_nodes), copy(ir.meta))
end
function block_for_inst(ir::IRCode, inst::Int)
if inst > length(ir.stmts)
inst = ir.new_nodes.info[inst - length(ir.stmts)].pos
end
block_for_inst(ir.cfg, inst)
end
function getindex(x::IRCode, s::SSAValue)
if s.id <= length(x.stmts)
return x.stmts[s.id]
else
return x.new_nodes.stmts[s.id - length(x.stmts)]
end
end
function setindex!(x::IRCode, repl::Union{Instruction, Nothing, AnySSAValue}, s::SSAValue)
if s.id <= length(x.stmts)
x.stmts[s.id] = repl
else
x.new_nodes.stmts[s.id - length(x.stmts)] = repl
end
return x
end
mutable struct UseRefIterator
stmt::Any
relevant::Bool
UseRefIterator(@nospecialize(a), relevant::Bool) = new(a, relevant)
end
getindex(it::UseRefIterator) = it.stmt
struct UseRef
urs::UseRefIterator
op::Int
UseRef(urs::UseRefIterator) = new(urs, 0)
UseRef(urs::UseRefIterator, op::Int) = new(urs, op)
end
struct OOBToken end; const OOB_TOKEN = OOBToken()
struct UndefToken end; const UNDEF_TOKEN = UndefToken()
@noinline function _useref_getindex(@nospecialize(stmt), op::Int)
if isa(stmt, Expr) && stmt.head === :(=)
rhs = stmt.args[2]
if isa(rhs, Expr)
if is_relevant_expr(rhs)
op > length(rhs.args) && return OOB_TOKEN
return rhs.args[op]
end
end
op == 1 || return OOB_TOKEN
return rhs
elseif isa(stmt, Expr) # @assert is_relevant_expr(stmt)
op > length(stmt.args) && return OOB_TOKEN
return stmt.args[op]
elseif isa(stmt, GotoIfNot)
op == 1 || return OOB_TOKEN
return stmt.cond
elseif isa(stmt, ReturnNode)
isdefined(stmt, :val) || return OOB_TOKEN
op == 1 || return OOB_TOKEN
return stmt.val
elseif isa(stmt, PiNode)
isdefined(stmt, :val) || return OOB_TOKEN
op == 1 || return OOB_TOKEN
return stmt.val
elseif isa(stmt, Union{SSAValue, NewSSAValue, GlobalRef})
op == 1 || return OOB_TOKEN
return stmt
elseif isa(stmt, UpsilonNode)
isdefined(stmt, :val) || return OOB_TOKEN
op == 1 || return OOB_TOKEN
return stmt.val
elseif isa(stmt, PhiNode)
op > length(stmt.values) && return OOB_TOKEN
isassigned(stmt.values, op) || return UNDEF_TOKEN
return stmt.values[op]
elseif isa(stmt, PhiCNode)
op > length(stmt.values) && return OOB_TOKEN
isassigned(stmt.values, op) || return UNDEF_TOKEN
return stmt.values[op]
else
return OOB_TOKEN
end
end
@inline getindex(x::UseRef) = _useref_getindex(x.urs.stmt, x.op)
function is_relevant_expr(e::Expr)
return e.head in (:call, :invoke, :invoke_modify,
:new, :splatnew, :(=), :(&),
:gc_preserve_begin, :gc_preserve_end,
:foreigncall, :isdefined, :copyast,
:undefcheck, :throw_undef_if_not,
:cfunction, :method, :pop_exception,
:new_opaque_closure)
end
@noinline function _useref_setindex!(@nospecialize(stmt), op::Int, @nospecialize(v))
if isa(stmt, Expr) && stmt.head === :(=)
rhs = stmt.args[2]
if isa(rhs, Expr)
if is_relevant_expr(rhs)
op > length(rhs.args) && throw(BoundsError())
rhs.args[op] = v
return stmt
end
end
op == 1 || throw(BoundsError())
stmt.args[2] = v
elseif isa(stmt, Expr) # @assert is_relevant_expr(stmt)
op > length(stmt.args) && throw(BoundsError())
stmt.args[op] = v
elseif isa(stmt, GotoIfNot)
op == 1 || throw(BoundsError())
stmt = GotoIfNot(v, stmt.dest)
elseif isa(stmt, ReturnNode)
op == 1 || throw(BoundsError())
stmt = typeof(stmt)(v)
elseif isa(stmt, Union{SSAValue, NewSSAValue, GlobalRef})
op == 1 || throw(BoundsError())
stmt = v
elseif isa(stmt, UpsilonNode)
op == 1 || throw(BoundsError())
stmt = typeof(stmt)(v)
elseif isa(stmt, PiNode)
op == 1 || throw(BoundsError())
stmt = typeof(stmt)(v, stmt.typ)
elseif isa(stmt, PhiNode)
op > length(stmt.values) && throw(BoundsError())
isassigned(stmt.values, op) || throw(BoundsError())
stmt.values[op] = v
elseif isa(stmt, PhiCNode)
op > length(stmt.values) && throw(BoundsError())
isassigned(stmt.values, op) || throw(BoundsError())
stmt.values[op] = v
else
throw(BoundsError())
end
return stmt
end
@inline function setindex!(x::UseRef, @nospecialize(v))
x.urs.stmt = _useref_setindex!(x.urs.stmt, x.op, v)
return x
end
function userefs(@nospecialize(x))
relevant = (isa(x, Expr) && is_relevant_expr(x)) ||
isa(x, GotoIfNot) || isa(x, ReturnNode) || isa(x, SSAValue) || isa(x, NewSSAValue) ||
isa(x, PiNode) || isa(x, PhiNode) || isa(x, PhiCNode) || isa(x, UpsilonNode)
return UseRefIterator(x, relevant)
end
@noinline function _advance(@nospecialize(stmt), op)
while true
op += 1
y = _useref_getindex(stmt, op)
y === OOB_TOKEN && return nothing
y === UNDEF_TOKEN || return op
end
end
@inline function iterate(it::UseRefIterator, op::Int=0)
it.relevant || return nothing
op = _advance(it.stmt, op)
op === nothing && return nothing
return (UseRef(it, op), op)
end
# This function is used from the show code, which may have a different
# `push!`/`used` type since it's in Base.
scan_ssa_use!(@specialize(push!), used, @nospecialize(stmt)) = foreachssa(ssa::SSAValue -> push!(used, ssa.id), stmt)
# Manually specialized copy of the above with push! === Compiler.push!
scan_ssa_use!(used::IdSet, @nospecialize(stmt)) = foreachssa(ssa::SSAValue -> push!(used, ssa.id), stmt)
function insert_node!(ir::IRCode, pos::SSAValue, inst::NewInstruction, attach_after::Bool=false)
node = add!(ir.new_nodes, pos.id, attach_after)
node[:line] = something(inst.line, ir[pos][:line])
flag = inst.flag
if !inst.effect_free_computed
(consistent, effect_free_and_nothrow, nothrow) = stmt_effect_flags(fallback_lattice, inst.stmt, inst.type, ir)
if consistent
flag |= IR_FLAG_CONSISTENT
end
if effect_free_and_nothrow
flag |= IR_FLAG_EFFECT_FREE | IR_FLAG_NOTHROW
elseif nothrow
flag |= IR_FLAG_NOTHROW
end
end
node[:inst], node[:type], node[:flag] = inst.stmt, inst.type, flag
return SSAValue(length(ir.stmts) + node.idx)
end
insert_node!(ir::IRCode, pos::Int, inst::NewInstruction, attach_after::Bool=false) =
insert_node!(ir, SSAValue(pos), inst, attach_after)
# For bootstrapping
function my_sortperm(v)
p = Vector{Int}(undef, length(v))
for i = 1:length(v)
p[i] = i
end
sort!(p, Sort.DEFAULT_UNSTABLE, Order.Perm(Sort.Forward,v))
p
end
mutable struct IncrementalCompact
ir::IRCode
result::InstructionStream
result_bbs::Vector{BasicBlock}
ssa_rename::Vector{Any}
bb_rename_pred::Vector{Int}
bb_rename_succ::Vector{Int}
used_ssas::Vector{Int}
late_fixup::Vector{Int}
perm::Vector{Int}
new_nodes_idx::Int
# This supports insertion while compacting
new_new_nodes::NewNodeStream # New nodes that were before the compaction point at insertion time
new_new_used_ssas::Vector{Int}
# TODO: Switch these two to a min-heap of some sort
pending_nodes::NewNodeStream # New nodes that were after the compaction point at insertion time
pending_perm::Vector{Int}
# State
idx::Int
result_idx::Int
active_result_bb::Int
renamed_new_nodes::Bool
cfg_transforms_enabled::Bool
fold_constant_branches::Bool
function IncrementalCompact(code::IRCode, allow_cfg_transforms::Bool=false)
# Sort by position with attach after nodes after regular ones
perm = my_sortperm(Int[let new_node = code.new_nodes.info[i]
(new_node.pos * 2 + Int(new_node.attach_after))
end for i in 1:length(code.new_nodes)])
new_len = length(code.stmts) + length(code.new_nodes)
result = InstructionStream(new_len)
used_ssas = fill(0, new_len)
new_new_used_ssas = Vector{Int}()
blocks = code.cfg.blocks
if allow_cfg_transforms
bb_rename = Vector{Int}(undef, length(blocks))
cur_bb = 1
domtree = construct_domtree(blocks)
for i = 1:length(bb_rename)
if bb_unreachable(domtree, i)
bb_rename[i] = -1
else
bb_rename[i] = cur_bb
cur_bb += 1
end
end
for i = 1:length(bb_rename)
bb_rename[i] == -1 && continue
preds, succs = blocks[i].preds, blocks[i].succs
# Rename preds
for j = 1:length(preds)
if preds[j] != 0
preds[j] = bb_rename[preds[j]]
end
end
# Dead blocks get removed from the predecessor list
filter!(x->x !== -1, preds)
# Rename succs
for j = 1:length(succs)
succs[j] = bb_rename[succs[j]]
end
end
let blocks = blocks, bb_rename = bb_rename
result_bbs = BasicBlock[blocks[i] for i = 1:length(blocks) if bb_rename[i] != -1]
end
else
bb_rename = Vector{Int}()
result_bbs = code.cfg.blocks
end
ssa_rename = Any[SSAValue(i) for i = 1:new_len]
late_fixup = Vector{Int}()
new_new_nodes = NewNodeStream()
pending_nodes = NewNodeStream()
pending_perm = Int[]
return new(code, result, result_bbs, ssa_rename, bb_rename, bb_rename, used_ssas, late_fixup, perm, 1,
new_new_nodes, new_new_used_ssas, pending_nodes, pending_perm,
1, 1, 1, false, allow_cfg_transforms, allow_cfg_transforms)
end
# For inlining
function IncrementalCompact(parent::IncrementalCompact, code::IRCode, result_offset)
perm = my_sortperm(Int[code.new_nodes.info[i].pos for i in 1:length(code.new_nodes)])
new_len = length(code.stmts) + length(code.new_nodes)
ssa_rename = Any[SSAValue(i) for i = 1:new_len]
bb_rename = Vector{Int}()
pending_nodes = NewNodeStream()
pending_perm = Int[]
return new(code, parent.result,
parent.result_bbs, ssa_rename, bb_rename, bb_rename, parent.used_ssas,
parent.late_fixup, perm, 1,
parent.new_new_nodes, parent.new_new_used_ssas, pending_nodes, pending_perm,
1, result_offset, parent.active_result_bb, false, false, false)
end
end
struct TypesView{T}
ir::T # ::Union{IRCode, IncrementalCompact}
end
types(ir::Union{IRCode, IncrementalCompact}) = TypesView(ir)
function getindex(compact::IncrementalCompact, ssa::SSAValue)
@assert ssa.id < compact.result_idx
return compact.result[ssa.id]
end
function getindex(compact::IncrementalCompact, ssa::OldSSAValue)
id = ssa.id
if id < compact.idx
new_idx = compact.ssa_rename[id]
return compact.result[new_idx]
elseif id <= length(compact.ir.stmts)
return compact.ir.stmts[id]
end
id -= length(compact.ir.stmts)
if id <= length(compact.ir.new_nodes)
return compact.ir.new_nodes.stmts[id]
end
id -= length(compact.ir.new_nodes)
return compact.pending_nodes.stmts[id]
end
function getindex(compact::IncrementalCompact, ssa::NewSSAValue)
if ssa.id < 0
return compact.new_new_nodes.stmts[-ssa.id]
else
return compact[SSAValue(ssa.id)]
end
end
function block_for_inst(compact::IncrementalCompact, idx::SSAValue)
id = idx.id
if id < compact.result_idx # if ssa within result
return searchsortedfirst(compact.result_bbs, BasicBlock(StmtRange(id, id)),
1, compact.active_result_bb, bb_ordering())-1
else
return block_for_inst(compact.ir.cfg, id)
end
end
function block_for_inst(compact::IncrementalCompact, idx::OldSSAValue)
id = idx.id
if id < compact.idx # if ssa within result
id = compact.ssa_rename[id]
return block_for_inst(compact, SSAValue(id))
else
return block_for_inst(compact.ir.cfg, id)
end
end
function block_for_inst(compact::IncrementalCompact, idx::NewSSAValue)
if idx.id > 0
@assert idx.id < compact.result_idx
return block_for_inst(compact, SSAValue(idx.id))
else
return block_for_inst(compact, SSAValue(compact.new_new_nodes.info[-idx.id].pos))
end
end
function dominates_ssa(compact::IncrementalCompact, domtree::DomTree, x::AnySSAValue, y::AnySSAValue)
xb = block_for_inst(compact, x)
yb = block_for_inst(compact, y)
if xb == yb
xinfo = yinfo = nothing
if isa(x, OldSSAValue)
x′ = compact.ssa_rename[x.id]::SSAValue
elseif isa(x, NewSSAValue)
if x.id > 0
x′ = SSAValue(x.id)
else
xinfo = compact.new_new_nodes.info[-x.id]
x′ = SSAValue(xinfo.pos)
end
else
x′ = x
end
if isa(y, OldSSAValue)
y′ = compact.ssa_rename[y.id]::SSAValue
elseif isa(y, NewSSAValue)
if y.id > 0
y′ = SSAValue(y.id)
else
yinfo = compact.new_new_nodes.info[-y.id]
y′ = SSAValue(yinfo.pos)
end
else
y′ = y
end
if x′.id == y′.id && (xinfo !== nothing || yinfo !== nothing)
if xinfo !== nothing && yinfo !== nothing
if xinfo.attach_after == yinfo.attach_after
return x.id < y.id
end
return yinfo.attach_after
elseif xinfo !== nothing
return !xinfo.attach_after
else
return (yinfo::NewNodeInfo).attach_after
end
end
return x′.id < y′.id
end
return dominates(domtree, xb, yb)
end
function count_added_node!(compact::IncrementalCompact, @nospecialize(v))
needs_late_fixup = false
for ops in userefs(v)
val = ops[]
if isa(val, SSAValue)
compact.used_ssas[val.id] += 1
elseif isa(val, NewSSAValue)
@assert val.id < 0 # Newly added nodes should be canonicalized
compact.new_new_used_ssas[-val.id] += 1
needs_late_fixup = true
end
end
return needs_late_fixup
end
function add_pending!(compact::IncrementalCompact, pos::Int, attach_after::Bool)
node = add!(compact.pending_nodes, pos, attach_after)
# TODO: switch this to `l = length(pending_nodes); splice!(pending_perm, searchsorted(pending_perm, l), l)`
push!(compact.pending_perm, length(compact.pending_nodes))
sort!(compact.pending_perm, DEFAULT_STABLE, Order.By(x->compact.pending_nodes.info[x].pos, Order.Forward))
return node
end
function insert_node!(compact::IncrementalCompact, before, inst::NewInstruction, attach_after::Bool=false)
@assert inst.effect_free_computed
if isa(before, SSAValue)
if before.id < compact.result_idx
count_added_node!(compact, inst.stmt)
line = something(inst.line, compact.result[before.id][:line])
node = add!(compact.new_new_nodes, before.id, attach_after)
push!(compact.new_new_used_ssas, 0)
node[:inst], node[:type], node[:line], node[:flag] = inst.stmt, inst.type, line, inst.flag
return NewSSAValue(-node.idx)
else
line = something(inst.line, compact.ir.stmts[before.id][:line])
node = add_pending!(compact, before.id, attach_after)
node[:inst], node[:type], node[:line], node[:flag] = inst.stmt, inst.type, line, inst.flag
os = OldSSAValue(length(compact.ir.stmts) + length(compact.ir.new_nodes) + length(compact.pending_nodes))
push!(compact.ssa_rename, os)
push!(compact.used_ssas, 0)
return os
end
elseif isa(before, OldSSAValue)
pos = before.id
if pos < compact.idx
renamed = compact.ssa_rename[pos]::AnySSAValue
count_added_node!(compact, inst.stmt)
line = something(inst.line, compact.result[renamed.id][:line])
node = add!(compact.new_new_nodes, renamed.id, attach_after)
push!(compact.new_new_used_ssas, 0)
node[:inst], node[:type], node[:line], node[:flag] = inst.stmt, inst.type, line, inst.flag
return NewSSAValue(-node.idx)
else
if pos > length(compact.ir.stmts)
#@assert attach_after
info = compact.pending_nodes.info[pos - length(compact.ir.stmts) - length(compact.ir.new_nodes)]
pos, attach_after = info.pos, info.attach_after
end
line = something(inst.line, compact.ir.stmts[pos][:line])
node = add_pending!(compact, pos, attach_after)
node[:inst], node[:type], node[:line], node[:flag] = inst.stmt, inst.type, line, inst.flag
os = OldSSAValue(length(compact.ir.stmts) + length(compact.ir.new_nodes) + length(compact.pending_nodes))
push!(compact.ssa_rename, os)
push!(compact.used_ssas, 0)
return os
end
elseif isa(before, NewSSAValue)
# TODO: This is incorrect and does not maintain ordering among the new nodes
before_entry = compact.new_new_nodes.info[-before.id]
line = something(inst.line, compact.new_new_nodes.stmts[-before.id][:line])
new_entry = add!(compact.new_new_nodes, before_entry.pos, attach_after)
new_entry[:inst], new_entry[:type], new_entry[:line], new_entry[:flag] = inst.stmt, inst.type, line, inst.flag
push!(compact.new_new_used_ssas, 0)
return NewSSAValue(-new_entry.idx)
else
error("Unsupported")
end
end
function insert_node_here!(compact::IncrementalCompact, inst::NewInstruction, reverse_affinity::Bool=false)
@assert inst.line !== nothing
refinish = false
result_idx = compact.result_idx
if reverse_affinity &&
((compact.active_result_bb == length(compact.result_bbs) + 1) ||
result_idx == first(compact.result_bbs[compact.active_result_bb].stmts))
compact.active_result_bb -= 1
refinish = true
end
if result_idx > length(compact.result)
@assert result_idx == length(compact.result) + 1
resize!(compact, result_idx)
end
flag = inst.flag
if !inst.effect_free_computed
(consistent, effect_free_and_nothrow, nothrow) = stmt_effect_flags(fallback_lattice, inst.stmt, inst.type, compact)
if consistent
flag |= IR_FLAG_CONSISTENT
end
if effect_free_and_nothrow
flag |= IR_FLAG_EFFECT_FREE | IR_FLAG_NOTHROW
elseif nothrow
flag |= IR_FLAG_NOTHROW
end
end
node = compact.result[result_idx]
node[:inst], node[:type], node[:line], node[:flag] = inst.stmt, inst.type, inst.line, flag
count_added_node!(compact, inst.stmt) && push!(compact.late_fixup, result_idx)
compact.result_idx = result_idx + 1
inst = SSAValue(result_idx)
refinish && finish_current_bb!(compact, 0)
return inst
end
function getindex(view::TypesView, v::OldSSAValue)
id = v.id
ir = view.ir.ir
stmts = ir.stmts
if id <= length(stmts)
return stmts[id][:type]
end
id -= length(stmts)
if id <= length(ir.new_nodes)
return ir.new_nodes.stmts[id][:type]
end
id -= length(ir.new_nodes)
return view.ir.pending_nodes.stmts[id][:type]
end
function kill_current_uses(compact::IncrementalCompact, @nospecialize(stmt))
for ops in userefs(stmt)
val = ops[]
if isa(val, SSAValue)
@assert compact.used_ssas[val.id] >= 1
compact.used_ssas[val.id] -= 1
elseif isa(val, NewSSAValue)
@assert val.id < 0
@assert compact.new_new_used_ssas[-val.id] >= 1
compact.new_new_used_ssas[-val.id] -= 1
end
end
end
function setindex!(compact::IncrementalCompact, @nospecialize(v), idx::SSAValue)
@assert idx.id < compact.result_idx
(compact.result[idx.id][:inst] === v) && return
# Kill count for current uses
kill_current_uses(compact, compact.result[idx.id][:inst])
compact.result[idx.id][:inst] = v
# Add count for new use
count_added_node!(compact, v) && push!(compact.late_fixup, idx.id)
return compact
end
function setindex!(compact::IncrementalCompact, @nospecialize(v), idx::OldSSAValue)
id = idx.id
if id < compact.idx
new_idx = compact.ssa_rename[id]
(compact.result[new_idx][:inst] === v) && return
kill_current_uses(compact, compact.result[new_idx][:inst])
compact.result[new_idx][:inst] = v
count_added_node!(compact, v) && push!(compact.late_fixup, new_idx)
return compact
elseif id <= length(compact.ir.stmts) # ir.stmts, new_nodes, and pending_nodes uses aren't counted yet, so no need to adjust
compact.ir.stmts[id][:inst] = v
return compact
end
id -= length(compact.ir.stmts)
if id <= length(compact.ir.new_nodes)
compact.ir.new_nodes.stmts[id][:inst] = v
return compact
end
id -= length(compact.ir.new_nodes)
compact.pending_nodes.stmts[id][:inst] = v
return compact
end
function setindex!(compact::IncrementalCompact, @nospecialize(v), idx::Int)
if idx < compact.result_idx
compact[SSAValue(idx)] = v
else
compact.ir.stmts[idx][:inst] = v
end
return compact
end
__set_check_ssa_counts(onoff::Bool) = __check_ssa_counts__[] = onoff
const __check_ssa_counts__ = fill(false)
function _oracle_check(compact::IncrementalCompact)
observed_used_ssas = Core.Compiler.find_ssavalue_uses1(compact)
for i = 1:length(observed_used_ssas)
if observed_used_ssas[i] != compact.used_ssas[i]
return observed_used_ssas
end
end
return nothing
end
function oracle_check(compact::IncrementalCompact)
maybe_oracle_used_ssas = _oracle_check(compact)
if maybe_oracle_used_ssas !== nothing
@eval Main (compact = $compact; oracle_used_ssas = $maybe_oracle_used_ssas)
error("Oracle check failed, inspect Main.compact and Main.oracle_used_ssas")
end
end
getindex(view::TypesView, idx::SSAValue) = getindex(view, idx.id)
function getindex(view::TypesView, idx::Int)
if isa(view.ir, IncrementalCompact) && idx < view.ir.result_idx
return view.ir.result[idx][:type]
elseif isa(view.ir, IncrementalCompact) && view.ir.renamed_new_nodes
if idx <= length(view.ir.result)
return view.ir.result[idx][:type]
else
return view.ir.new_new_nodes.stmts[idx - length(view.ir.result)][:type]
end
else
ir = isa(view.ir, IncrementalCompact) ? view.ir.ir : view.ir
if idx <= length(ir.stmts)
return ir.stmts[idx][:type]
else
return ir.new_nodes.stmts[idx - length(ir.stmts)][:type]
end
end
end
function getindex(view::TypesView, idx::NewSSAValue)
return view.ir[idx][:type]
end
function process_phinode_values(old_values::Vector{Any}, late_fixup::Vector{Int},
processed_idx::Int, result_idx::Int,
ssa_rename::Vector{Any}, used_ssas::Vector{Int},
new_new_used_ssas::Vector{Int},
do_rename_ssa::Bool)
values = Vector{Any}(undef, length(old_values))
for i = 1:length(old_values)
isassigned(old_values, i) || continue
val = old_values[i]
if isa(val, SSAValue)
if do_rename_ssa
if val.id > processed_idx
push!(late_fixup, result_idx)
val = OldSSAValue(val.id)
else