Skip to content

Commit 406fa38

Browse files
committed
implement a better statement selection logic
Specifically, this commit aims to review the implementation of `add_control_flow!` and improves its accuracy. Ideally, it should pass JET's existing test cases as well as the newly added ones, including the test cases from JuliaDebug/LoweredCodeUtils.jl#99. The goal is to share the same high-precision CFG selection logic between LoweredCodeUtils and JET. The new algorithm is based on what was proposed in [^Wei84]. If there is even one active block in the blocks reachable from a conditional branch up to its successors' nearest common post-dominator (referred to as **INFL** in the paper), it is necessary to follow that conditional branch and execute the code. Otherwise, execution can be short-circuited from the conditional branch to the nearest common post-dominator. COMBAK: It is important to note that in Julia's IR (`CodeInfo`), "short-circuiting" a specific code region is not a simple task. Simply ignoring the path to the post-dominator does not guarantee fall-through to the post-dominator. Therefore, a more careful implementation is required for this aspect. [Wei84]: M. Weiser, "Program Slicing," IEEE Transactions on Software Engineering, 10, pages 352-357, July 1984.
1 parent 2dfcd4e commit 406fa38

File tree

3 files changed

+238
-70
lines changed

3 files changed

+238
-70
lines changed

src/JET.jl

+4-3
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,10 @@ using .CC: @nospecs, ⊑,
4141
InvokeCallInfo, MethodCallResult, MethodMatchInfo, MethodMatches, NOT_FOUND,
4242
OptimizationState, OptimizationParams, OverlayMethodTable, StmtInfo, UnionSplitInfo,
4343
UnionSplitMethodMatches, VarState, VarTable, WorldRange, WorldView,
44-
argextype, argtype_by_index, argtypes_to_type, hasintersect, ignorelimited,
45-
instanceof_tfunc, istopfunction, singleton_type, slot_id, specialize_method,
46-
tmeet, tmerge, typeinf_lattice, widenconst, widenlattice
44+
argextype, argtype_by_index, argtypes_to_type, compute_basic_blocks, construct_domtree,
45+
construct_postdomtree, hasintersect, ignorelimited, instanceof_tfunc, istopfunction,
46+
nearest_common_dominator, singleton_type, slot_id, specialize_method, tmeet, tmerge,
47+
typeinf_lattice, widenconst, widenlattice
4748

4849
using Base: IdSet, get_world_counter
4950

src/toplevel/virtualprocess.jl

+123-58
Original file line numberDiff line numberDiff line change
@@ -1091,16 +1091,44 @@ end
10911091

10921092
# select statements that should be concretized, and actually interpreted rather than abstracted
10931093
function select_statements(mod::Module, src::CodeInfo)
1094-
stmts = src.code
10951094
cl = LoweredCodeUtils.CodeLinks(mod, src) # make `CodeEdges` hold `CodeLinks`?
10961095
edges = LoweredCodeUtils.CodeEdges(src, cl)
1097-
1098-
concretize = falses(length(stmts))
1099-
1100-
select_direct_requirement!(concretize, stmts, edges)
1101-
1096+
concretize = falses(length(src.code))
1097+
select_direct_requirement!(concretize, src.code, edges)
11021098
select_dependencies!(concretize, src, edges, cl)
1099+
return concretize
1100+
end
11031101

1102+
# just for testing, and debugging
1103+
function select_statements(mod::Module, src::CodeInfo, names::Symbol...)
1104+
cl = LoweredCodeUtils.CodeLinks(mod, src) # make `CodeEdges` hold `CodeLinks`?
1105+
edges = LoweredCodeUtils.CodeEdges(src, cl)
1106+
concretize = falses(length(src.code))
1107+
objs = Set{GlobalRef}(GlobalRef(mod, name) for name in names)
1108+
LoweredCodeUtils.add_requests!(concretize, objs, edges, ())
1109+
select_dependencies!(concretize, src, edges, cl)
1110+
return concretize
1111+
end
1112+
function select_statements(mod::Module, src::CodeInfo, slots::SlotNumber...)
1113+
cl = LoweredCodeUtils.CodeLinks(mod, src) # make `CodeEdges` hold `CodeLinks`?
1114+
edges = LoweredCodeUtils.CodeEdges(src, cl)
1115+
concretize = falses(length(src.code))
1116+
for slot in slots
1117+
for d in cl.slotassigns[slot.id]
1118+
concretize[d] = true
1119+
end
1120+
end
1121+
select_dependencies!(concretize, src, edges, cl)
1122+
return concretize
1123+
end
1124+
function select_statements(mod::Module, src::CodeInfo, idxs::Int...)
1125+
cl = LoweredCodeUtils.CodeLinks(mod, src) # make `CodeEdges` hold `CodeLinks`?
1126+
edges = LoweredCodeUtils.CodeEdges(src, cl)
1127+
concretize = falses(length(src.code))
1128+
for idx = idxs
1129+
concretize[idx] |= true
1130+
end
1131+
select_dependencies!(concretize, src, edges, cl)
11041132
return concretize
11051133
end
11061134

@@ -1173,67 +1201,70 @@ end
11731201

11741202
# The goal of this function is to request concretization of the minimal necessary control
11751203
# flow to evaluate statements whose concretization have already been requested.
1176-
# The basic approach is to check if there are any active successors for each basic block,
1177-
# and if there is an active successor and the terminator is not a fall-through, then request
1178-
# the concretization of that terminator. Additionally, for conditional terminators, a simple
1179-
# optimization using post-domination analysis is also performed.
1180-
function add_control_flow!(concretize::BitVector, src::CodeInfo, cfg::CFG, postdomtree)
1204+
# The basic algorithm is based on what was proposed in [^Wei84]. If there is even one active
1205+
# block in the blocks reachable from a conditional branch up to its successors' nearest
1206+
# common post-dominator (referred to as **INFL** in the paper), it is necessary to follow
1207+
# that conditional branch and execute the code. Otherwise, execution can be short-circuited
1208+
# from the conditional branch to the nearest common post-dominator.
1209+
#
1210+
# COMBAK: It is important to note that in Julia's intermediate code representation (`CodeInfo`),
1211+
# "short-circuiting" a specific code region is not a simple task. Simply ignoring the path
1212+
# to the post-dominator does not guarantee fall-through to the post-dominator. Therefore,
1213+
# a more careful implementation is required for this aspect.
1214+
#
1215+
# [Wei84]: M. Weiser, "Program Slicing," IEEE Transactions on Software Engineering, 10, pages 352-357, July 1984.
1216+
function add_control_flow!(concretize::BitVector, src::CodeInfo, cfg::CFG, domtree, postdomtree)
11811217
local changed::Bool = false
11821218
function mark_concretize!(idx::Int)
11831219
if !concretize[idx]
1184-
concretize[idx] = true
1220+
changed |= concretize[idx] = true
11851221
return true
11861222
end
11871223
return false
11881224
end
1189-
nblocks = length(cfg.blocks)
1190-
for bbidx = 1:nblocks
1191-
bb = cfg.blocks[bbidx] # forward traversal
1225+
for bbidx = 1:length(cfg.blocks) # forward traversal
1226+
bb = cfg.blocks[bbidx]
11921227
nsuccs = length(bb.succs)
11931228
if nsuccs == 0
11941229
continue
11951230
elseif nsuccs == 1
1196-
terminator_idx = bb.stmts[end]
1197-
if src.code[terminator_idx] isa GotoNode
1198-
# If the destination of this `GotoNode` is not active, it's fine to ignore
1199-
# the control flow caused by this `GotoNode` and treat it as a fall-through.
1200-
# If the block that is fallen through to is active and has a dependency on
1201-
# this goto block, then the concretization of this goto block should already
1202-
# be requested (at some point of the higher concretization convergence cycle
1203-
# of `select_dependencies`), and thus, this `GotoNode` will be concretized.
1204-
if any(@view concretize[cfg.blocks[only(bb.succs)].stmts])
1205-
changed |= mark_concretize!(terminator_idx)
1231+
termidx = bb.stmts[end]
1232+
if src.code[termidx] isa GotoNode
1233+
succ = only(bb.succs)
1234+
if any(@view concretize[cfg.blocks[succ].stmts])
1235+
dominator = nearest_common_dominator(domtree, bbidx, succ)
1236+
if dominator succ
1237+
for blk in reachable_blocks(cfg, dominator, succ)
1238+
if blk == dominator || blk == succ
1239+
continue
1240+
end
1241+
if any(@view concretize[cfg.blocks[blk].stmts])
1242+
mark_concretize!(termidx)
1243+
break
1244+
end
1245+
end
1246+
else
1247+
mark_concretize!(termidx)
1248+
end
12061249
end
12071250
end
1251+
continue # we can just fall-through
12081252
elseif nsuccs == 2
1209-
terminator_idx = bb.stmts[end]
1210-
@assert is_conditional_terminator(src.code[terminator_idx]) "invalid IR"
1253+
termidx = bb.stmts[end]
1254+
@assert is_conditional_terminator(src.code[termidx]) "invalid IR"
12111255
succ1, succ2 = bb.succs
1212-
succ1_req = any(@view concretize[cfg.blocks[succ1].stmts])
1213-
succ2_req = any(@view concretize[cfg.blocks[succ2].stmts])
1214-
if succ1_req
1215-
if succ2_req
1216-
changed |= mark_concretize!(terminator_idx)
1217-
else
1218-
active_bb, inactive_bb = succ1, succ2
1219-
@goto asymmetric_case
1256+
postdominator = nearest_common_dominator(postdomtree, succ1, succ2)
1257+
inflblks = reachable_blocks(cfg, succ1, postdominator) reachable_blocks(cfg, succ2, postdominator)
1258+
for blk in inflblks
1259+
if blk == postdominator
1260+
continue
12201261
end
1221-
elseif succ2_req
1222-
active_bb, inactive_bb = succ2, succ1
1223-
@label asymmetric_case
1224-
# We can ignore the control flow of this conditional terminator and treat
1225-
# it as a fall-through if only one of its successors is active and the
1226-
# active block post-dominates the inactive one, since the post-domination
1227-
# ensures that the active basic block will be reached regardless of the
1228-
# control flow.
1229-
if CC.postdominates(postdomtree, active_bb, inactive_bb)
1230-
# fall through this block
1231-
else
1232-
changed |= mark_concretize!(terminator_idx)
1262+
if any(@view concretize[cfg.blocks[blk].stmts])
1263+
mark_concretize!(termidx)
1264+
break
12331265
end
1234-
else
1235-
# both successors are inactive, just fall through this block
12361266
end
1267+
# we can just fall-through to the post dominator block (by ignoring all statements between)
12371268
end
12381269
end
12391270
return changed
@@ -1242,6 +1273,25 @@ end
12421273
is_conditional_terminator(@nospecialize stmt) = stmt isa GotoIfNot ||
12431274
(@static @isdefined(EnterNode) ? stmt isa EnterNode : isexpr(stmt, :enter))
12441275

1276+
function reachable_blocks(cfg::CFG, from_bb::Int, to_bb::Int)
1277+
worklist = Int[from_bb]
1278+
visited = BitSet(from_bb)
1279+
if to_bb == from_bb
1280+
return visited
1281+
end
1282+
push!(visited, to_bb)
1283+
function visit!(bb::Int)
1284+
if bb visited
1285+
push!(visited, bb)
1286+
push!(worklist, bb)
1287+
end
1288+
end
1289+
while !isempty(worklist)
1290+
foreach(visit!, cfg.blocks[pop!(worklist)].succs)
1291+
end
1292+
return visited
1293+
end
1294+
12451295
function add_required_inplace!(concretize::BitVector, src::CodeInfo, edges, cl)
12461296
changed = false
12471297
for i = 1:length(src.code)
@@ -1272,27 +1322,42 @@ function is_arg_requested(@nospecialize(arg), concretize, edges, cl)
12721322
return false
12731323
end
12741324

1325+
# The purpose of this function is to find other statements that affect the execution of the
1326+
# statements choosen by `select_direct_dependencies!`. In other words, it extracts the
1327+
# minimal amount of code necessary to realize the required concretization.
1328+
# This technique is generally referred to as "program slicing," and specifically as
1329+
# "static program slicing". The basic algorithm implemented here is an extension of the one
1330+
# proposed in https://dl.acm.org/doi/10.5555/800078.802557, which is especially tuned for
1331+
# Julia's intermediate code representation.
12751332
function select_dependencies!(concretize::BitVector, src::CodeInfo, edges, cl)
12761333
typedefs = LoweredCodeUtils.find_typedefs(src)
1277-
cfg = CC.compute_basic_blocks(src.code)
1278-
postdomtree = CC.construct_postdomtree(cfg.blocks)
1334+
cfg = compute_basic_blocks(src.code)
1335+
domtree = construct_domtree(cfg.blocks)
1336+
postdomtree = construct_postdomtree(cfg.blocks)
12791337

12801338
while true
12811339
changed = false
12821340

1283-
# discover struct/method definitions at the beginning,
1284-
# and propagate the definition requirements by tracking SSA precedessors
1341+
# Discover Dtruct/method definitions at the beginning,
1342+
# and propagate the definition requirements by tracking SSA precedessors.
1343+
# (TODO maybe hoist this out of the loop?)
12851344
changed |= LoweredCodeUtils.add_typedefs!(concretize, src, edges, typedefs, ())
12861345
changed |= add_ssa_preds!(concretize, src, edges, ())
12871346

1288-
# mark some common inplace operations like `push!(x, ...)` and `setindex!(x, ...)`
1289-
# when `x` has been marked already: otherwise we may end up using it with invalid state
1347+
# Mark some common inplace operations like `push!(x, ...)` and `setindex!(x, ...)`
1348+
# when `x` has been marked already: otherwise we may end up using it with invalid state.
1349+
# However, note that this is an incomplete approach, and note that the slice created
1350+
# by this routine will not be sound because of this. This is because
1351+
# `add_required_inplace!` only requires certain special-cased function calls and
1352+
# does not take into account the possibility that arguments may be mutated in
1353+
# arbitrary function calls. Ideally, function calls should be required while
1354+
# considering the effects of these statements, or by some sort of an
1355+
# inter-procedural program slicing
12901356
changed |= add_required_inplace!(concretize, src, edges, cl)
12911357
changed |= add_ssa_preds!(concretize, src, edges, ())
12921358

1293-
# mark necessary control flows,
1294-
# and propagate the definition requirements by tracking SSA precedessors
1295-
changed |= add_control_flow!(concretize, src, cfg, postdomtree)
1359+
# Mark necessary control flows.
1360+
changed |= add_control_flow!(concretize, src, cfg, domtree, postdomtree)
12961361
changed |= add_ssa_preds!(concretize, src, edges, ())
12971362

12981363
changed || break

0 commit comments

Comments
 (0)