-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathir.jl
2170 lines (2012 loc) · 80.6 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
isterminator(@nospecialize(stmt)) = isa(stmt, GotoNode) || isa(stmt, GotoIfNot) ||
isa(stmt, ReturnNode) || isa(stmt, EnterNode) || isexpr(stmt, :leave)
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::Int->x==from, preds)::Int)
deleteat!(succs, findfirst(x::Int->x==to, succs)::Int)
nothing
end
function bb_ordering()
lt = (<=)
by = x::BasicBlock -> 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, EnterNode)
# :enter starts/ends a BB
push!(jump_dests, idx)
push!(jump_dests, idx+1)
# The catch block is a jump dest
if stmt.catch_dest != 0
push!(jump_dests, stmt.catch_dest)
end
elseif isa(stmt, Expr)
if stmt.head === :leave
# :leave terminates a BB
push!(jump_dests, idx+1)
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 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 isa(terminator, EnterNode)
# :enter gets a virtual edge to the exception handler and
# the exception handler gets a virtual edge from outside
# the function.
if terminator.catch_dest != 0
block′ = block_for_inst(basic_block_index, terminator.catch_dest)
push!(blocks[block′].preds, num)
push!(blocks[block′].preds, 0)
push!(b.succs, block′)
end
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 is_valid_phiblock_stmt(@nospecialize(stmt))
isa(stmt, PhiNode) && return true
isa(stmt, Union{UpsilonNode, PhiCNode, SSAValue}) && return false
isa(stmt, Expr) && return is_value_pos_expr_head(stmt.head)
return true
end
function first_insert_for_bb(code::Vector{Any}, cfg::CFG, block::Int)
stmts = cfg.blocks[block].stmts
lastnonphiidx = first(stmts)
for idx in stmts
stmt = code[idx]
if !isa(stmt, PhiNode)
if !is_valid_phiblock_stmt(stmt)
return lastnonphiidx
end
else
lastnonphiidx = idx + 1
end
end
if lastnonphiidx > last(stmts)
error("any insert position isn't found")
end
return lastnonphiidx
end
# mutable version of the compressed DebugInfo
mutable struct DebugInfoStream
def::Union{MethodInstance,Symbol,Nothing}
linetable::Union{Nothing,DebugInfo}
edges::Vector{DebugInfo}
firstline::Int32 # the starting line for this block (specified by having an index of 0)
codelocs::Vector{Int32} # for each statement:
# index into linetable (if defined), else a line number (in the file represented by def)
# then index into edges
# then index into edges[linetable]
function DebugInfoStream(codelocs::Vector{Int32})
return new(nothing, nothing, DebugInfo[], 0, codelocs)
end
# DebugInfoStream(def::Union{MethodInstance,Nothing}, di::DebugInfo, nstmts::Int) =
# if debuginfo_file1(di.def) === debuginfo_file1(di.def)
# new(def, di.linetable, Core.svec(di.edges...), getdebugidx(di, 0),
# ccall(:jl_uncompress_codelocs, Any, (Any, Int), di.codelocs, nstmts)::Vector{Int32})
# else
function DebugInfoStream(def::Union{MethodInstance,Nothing}, di::DebugInfo, nstmts::Int)
codelocs = zeros(Int32, nstmts * 3)
for i = 1:nstmts
codelocs[3i - 2] = i
end
return new(def, di, DebugInfo[], 0, codelocs)
end
global copy(di::DebugInfoStream) = new(di.def, di.linetable, di.edges, di.firstline, di.codelocs)
end
Core.DebugInfo(di::DebugInfoStream, nstmts::Int) =
DebugInfo(something(di.def), di.linetable, Core.svec(di.edges...),
ccall(:jl_compress_codelocs, Any, (Int32, Any, Int), di.firstline, di.codelocs, nstmts)::String)
getdebugidx(debuginfo::DebugInfo, pc::Int) =
ccall(:jl_uncompress1_codeloc, NTuple{3,Int32}, (Any, Int), debuginfo.codelocs, pc)
function getdebugidx(debuginfo::DebugInfoStream, pc::Int)
if 3 <= 3pc <= length(debuginfo.codelocs)
return (debuginfo.codelocs[3pc-2], debuginfo.codelocs[3pc-1], debuginfo.codelocs[3pc-0])
elseif pc == 0
return (Int32(debuginfo.firstline), Int32(0), Int32(0))
else
return (Int32(-1), Int32(0), Int32(0))
end
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
stmt::Vector{Any}
type::Vector{Any}
info::Vector{CallInfo}
line::Vector{Int32}
flag::Vector{UInt32}
function InstructionStream(stmts::Vector{Any}, type::Vector{Any}, info::Vector{CallInfo}, line::Vector{Int32}, flag::Vector{UInt32})
return new(stmts, type, info, line, flag)
end
end
function InstructionStream(len::Int)
stmts = Vector{Any}(undef, len)
types = Vector{Any}(undef, len)
info = Vector{CallInfo}(undef, len)
fill!(info, NoCallInfo())
lines = fill(Int32(0), 3len)
flags = fill(IR_FLAG_NULL, len)
return InstructionStream(stmts, types, info, lines, flags)
end
InstructionStream() = InstructionStream(0)
length(is::InstructionStream) = length(is.stmt)
iterate(is::Compiler.InstructionStream, st::Int=1) = (st <= Compiler.length(is)) ? (is[st], st + 1) : nothing
isempty(is::InstructionStream) = isempty(is.stmt)
function add_new_idx!(is::InstructionStream)
ninst = length(is) + 1
resize!(is, ninst)
return ninst
end
function copy(is::InstructionStream)
return InstructionStream(
copy_exprargs(is.stmt),
copy(is.type),
copy(is.info),
copy(is.line),
copy(is.flag))
end
function resize!(stmts::InstructionStream, len)
old_length = length(stmts)
resize!(stmts.stmt, len)
resize!(stmts.type, len)
resize!(stmts.info, len)
resize!(stmts.line, 3len)
resize!(stmts.flag, len)
for i in (old_length + 1):len
stmts.line[3i-2], stmts.line[3i-1], stmts.line[3i] = NoLineUpdate
stmts.flag[i] = IR_FLAG_NULL
stmts.info[i] = NoCallInfo()
end
return stmts
end
struct Instruction
data::InstructionStream
idx::Int
end
Instruction(is::InstructionStream) = Instruction(is, add_new_idx!(is))
@inline function getindex(node::Instruction, fld::Symbol)
(fld === :inst) && (fld = :stmt) # deprecated
isdefined(node, fld) && return getfield(node, fld)
fldarray = getfield(getfield(node, :data), fld)
fldidx = getfield(node, :idx)
(fld === :line) && return (fldarray[3fldidx-2], fldarray[3fldidx-1], fldarray[3fldidx-0])
(1 ≤ fldidx ≤ length(fldarray)) || throw(InvalidIRError())
return fldarray[fldidx]
end
@inline function setindex!(node::Instruction, @nospecialize(val), fld::Symbol)
(fld === :inst) && (fld = :stmt) # deprecated
fldarray = getfield(getfield(node, :data), fld)
fldidx = getfield(node, :idx)
if fld === :line
(fldarray[3fldidx-2], fldarray[3fldidx-1], fldarray[3fldidx-0]) = val::NTuple{3,Int32}
else
fldarray[fldidx] = val
end
return node
end
@inline getindex(is::InstructionStream, idx::Int) = Instruction(is, idx)
function setindex!(is::InstructionStream, newval::Instruction, idx::Int)
is.stmt[idx] = newval[:stmt]
is.type[idx] = newval[:type]
is.info[idx] = newval[:info]
(is.line[3idx-2], is.line[3idx-1], is.line[3idx-0]) = newval[:line]
is.flag[idx] = newval[:flag]
return is
end
function setindex!(is::InstructionStream, newval::Union{AnySSAValue, Nothing}, idx::Int)
is.stmt[idx] = newval
return is
end
function setindex!(node::Instruction, newval::Instruction)
node.data[node.idx] = newval
return node
end
has_flag(inst::Instruction, flag::UInt32) = has_flag(inst[:flag], flag)
add_flag!(inst::Instruction, flag::UInt32) = inst[:flag] |= flag
sub_flag!(inst::Instruction, flag::UInt32) = inst[:flag] &= ~flag
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_inst!(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::CallInfo
line::Union{NTuple{3,Int32},Nothing} # if nothing, copy the line from previous statement in the insertion location
flag::Union{UInt32,Nothing} # if nothing, IR flags will be recomputed on insertion
function NewInstruction(@nospecialize(stmt), @nospecialize(type), @nospecialize(info::CallInfo),
line::Union{NTuple{3,Int32},Int32,Nothing}, flag::Union{UInt32,Nothing})
line isa Int32 && (line = (line, zero(Int32), zero(Int32)))
return new(stmt, type, info, line, flag)
end
end
function NewInstruction(@nospecialize(stmt), @nospecialize(type), line::Union{NTuple{3,Int32},Int32,Nothing}=nothing)
return NewInstruction(stmt, type, NoCallInfo(), line, nothing)
end
@nospecialize
function NewInstruction(newinst::NewInstruction;
stmt::Any=newinst.stmt,
type::Any=newinst.type,
info::CallInfo=newinst.info,
line::Union{NTuple{3,Int32},Int32,Nothing}=newinst.line,
flag::Union{UInt32,Nothing}=newinst.flag)
return NewInstruction(stmt, type, info, line, flag)
end
function NewInstruction(inst::Instruction;
stmt::Any=inst[:stmt],
type::Any=inst[:type],
info::CallInfo=inst[:info],
line::Union{NTuple{3,Int32},Int32,Nothing}=inst[:line],
flag::Union{UInt32,Nothing}=inst[:flag])
return NewInstruction(stmt, type, info, line, flag)
end
@specialize
removable_if_unused(newinst::NewInstruction) = add_flag(newinst, IR_FLAGS_REMOVABLE)
function add_flag(newinst::NewInstruction, newflag::UInt32)
flag = newinst.flag
if flag === nothing
flag = newflag
else
flag |= newflag
end
return NewInstruction(newinst; flag)
end
function sub_flag(newinst::NewInstruction, newflag::UInt32)
flag = newinst.flag
if flag === nothing
flag = IR_FLAG_NULL
else
flag &= ~newflag
end
return NewInstruction(newinst; flag)
end
struct IRCode
stmts::InstructionStream
argtypes::Vector{Any}
sptypes::Vector{VarState}
debuginfo::DebugInfoStream
cfg::CFG
new_nodes::NewNodeStream
meta::Vector{Expr}
valid_worlds::WorldRange
function IRCode(stmts::InstructionStream, cfg::CFG, debuginfo::DebugInfoStream,
argtypes::Vector{Any}, meta::Vector{Expr}, sptypes::Vector{VarState},
valid_worlds=WorldRange(typemin(UInt), typemax(UInt)))
return new(stmts, argtypes, sptypes, debuginfo, cfg, NewNodeStream(), meta, valid_worlds)
end
function IRCode(ir::IRCode, stmts::InstructionStream, cfg::CFG, new_nodes::NewNodeStream)
di = ir.debuginfo
@assert di.codelocs === stmts.line
return new(stmts, ir.argtypes, ir.sptypes, di, cfg, new_nodes, ir.meta, ir.valid_worlds)
end
global function copy(ir::IRCode)
di = ir.debuginfo
stmts = copy(ir.stmts)
di = copy(di)
di.edges = copy(di.edges)
di.codelocs = stmts.line
return new(stmts, copy(ir.argtypes), copy(ir.sptypes), di, copy(ir.cfg), copy(ir.new_nodes), copy(ir.meta), ir.valid_worlds)
end
end
"""
IRCode()
Create an empty IRCode object with a single `return nothing` statement. This method is mostly intended
for debugging and unit testing of IRCode APIs. The compiler itself should generally obtain an IRCode
from the frontend or one of the caches.
"""
function IRCode()
stmts = InstructionStream(1)
debuginfo = DebugInfoStream(stmts.line)
stmts.line[1] = 1
ir = IRCode(stmts, CFG([BasicBlock(1:1, Int[], Int[])], Int[1]), debuginfo, Any[], Expr[], VarState[])
ir[SSAValue(1)][:stmt] = ReturnNode(nothing)
ir[SSAValue(1)][:type] = Nothing
ir[SSAValue(1)][:flag] = 0x00
ir[SSAValue(1)][:line] = NoLineUpdate
return ir
end
construct_domtree(ir::IRCode) = construct_domtree(ir.cfg)
construct_domtree(cfg::CFG) = construct_domtree(cfg.blocks)
construct_postdomtree(ir::IRCode) = construct_postdomtree(ir.cfg)
construct_postdomtree(cfg::CFG) = construct_postdomtree(cfg.blocks)
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
block_for_inst(ir::IRCode, ssa::SSAValue) = block_for_inst(ir, ssa.id)
function getindex(ir::IRCode, s::SSAValue)
id = s.id
(id ≥ 1) || throw(InvalidIRError())
nstmts = length(ir.stmts)
if id <= nstmts
return ir.stmts[id]
else
id -= nstmts
stmts = ir.new_nodes.stmts
(id ≤ length(stmts)) || throw(InvalidIRError())
return stmts[id]
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, EnterNode)
isdefined(stmt, :scope) || return OOB_TOKEN
op == 1 || return OOB_TOKEN
return stmt.scope
elseif isa(stmt, PiNode)
isdefined(stmt, :val) || return OOB_TOKEN
op == 1 || return OOB_TOKEN
return stmt.val
elseif isa(stmt, Union{AnySSAValue, 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,
:throw_undef_if_not,
:cfunction, :method, :pop_exception,
:leave,
: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 = ReturnNode(v)
elseif isa(stmt, EnterNode)
op == 1 || throw(BoundsError())
stmt = EnterNode(stmt.catch_dest, v)
elseif isa(stmt, Union{AnySSAValue, GlobalRef})
op == 1 || throw(BoundsError())
stmt = v
elseif isa(stmt, UpsilonNode)
op == 1 || throw(BoundsError())
stmt = UpsilonNode(v)
elseif isa(stmt, PiNode)
op == 1 || throw(BoundsError())
stmt = PiNode(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, OldSSAValue) || isa(x, NewSSAValue) ||
isa(x, PiNode) || isa(x, PhiNode) || isa(x, PhiCNode) || isa(x, UpsilonNode) || isa(x, EnterNode)
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, newinst::NewInstruction, attach_after::Bool=false)
posid = pos.id
if pos.id > length(ir.stmts)
if attach_after
info = ir.new_nodes.info[pos.id-length(ir.stmts)];
posid = info.pos
attach_after = info.attach_after
else
error("Cannot attach before a pending node.")
end
end
node = add_inst!(ir.new_nodes, posid, attach_after)
newline = something(newinst.line, ir[pos][:line])
newflag = recompute_newinst_flag(newinst, ir)
node = inst_from_newinst!(node, newinst, newline, newflag)
return SSAValue(length(ir.stmts) + node.idx)
end
insert_node!(ir::IRCode, pos::Int, newinst::NewInstruction, attach_after::Bool=false) =
insert_node!(ir, SSAValue(pos), newinst, attach_after)
struct CFGTransformState
cfg_transforms_enabled::Bool
fold_constant_branches::Bool
result_bbs::Vector{BasicBlock}
bb_rename_pred::Vector{Int}
bb_rename_succ::Vector{Int}
domtree::Union{Nothing, DomTree}
end
# N.B.: Takes ownership of the CFG array
function CFGTransformState!(blocks::Vector{BasicBlock}, allow_cfg_transforms::Bool=false)
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::Int->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
# TODO: This could be done by just renaming the domtree
domtree = construct_domtree(result_bbs)
else
bb_rename = Vector{Int}()
result_bbs = blocks
domtree = nothing
end
return CFGTransformState(allow_cfg_transforms, allow_cfg_transforms, result_bbs, bb_rename, bb_rename, domtree)
end
mutable struct IncrementalCompact
ir::IRCode
result::InstructionStream
cfg_transform::CFGTransformState
ssa_rename::Vector{Any}
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}
pending_nodes::NewNodeStream # New nodes that were after the compaction point at insertion time
pending_perm::Vector{Int} # pending_nodes.info[pending_perm] is in min-heap order by pos
# State
idx::Int
result_idx::Int
active_bb::Int
active_result_bb::Int
renamed_new_nodes::Bool
function IncrementalCompact(code::IRCode, cfg_transform::CFGTransformState)
# Sort by position with attach after nodes after regular ones
info = code.new_nodes.info
perm = sort!(collect(eachindex(info)); by=i::Int->(2info[i].pos+info[i].attach_after, i))
new_len = length(code.stmts) + length(info)
result = InstructionStream(new_len)
code.debuginfo.codelocs = result.line
used_ssas = fill(0, new_len)
new_new_used_ssas = Vector{Int}()
blocks = code.cfg.blocks
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, cfg_transform, ssa_rename, used_ssas, late_fixup, perm, 1,
new_new_nodes, new_new_used_ssas, pending_nodes, pending_perm,
1, 1, 1, 1, false)
end
# For inlining
function IncrementalCompact(parent::IncrementalCompact, code::IRCode, result_offset)
info = code.new_nodes.info
perm = sort!(collect(eachindex(info)); by=i::Int->(info[i].pos, i))
new_len = length(code.stmts) + length(info)
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, CFGTransformState(false, false, parent.cfg_transform.result_bbs, bb_rename, bb_rename, nothing),
ssa_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, 1, parent.active_result_bb, false)
end
end
function IncrementalCompact(code::IRCode, allow_cfg_transforms::Bool=false)
return IncrementalCompact(code, CFGTransformState!(code.cfg.blocks, allow_cfg_transforms))
end
struct TypesView{T}
ir::T # ::Union{IRCode, IncrementalCompact}
end
types(ir::Union{IRCode, IncrementalCompact}) = TypesView(ir)
function getindex(compact::IncrementalCompact, ssa::SSAValue)
(1 ≤ ssa.id ≤ compact.result_idx) || throw(InvalidIRError())
return compact.result[ssa.id]
end
function getindex(compact::IncrementalCompact, ssa::OldSSAValue)
id = ssa.id
(id ≥ 1) || throw(InvalidIRError())
if id < compact.idx
new_idx = compact.ssa_rename[id]::Int
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)
(id ≤ length(compact.pending_nodes.stmts)) || throw(InvalidIRError())
return compact.pending_nodes.stmts[id]
end
function getindex(compact::IncrementalCompact, ssa::NewSSAValue)
if ssa.id < 0
stmts = compact.new_new_nodes.stmts
(-ssa.id ≤ length(stmts)) || throw(InvalidIRError())
return 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.cfg_transform.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]::Int
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
if isa(compact[x][:stmt], PhiNode)
if isa(compact[y][:stmt], PhiNode)
# A node dominates another only if it dominates all uses of that note.
# Usually that is not a distinction. However, for phi nodes, the use
# occurs on the edge to the predecessor block. Thus, by definition, for
# any other PhiNode in the same BB there must be (at least) one edge
# that this phi node does not dominate.
return false
end
end
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
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
elseif yinfo !== nothing
return yinfo.attach_after
end
end
return x′.id < y′.id
end
return dominates(domtree, xb, yb)
end
function _count_added_node!(compact::IncrementalCompact, @nospecialize(val))
if isa(val, SSAValue)
compact.used_ssas[val.id] += 1
return false
elseif isa(val, NewSSAValue)
@assert val.id < 0 # Newly added nodes should be canonicalized
compact.new_new_used_ssas[-val.id] += 1
return true
end
return false
end
function count_added_node!(compact::IncrementalCompact, @nospecialize(v))
needs_late_fixup = false
for ops in userefs(v)
needs_late_fixup |= _count_added_node!(compact, ops[])
end
return needs_late_fixup
end
function add_pending!(compact::IncrementalCompact, pos::Int, attach_after::Bool)
node = add_inst!(compact.pending_nodes, pos, attach_after)
heappush!(compact.pending_perm, length(compact.pending_nodes), By(x::Int->compact.pending_nodes.info[x].pos))
return node
end
function inst_from_newinst!(node::Instruction, newinst::NewInstruction,
newline::NTuple{3,Int32}=newinst.line::NTuple{3,Int32}, newflag::UInt32=newinst.flag::UInt32)
node[:stmt] = newinst.stmt
node[:type] = newinst.type
node[:info] = newinst.info
node[:line] = newline
node[:flag] = newflag
return node
end
function recompute_newinst_flag(newinst::NewInstruction, src::Union{IRCode,IncrementalCompact})
flag = newinst.flag
flag !== nothing && return flag
return recompute_effects_flags(fallback_lattice, newinst.stmt, newinst.type, src)
end
function insert_node!(compact::IncrementalCompact, @nospecialize(before), newinst::NewInstruction, attach_after::Bool=false)
newflag = recompute_newinst_flag(newinst, compact)
if isa(before, SSAValue)
if before.id < compact.result_idx
count_added_node!(compact, newinst.stmt)
newline = something(newinst.line, compact.result[before.id][:line])
node = add_inst!(compact.new_new_nodes, before.id, attach_after)
node = inst_from_newinst!(node, newinst, newline, newflag)
push!(compact.new_new_used_ssas, 0)
return NewSSAValue(-node.idx)
else
newline = something(newinst.line, compact.ir.stmts[before.id][:line])
node = add_pending!(compact, before.id, attach_after)
node = inst_from_newinst!(node, newinst, newline, newflag)
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, newinst.stmt)
newline = something(newinst.line, compact.result[renamed.id][:line])
node = add_inst!(compact.new_new_nodes, renamed.id, attach_after)
node = inst_from_newinst!(node, newinst, newline, newflag)
push!(compact.new_new_used_ssas, 0)
return NewSSAValue(-node.idx)