Algorithmresearch
IDE framework
Also called interprocedural distributive environments.
Extends IFDS to environment problems, such as linear constant propagation, by labeling exploded edges with distributive value functions.
- Solves
- Constant propagation
- Time
- O(E D^3) worst · averageΘ(N + E) best
- Space
- O(N D^2 + C D^2) extra
- Where
- C = the number of call sites; D = the largest number of facts of one procedure; E = the number of edges of the supergraph; N = the number of nodes of the supergraph
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
The IDE framework of Sagiv, Reps and Horwitz extends IFDS from sets of facts to environments. IDE stands for Interprocedural, Distributive, Environment. An environment maps each fact, usually a variable, to a value in a lattice, and every flow function must distribute over the meet of environments. Such a function is fixed by small functions on single values, one for each pair of facts. IDE puts these micro-functions on the edges of the exploded supergraph of IFDS. Phase I walks the graph like the tabulation algorithm, but each path edge carries the meet of the micro-functions along its paths. Phase II pushes actual values through these functions. The main example is linear constant propagation, where a variable may be a constant or of one other variable. The result is the meet over all valid paths, and the time is when micro-functions are cheap and the value lattice has finite height.
In plain words
IFDS answers yes or no questions, such as "may this variable hold a secret". Many analyses need a value instead, such as "this variable is always 7". IDE handles these. It keeps the same big graph, with one copy of every program point for each variable. But each edge now carries a small rule that says how a value changes on the way, such as "add 1" or "times 3". First the algorithm builds, for each procedure, rules that go all the way from the entry to every point. It joins rules where paths meet. Then it feeds the real values in at the entry of the program and applies the rules. A procedure that adds 1 to its argument gives a constant at each call with a constant argument, even when the argument differs between callers.
The problem
An IDE instance is a supergraph , a finite set of facts for each procedure , a value lattice of finite height, and for each edge an environment transformer that distributes over the pointwise meet. The output is, for every node and fact , the meet over all valid paths
where is the start environment. This page uses the meet convention of Kildall: the start value is and the result is the greatest solution. In the join convention of Cousot the order flips and the same result is the least solution.
A distributive transformer is given by micro-functions. For each pair of facts there is a function , and
where the extra fact always has the value . The pair carries the part of that does not depend on any input, such as x = 5. A pair with has no edge.
The implementation solves linear constant propagation on the toy IR. The values are , the integers and . The micro-functions are:
| form | meaning |
|---|---|
top |
, the function of no path |
bot |
|
const k |
|
line a b |
with , and |
point l0 v |
, every other value |
Every form maps to . The set is closed under meet and composition. The meet of two lines with different slopes agrees with both at one point at most, so it is a point function or bot. Each function has exactly one form, so two functions are equal exactly when their tuples are equal. A chain of strict meets from top has at most three steps.
| statement | edges and micro-functions |
|---|---|
x = k |
: const k; every other : identity |
x = a |
: identity, plus the identity for every |
x = a + k, a - k, k - a, a * k |
: a line. a * 0 gives : const 0 |
x = k1 op k2 |
: const of the result, or bot on a trap |
any other x = a op b |
: bot |
ret a |
: identity, or : const a for a constant |
call edge of x = call q(a, b) |
each argument variable to its parameter: identity; a constant argument gives parameter: const |
| call-to-return edge | identity for every fact of the caller except x |
| return edge | : identity, : identity |
The parameters of main are unless a seed value is given.
The algorithm
Phase I computes a jump function for each pair of a node in procedure and facts . It is the meet of the micro-function compositions along all same-level paths from to . It also computes a summary function for each call site, which goes from through the callee to . A key enters the worklist again each time its function goes down. Phase II computes values at start nodes and call nodes with a second worklist, then gets every other value with one application of a jump function.
IDE(G*, F, seeds) F gives the labelled exploded edges; seeds gives values to the parameters of main- 1
Jump, Through, Summary ← λl.⊤ everywhere; WorkList ← [] - 2
for each d in {0} ∪ params(main) do PROPAGATE(s_main, d, d, id) - 3
while WorkList is not empty do - 4
(n, d1, d2) ← remove the first item; f ← Jump(n, d1, d2) (n is in procedure p) - 5
if n is a call node c, with callee q and return site r then - 6
for each call edge <c,d2> → <s_q,d3> do PROPAGATE(s_q, d3, d3, id) - 7
for each edge <c,d2> → <r,d3> with label g, call-to-return or Summary(c, d2, d3), do PROPAGATE(r, d1, d3, g ∘ f) - 8
else if n is the exit node e_p then - 9
for each call node c of p, with return site r, and each return edge <e_p,d2> → <r,d5> with label g do - 10
t ← Through(c, d1, d5) ⊓ (g ∘ f); if t = Through(c, d1, d5) then skip it, else Through(c, d1, d5) ← t - 11
for each call edge <c,d4> → <s_p,d1> with label h do - 12
s ← Summary(c, d4, d5) ⊓ (t ∘ h); if s ≠ Summary(c, d4, d5) then Summary(c, d4, d5) ← s - 13
for each d3 with Jump(c, d3, d4) ≠ λl.⊤ do PROPAGATE(r, d3, d5, s ∘ Jump(c, d3, d4)) - 14
else for each successor m of n and each edge <n,d2> → <m,d3> with label g do PROPAGATE(m, d1, d3, g ∘ f) - 15
val ← ⊤ everywhere; LOWER(s_main, 0, ⊥); for each parameter x of main do LOWER(s_main, x, seed of x, or ⊥) - 16
while WorkList2 is not empty do - 17
(n, d) ← remove the first item; v ← val(n, d) (n is in procedure p) - 18
if n = s_p then for each m in {s_p} ∪ calls(p) and each d2 with Jump(m, d, d2) ≠ λl.⊤ do LOWER(m, d2, Jump(m, d, d2)(v)) - 19
if n is a call node with callee q then for each call edge <n,d> → <s_q,d3> with label h do LOWER(s_q, d3, h(v)) - 20
for each other node n of p and each d2 do val(n, d2) ← ⊓ over d1 of Jump(n, d1, d2)(val(s_p, d1)) - 21
return val without the fact 0 PROPAGATE(n, d1, d2, f)- 22
j ← Jump(n, d1, d2) ⊓ f; if j ≠ Jump(n, d1, d2) then Jump(n, d1, d2) ← j and append (n, d1, d2) to WorkList unless it is there LOWER(n, d, v)- 23
w ← val(n, d) ⊓ v; if w ≠ val(n, d) then val(n, d) ← w and append (n, d) to WorkList2 unless it is there
Phase I has the shape of the IFDS tabulation. The differences are in L22 and in the exit case. A key is not done when it is first found. It goes back on the worklist each time its function goes down, and the finite height of the function space bounds how often this happens. At the exit (L9 to L13), collects the effect of the callee from the entry fact to the return fact at the site . Each call edge into then turns it into a summary function, and every path edge that already reaches the call is extended.
In Phase II, line L18 handles the start node of and the call nodes of only. These are the nodes where values must cross into other procedures, so they need the worklist. Every other node gets its value in L20, in one pass, from the values at the start of its procedure.
The implementation keeps, next to , an index of sources for L13 and an index of targets for L18. It also builds, for each call site, the inverse of its call edges for L11.
Example
add(a, b): t = a * 3
u = t + 1
ret u
main(n): x = 2
y = call add(x, n) c1
z = call add(n, x) c2
v = 4
w = call add(v, y) c3
ret w
The parameter n of main is . Phase I finds these jump functions in add: is line 3 0, is line 3 1, and at the exit is line 3 1. The fact only reaches itself. At the exit, L10 to L12 give one summary function per call site from the argument variable to the target: at , at and at , all line 3 1. Each site also gets , so there are six summary functions.
Back in main, L13 composes each summary function with the jump function at the call:
| target | composition | jump function from the start of main |
|---|---|---|
y |
line 3 1 after : const 2 |
: const 7 |
z |
line 3 1 after : identity |
: line 3 1 |
w |
line 3 1 after : const 4 |
: const 13 |
Phase II starts with and at the start of main. So y is 7, w is 13, and z is . At the start of add, a gets 2, and 4 from the three calls, so it is . The same is true of b. A context-insensitive analysis of the same supergraph sees only at the entry of add, so it reports u as and gets for y and w too. IDE gets the constants because the summary keeps the relation , not the value of a.
The run finds 53 keys, with 53 changes of jump functions, 6 summary functions and 20 changes of values in Phase II.
Correctness
The full proof is in the proof file. Its steps:
- The micro-functions. The forms are closed under meet and composition, every form is distributive and maps to , each function has one form, and a strictly falling chain has at most four elements.
- One path, many facts. For a path of the supergraph, is the meet of the compositions of micro-functions along the exploded paths that follow and end at , applied to the start values. So MVP is the meet over valid paths of the exploded graph.
- Phase I is sound. Every stored jump, through and summary function is a finite meet of the functions of real same-level paths. The proof is an induction on time, with distributivity to move compositions inside meets.
- Phase I is complete. Each key is taken off the worklist after its last change. This gives five local constraints at the end. The one at summary functions holds because L7 or L13 runs after both functions take their final values. An induction on the length of the path then shows that the jump function is at most the function of every same-level path.
- Phase II. The values at start nodes and call nodes are meets of real path values, and at the end they satisfy three local constraints. An induction on the number of calls that are still open gives the other direction. L20 then gives the right value at every other node.
- Termination and cost. Each function changes at most three times and each value at most twice. The cost counts the work at each kind of node, as for IFDS.
Proof: The IDE algorithm computes the meet over all valid paths for linear constant propagation in O(E D^3) timefull
Setting. is the supergraph of the program, as on the page. Every procedure has a start node and an exit node . A call site has a call node in some procedure, a return site and three edges: the call edge , the return edge and the call-to-return edge . The facts of form a finite set , and . is a new fact that is in no .
The values form the flat lattice , with for every integer and no order between two integers. The meet is . This is the meet convention of Kildall: the start value is and the result is the greatest solution. In the join convention of Cousot the order flips and the same result is the least solution.
A micro-function is one of the forms of the page: , , , with , and the point function that maps to and every other value to . All forms map to , the line maps to , and the constant maps to . Let be the set of these functions. Three facts about are used below, and the tests of the implementation check each of them by brute force on sample points.
- (F1) is closed under the pointwise meet and under composition, and
meet_fnandcomposecompute them exactly. For example, the meet of and agrees with both at when this is an integer, and gives at every other value. So it is the point function , or when is not an integer. The other cases are the same kind of algebra. - (F2) Every is distributive: . If one of is , this follows from . If , it is clear. Otherwise , and is , or when is the constant , in which case . So is also monotone.
- (F3) Each function has one form, and a strictly falling chain in has at most four elements: , then a constant or a line, then a point function, then . The meet of two different constants, lines or points is lower in this list, and nothing is between and the constants and lines.
By (F3), the meet of any set of functions of , even an infinite set, is the meet of a finite subset, so it is in and it is the pointwise meet. The same holds in , which has height 2.
Every edge of and every pair , have a micro-function . The function is when there is no exploded edge, and is the identity. An environment maps the facts of a procedure to , with . The edge has the environment transformer
For a path , . The start environment gives to , the seed value or to each parameter of main, and to the other variables of main. Valid and same-level paths are defined by matched brackets, as for IFDS. The meet over all valid paths is
The exploded supergraph has a node for every node and fact , and an edge labelled for every edge with . For a path of , is the composition of its labels, and the identity for the empty path. No label is , and a composition is only if one of its parts is. So .
We use the lines L1 to L23 of the pseudocode. is the jump function of , is the function of line L10, is the summary function, and is the value of Phase II. A missing function is , and a missing value is .
Lemma 1 (one path, many facts). For a path of from to , an environment and a fact ,
Proof. Induction on the length of . For the empty path the only is the empty path from , and both sides are . Let . By induction and by (F2),
where runs over the paths that follow and end at . An empty meet is , and every micro-function maps to , so empty meets do no harm. A term with is and drops out. The other terms are exactly the paths of .
The brackets of a path of are those of its shadow in . So Lemma 1 gives:
Corollary 2. is the meet of over all valid paths of from some to .
A path that starts at for a variable of main that is not a parameter has the value and drops out. So from now on is or a parameter of main.
Decomposition. Cut a valid path of from at its last call edge that is never closed. This gives , where is empty or ends with that call edge, and is a same-level path from some . We call an entry path to and the entry fact. Let
By Corollary 2, (F2) and the remark after (F3),
Phase I.
Lemma 3 (Phase I is sound). Every function that the algorithm stores as is a finite meet of over same-level paths from to . Every is a finite meet of , where is same-level from to some and is the label of a return edge of the site . Every is a finite meet of over same-level paths from to that start with the call edge of and end with its return edge. So, at every time, .
Proof. Induction on time. A new value is the meet of the old value and one new term, so it is enough to look at the terms. By (F2) and the pointwise meet, and , so a composition of finite meets of path functions is a finite meet of the functions of the joined paths.
- L2 and L6 give the identity to , the function of the empty path.
- L7 and L14 give for an exploded edge with label . The joined paths are same-level.
- L7 also gives , and L13 gives . A same-level path followed by a call, a same-level path in the callee and the matching return is same-level.
- L10 gives for a return edge of with label .
- L12 gives for a call edge with label .
A key exists once . Every key is put on the worklist when its function changes, unless it is on the worklist already, and L4 reads the current function when it takes the key off. Also, L4 takes the key off the worklist before the key can be added again. So every key that exists at the end was taken off at least once after its last change, and at that time L5 to L14 saw its final function. Write , , for the final functions. Since stored functions only go down, this gives the following constraints at the end.
- (C1) For every exploded edge with label that is intraprocedural or a call-to-return edge, when exists.
- (C2) If exists and the call edge of goes from to , then .
- (C3) If exists, then for every call site of and every return edge of with label .
- (C4) for every call edge with label . When L10 lowers , L11 and L12 meet with the new at once. When does not change, the old step still holds.
- (C5) whenever exists.
Proof of (C5). Let be the time when got its final value, the time of the last change of , and the time of the last removal of from the worklist. If , then L7 sees the final and the final at . If , then , so at the key already exists, is among the sources of , and L13 meets with for the final and .
Lemma 4 (Phase I is complete). Let be a valid path of from some , where is or a parameter of main, cut as in the decomposition, with from to . Then at the end . In particular the key exists.
Proof. Strong induction on the length of .
-
is empty. If is empty, L2 gives the identity to . Otherwise ends with a call edge from to , and the path without this edge is shorter. By induction, the key of for this shorter path exists, and (C2) gives .
-
The last edge of is intraprocedural or a call-to-return edge with label , from . By induction , where is without its last edge. By (C1) and (F2), .
-
The last edge of is a return edge. Then , where the call edge goes from to with label , is same-level from to , and the return edge has label . The path is shorter and has the entry fact , so . The path is shorter, so . By (C3), (C4) and (C5),
Each step uses that composition is monotone in both places, which holds by (F2).
Corollary 5. If some entry path reaches , then at the end, for every in and every . Otherwise no key exists.
Proof. The first part is Lemma 3 and Lemma 4, with the remark after (F3) for the infinite meet. For the second part, a key with the source is first made by L2 or L6, and both need an entry path to , by Lemma 3 applied to the key of the call node.
Phase II.
By Corollary 5, Phase II works with . Let be the set of start nodes and call nodes.
Lemma 6 (Phase II is sound). Every value that L23 stores as with is a finite meet of values of valid paths of to . So .
Proof. Induction on time. L15 uses the empty path. L18 applies , a finite meet of same-level path functions, to a finite meet of values of valid paths to . By (F2) the result is a finite meet of values of the joined paths, and a valid path followed by a same-level path is valid. L19 appends a call edge to a valid path, and the result is valid.
The Phase II worklist has the same property as the Phase I worklist: each pair is taken off after its last change. So at the end of L19 the values satisfy the following constraints.
- (V1) for and the parameters of main.
- (V2) for every and every key .
- (V3) for every call edge with label .
Lemma 7 (Phase II is complete on ). For every valid path of from some to with , .
Proof. Induction on the number of call edges of that are never closed. Cut , with from . First we show . If , then is empty and (V1) gives it. If , then , where the call edge goes from to with label . The path ends at a call node and has open calls, so by induction , and (V3) with (F2) gives the claim. Now is or a call node of , so by (V2), Lemma 4 and (F2),
Theorem (correctness). At the end, for every node and every fact . So the result of line L21 is the meet over all valid paths.
Proof. For , this is Lemma 6, Lemma 7 and Corollary 2. For another node of , L20 sets
Keys that do not exist give and drop out. We show that the right side is . Every entry path to is a valid path, so , and by and monotonicity the right side is at most . For the other direction, for gives . A same-level path to followed by one from to is same-level, so . With (F2), the right side is at least .
Lemma 8 (termination). The algorithm stops.
Proof. By (F3), each , and changes at most three times. There are finitely many keys, and each change puts at most one key on the worklist. So Phase I takes finitely many keys off the worklist, and each removal does a finite amount of work. In Phase II each value changes at most twice, from to an integer and from there to . So each pair enters the worklist at most twice. L20 is one pass over the keys.
Theorem (cost). Let be the number of nodes of , its number of edges and its number of call sites. Assume that the meet, the composition and the application of micro-functions take constant time, as they do with integers of bounded size, and use hash tables with constant expected cost per operation. Then the algorithm runs in time and uses space.
Proof. Write . A node has at most keys, and each is taken off at most three times, once per change.
- An ordinary node with successors gives at most calls of PROPAGATE per removal. In total , and over all nodes.
- A call node gives at most calls per removal at L6 and L7, since a pair has at most summary functions. In total per call site.
- An exit node gives at most meets at L10 per removal and per call site. In total per call site, since each call site calls one procedure. Each changes at most three times, there are of them per site, and each change runs L11 over at most facts: per site. Each changes at most three times, and each change runs L13 over at most sources: per site.
- Phase II takes each pair at a start node or a call node off at most twice. A start node of runs L18 over at most keys per removal, which is in total. A call node runs L19 over at most facts per removal, which is . L20 is one pass over at most keys.
A call site has three edges in , so , and the total is . The keys, their functions and the source and target indexes take space. The summary functions, the functions and the inverse call maps take per call site, and the values take .
Without the functions , the exit case would compose every key of with every call edge into and with every source of the call node. That is steps per call site in the worst case. The functions keep this case at .
Complexity
- Phase I. A node has at most keys, and each is taken off the worklist at most three times, once per change. So the counts of IFDS grow by a constant factor: for ordinary nodes and per call site for call nodes and exit nodes.
- Phase II. Each value at a start node or a call node changes at most twice. Each time a start value changes, L18 looks at the keys of that entry fact at the start node and at each call node of the procedure. L20 is one pass over the keys. This is .
- Total. time and space, with hash tables and micro-functions of constant size. Each meet, composition and application is here when integers fit in a word.
- Best case. Building the supergraph reads the program, .
- Few targets per fact. In linear constant propagation a statement sends a variable to itself and to at most one other variable. So the flow steps stay near the number of keys, far below the factor per edge.
The tables below are measured, not proved. The first has random modules of the toy IR with loops and recursion. f0 calls f1, each fi calls f(i+1) and one random procedure, and some arguments are constants.
| procedures | variables | keys | jump changes | summary changes | value changes | ms | ||||
|---|---|---|---|---|---|---|---|---|---|---|
| 4 | 4 | 133 | 155 | 15 | 1509 | 1688 | 16 | 122 | 634880 | 5.2 |
| 16 | 4 | 527 | 615 | 15 | 5756 | 6371 | 65 | 459 | 2519040 | 20.9 |
| 16 | 16 | 711 | 801 | 27 | 13567 | 14490 | 68 | 869 | 17583552 | 75.6 |
| 64 | 4 | 2061 | 2430 | 15 | 21926 | 24562 | 297 | 1773 | 9953280 | 248.4 |
| 64 | 16 | 2762 | 3127 | 27 | 50878 | 54734 | 304 | 3313 | 68643904 | 626.1 |
Most keys get one function and keep it. At most about one key in eight goes down after it is found. The second table is a worst case for the number of keys. A procedure g with parameters moves them around in a loop with linear steps, so every entry fact reaches every variable, and at the loop head the lines meet into points and then into bot. main calls g twice.
| keys | jump changes | summary changes | value changes | ms | |||||
|---|---|---|---|---|---|---|---|---|---|
| 4 | 14 | 17 | 7 | 246 | 458 | 18 | 19 | 8704 | 1.7 |
| 8 | 18 | 21 | 11 | 1058 | 2054 | 34 | 35 | 36288 | 6.9 |
| 16 | 26 | 29 | 19 | 5946 | 11774 | 66 | 67 | 232000 | 85.6 |
| 32 | 42 | 45 | 35 | 39530 | 78830 | 130 | 131 | 2099520 | 435.8 |
Here the keys come close to , and almost every key changes twice. The times were taken on a busy machine, so only the counts are reliable.
Properties
- Exact. For a distributive problem whose micro-functions are closed under meet and composition, the result is the meet over all valid paths, with and without recursion.
- Relations, not values. A summary function keeps how the result depends on the argument. One summary serves callers with different constant arguments.
- IFDS as a special case. With the two-point lattice and the identity on every edge, Phase I finds exactly the path edges of IFDS, and a fact holds where its value is not .
- Order free. The final jump functions and values do not depend on the order of the worklists.
- Only what is reached. Keys exist only for entry facts that some valid path reaches.
Variants and improvements
- Copy constant propagation. Without lines and points, only
const, identity andbotremain. This is cheaper and finds constants that are only copied across calls. - Affine relations. Linear constant propagation follows one variable at a time. Relations between several variables, such as , need weighted pushdown systems or other summary-based methods, which cost more.
- Solvers. Heros (Bodden 2012) runs IDE problems on Soot for Java. PhASAR (Schubert, Hermann and Bodden 2019) runs them on LLVM IR. Both build the supergraph on demand.
- Typestate. IDE is also used for typestate, with an object as the fact and the set of its possible states as the value.
- Other forms. Like IFDS, IDE can be read as a functional approach where each procedure summary is stored one pair of facts at a time. It is also a weighted form of CFL-reachability and of pushdown reachability.
When to use it
Use IDE when the result at a point is a value per variable, the transformers are distributive, and you want precision across calls. Linear constant propagation, copy constants and typestate fit. If the facts have no values, IFDS is simpler. If one result depends on two variables at once, as in x = a + b with both unknown, the transformer is not distributive in this sense, and IDE gives bot. Then use an intraprocedural method such as sparse conditional constant propagation inside procedures, or a non-distributive functional approach.
Pitfalls
- Forms must be unique. L22 stops when the new function equals the old one. If one function has two forms, the test can fail forever or miss a change. Keep every micro-function in one normal form, or compare the functions themselves.
- Integer overflow. The meet of two lines solves . With machine integers that wrap around, this equation can have several solutions, and the point form is wrong. Use exact integers, or treat a possible overflow as
bot. - Infinite height. Full linear functions over the integers are fine here because each chain has at most three steps. A richer function space without a height bound may not stop.
- Functions on . Every micro-function must map to , or a fact that no path reaches can give a value. This holds for
const ktoo, although it ignores every other input. - Branches are ignored. The result is the meet over valid paths of the graph, so a branch that is never taken still counts. A recursive procedure is analysed at every depth, even when a test stops the recursion early.
- Values at other nodes. Running the Phase II worklist over every node is correct but costs more. Only start nodes and call nodes need it.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ide-framework/. The authors are listed in prov/60PTYF.jsonl.
"""The IDE algorithm of Sagiv, Reps and Horwitz, with linear constant
propagation on the toy IR as the instance.
A module is a dict from procedure name to toyir.Program, as for IFDS. The
supergraph has a node (proc, label, i) for instruction i of a block, a node
for each terminator (i = len(instrs)) and an exit node (proc, EXIT, 0) per
procedure. The facts of a procedure are its variables and RET; ZERO is the
extra fact. Every exploded edge carries a micro-function on values.
Values: TOP (no value seen), an int, or BOT (not a constant).
Micro-functions, in a form that is unique for each function:
("top",) l -> TOP for every l, the function of no path
("bot",) l -> BOT
("const", k) l -> k
("line", a, b) l -> a*l + b for an int l, BOT -> BOT (a != 0)
("point", l0, v) l0 -> v, any other l -> BOT
Every function maps TOP to TOP. A value that some path reaches is never
TOP, so only the behaviour on ints and BOT matters, and there the forms
above are closed under meet and composition, with no loss.
"""
from collections import Counter, deque
import toyir
ZERO = "0"
RET = "RET"
EXIT = "$exit"
TOP = "top"
BOT = "bot"
TOPF = ("top",)
BOTF = ("bot",)
ID = ("line", 1, 0)
# ------------------------------------------------------------------ values
def meet_val(a, b):
if a == TOP:
return b
if b == TOP or a == b:
return a
return BOT
def apply(f, l):
"""The value of the micro-function f at l."""
if l == TOP or f[0] == "top":
return TOP
k = f[0]
if k == "bot":
return BOT
if k == "const":
return f[1]
if l == BOT:
return BOT
if k == "line":
return f[1] * l + f[2]
return f[2] if l == f[1] else BOT
def _point_or_bot(num, den, value):
"""The point function at l0 = num / den with the given value, or BOT
when l0 is not an int (or the value is BOT)."""
if value == BOT or num % den != 0:
return BOTF
return ("point", num // den, value)
def meet_fn(f, g):
"""The pointwise meet of two micro-functions."""
if f[0] == "top":
return g
if g[0] == "top" or f == g:
return f
if f[0] == "bot" or g[0] == "bot":
return BOTF
if f[0] > g[0]:
f, g = g, f
# Now f[0] <= g[0] in the order const < line < point.
if f[0] == "const" and g[0] == "const":
return BOTF
if f[0] == "const" and g[0] == "line":
k, a, b = f[1], g[1], g[2]
return _point_or_bot(k - b, a, k)
if f[0] == "const": # g is a point
return g if g[2] == f[1] else BOTF
if f[0] == "line" and g[0] == "line":
a1, b1, a2, b2 = f[1], f[2], g[1], g[2]
if a1 == a2:
return BOTF
num, den = b2 - b1, a1 - a2
if num % den != 0:
return BOTF
l0 = num // den
return ("point", l0, a1 * l0 + b1)
if f[0] == "line": # g is a point
return g if f[1] * g[1] + f[2] == g[2] else BOTF
return BOTF # two different points
def compose(g, f):
"""The micro-function g after f."""
if f[0] == "top" or g[0] == "top":
return TOPF
if g[0] == "bot" or g[0] == "const":
return g
if f[0] == "bot":
return BOTF
if f[0] == "const":
v = apply(g, f[1])
return BOTF if v == BOT else ("const", v)
if f[0] == "point":
v = apply(g, f[2])
return BOTF if v == BOT else ("point", f[1], v)
a1, b1 = f[1], f[2] # f is a line
if g[0] == "line":
return ("line", g[1] * a1, g[1] * b1 + g[2])
return _point_or_bot(g[1] - b1, a1, g[2]) # g is a point
# ------------------------------------------------------------- supergraph
def _linear(op, a, b):
"""The micro-function of x = a op b, as (source, function): source is a
variable, or ZERO for a function that ignores its input."""
if isinstance(a, int) and isinstance(b, int):
try:
return ZERO, ("const", toyir._binop(op, a, b))
except toyir._Trap:
return ZERO, BOTF
if isinstance(a, str) and isinstance(b, str):
return ZERO, BOTF
if op == "+":
return (a, ("line", 1, b)) if isinstance(a, str) else (b, ("line", 1, a))
if op == "-":
return (a, ("line", 1, -b)) if isinstance(a, str) else (b, ("line", -1, a))
if op == "*":
var, k = (a, b) if isinstance(a, str) else (b, a)
return (ZERO, ("const", 0)) if k == 0 else (var, ("line", k, 0))
return ZERO, BOTF
class Supergraph:
"""The supergraph of a module and the exploded edges of linear constant
propagation. Each flow method returns a list of (fact, micro-function)."""
def __init__(self, module, main=None):
self.module = module
self.main = main if main is not None else next(iter(module))
self.facts = {}
self.start = {}
self.exit = {}
self.succ = {}
self.callee = {}
self.ret_site = {}
self.callers = {p: [] for p in module}
self.calls_in = {p: [] for p in module}
self.nodes = []
self.proc = {}
for p, prog in module.items():
names = set(prog.params)
for label, blk in prog.blocks.items():
for i, ins in enumerate(blk.instrs):
if ins[0] not in ("const", "copy", "op", "call"):
raise ValueError("unsupported instruction: %r" % (ins,))
names.add(ins[1])
names.update(toyir.uses(ins))
node = (p, label, i)
self.nodes.append(node)
if ins[0] == "call":
q = ins[2]
if q not in module:
raise ValueError("unknown procedure %r" % q)
if len(ins[3]) != len(module[q].params):
raise ValueError("wrong number of arguments for %r" % q)
self.callee[node] = q
self.ret_site[node] = (p, label, i + 1)
self.callers[q].append(node)
self.calls_in[p].append(node)
else:
self.succ[node] = [(p, label, i + 1)]
names.update(toyir.term_uses(blk.term))
tnode = (p, label, len(blk.instrs))
self.nodes.append(tnode)
if blk.term[0] == "ret":
self.succ[tnode] = [(p, EXIT, 0)]
else:
self.succ[tnode] = [(p, s, 0) for s in toyir.succs(prog, label)]
if RET in names or ZERO in names:
raise ValueError("reserved name used as a variable")
self.facts[p] = sorted(names) + [RET]
self.start[p] = (p, prog.entry, 0)
self.exit[p] = (p, EXIT, 0)
self.nodes.append(self.exit[p])
self.succ[self.exit[p]] = []
for n in self.nodes:
self.proc[n] = n[0]
def num_edges(self):
return sum(len(v) for v in self.succ.values()) + 3 * len(self.callee)
def instr(self, n):
p, label, i = n
blk = self.module[p].blocks[label]
return blk.instrs[i] if i < len(blk.instrs) else blk.term
def normal_flow(self, n, m, d):
ins = self.instr(n)
k = ins[0]
if k == "jump" or k == "br":
return [(d, ID)]
if k == "ret":
a = ins[1]
out = [(d, ID)]
if d == ZERO and isinstance(a, int):
out.append((RET, ("const", a)))
elif d == a:
out.append((RET, ID))
return out
x = ins[1]
if k == "const":
src, fn = ZERO, ("const", ins[2])
elif k == "copy":
src, fn = ins[2], ID
else:
src, fn = _linear(ins[2], ins[3], ins[4])
out = []
if d != x:
out.append((d, ID))
if d == src:
out.append((x, fn))
return out
def call_flow(self, c, d):
ins = self.instr(c)
params = self.module[ins[2]].params
if d == ZERO:
out = [(ZERO, ID)]
out += [(params[j], ("const", a)) for j, a in enumerate(ins[3]) if isinstance(a, int)]
return out
return [(params[j], ID) for j, a in enumerate(ins[3]) if a == d]
def c2r_flow(self, c, d):
return [] if d == self.instr(c)[1] else [(d, ID)]
def ret_flow(self, c, d):
if d == ZERO:
return [(ZERO, ID)]
return [(self.instr(c)[1], ID)] if d == RET else []
# -------------------------------------------------------------- the solver
def ide(sg, seeds=None):
"""Run IDE. seeds maps each parameter of main to its value at the start
(an int or BOT); a missing parameter is BOT. Returns (V, stats), where
V[n] maps each variable with a value other than TOP to that value."""
seeds = dict(seeds or {})
main = sg.main
stats = Counter()
jump = {} # (n, d1, d2) -> the jump function from <s_p, d1> to <n, d2>
sources = {} # (n, d2) -> the d1 with a jump function to <n, d2>
targets = {} # (n, d1) -> the d2 with a jump function from <s_p, d1> to <n, d2>
summary = {} # (c, d4) -> {d5: the summary function from <c, d4> to <r, d5>}
through = {} # (c, d1, d5) -> meet of ret o jump(e_q, d1, d2) over d2
inv_call = {} # c -> d1 -> [(d4, h)] for the call edges <c, d4> -> <s_q, d1>
for c in sg.callee:
inv = {}
for d4 in sg.facts[sg.proc[c]] + [ZERO]:
for d1, h in sg.call_flow(c, d4):
inv.setdefault(d1, []).append((d4, h))
inv_call[c] = inv
work = deque()
queued = set()
def propagate(n, d1, d2, f):
key = (n, d1, d2)
old = jump.get(key, TOPF)
new = meet_fn(old, f)
stats["meets"] += 1
if new != old: # @line L22
if old == TOPF:
stats["path_edges"] += 1
sources.setdefault((n, d2), set()).add(d1)
targets.setdefault((n, d1), set()).add(d2)
jump[key] = new
stats["jump_changes"] += 1
if key not in queued:
queued.add(key)
work.append(key)
# Phase I: jump functions and summary functions.
s_main = sg.start[main] # @line L1
for d in [ZERO] + list(sg.module[main].params): # @line L2
propagate(s_main, d, d, ID)
while work: # @line L3
key = work.popleft() # @line L4
queued.discard(key)
n, d1, d2 = key
f = jump[key]
stats["pops"] += 1
p = sg.proc[n]
if n in sg.callee: # @line L5
c, q, r = n, sg.callee[n], sg.ret_site[n]
for d3, _h in sg.call_flow(c, d2): # @line L6
propagate(sg.start[q], d3, d3, ID)
for d3, g in sg.c2r_flow(c, d2): # @line L7
propagate(r, d1, d3, compose(g, f))
for d3, s in list(summary.get((c, d2), {}).items()):
propagate(r, d1, d3, compose(s, f))
elif n == sg.exit[p]: # @line L8
for c in sg.callers[p]: # @line L9
r = sg.ret_site[c]
for d5, g in sg.ret_flow(c, d2):
tkey = (c, d1, d5)
told = through.get(tkey, TOPF)
t = meet_fn(told, compose(g, f)) # @line L10
if t == told:
continue
through[tkey] = t
for d4, h in inv_call[c].get(d1, ()): # @line L11
sums = summary.setdefault((c, d4), {})
sold = sums.get(d5, TOPF)
s = meet_fn(sold, compose(t, h)) # @line L12
if s == sold:
continue
sums[d5] = s
stats["summary_changes"] += 1
for d3 in list(sources.get((c, d4), ())): # @line L13
propagate(r, d3, d5, compose(s, jump[(c, d3, d4)]))
else:
for m in sg.succ[n]: # @line L14
for d3, g in sg.normal_flow(n, m, d2):
propagate(m, d1, d3, compose(g, f))
# Phase II: values.
val = {}
work2 = deque()
in_work2 = set()
def lower(n, d, v):
old = val.get((n, d), TOP)
new = meet_val(old, v)
if new != old: # @line L23
val[(n, d)] = new
stats["value_changes"] += 1
if (n, d) not in in_work2:
in_work2.add((n, d))
work2.append((n, d))
lower(s_main, ZERO, BOT) # @line L15
for x in sg.module[main].params:
lower(s_main, x, seeds.get(x, BOT))
while work2: # @line L16
n, d = work2.popleft() # @line L17
in_work2.discard((n, d))
v = val[(n, d)]
p = sg.proc[n]
if n == sg.start[p]: # @line L18
for m in [n] + sg.calls_in[p]:
for d2 in list(targets.get((m, d), ())):
lower(m, d2, apply(jump[(m, d, d2)], v))
if n in sg.callee: # @line L19
q = sg.callee[n]
for d3, h in sg.call_flow(n, d):
lower(sg.start[q], d3, apply(h, v))
for (n, d1, d2), f in jump.items(): # @line L20
p = sg.proc[n]
if n == sg.start[p] or n in sg.callee:
continue
v = val.get((sg.start[p], d1), TOP)
if v != TOP:
new = meet_val(val.get((n, d2), TOP), apply(f, v))
if new != TOP:
val[(n, d2)] = new
V = {n: {} for n in sg.nodes} # @line L21
for (n, d), v in val.items():
if d != ZERO and v != TOP:
V[n][d] = v
return V, stats
def ide_framework(module, main=None, seeds=None):
"""Convenience wrapper: the constants at every node of the module."""
sg = Supergraph(module, main)
V, _ = ide(sg, seeds)
return V
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.
A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:
("const", x, k) x = k
("copy", x, a) x = y
("op", x, op, a, b) x = a op b
("phi", x, {pred: a}) x = phi [pred: a, ...]
("addr", p, x) p = &x
("load", x, p) x = *p
("store", p, a) *p = a
("alloc", p) p = alloc
("call", x, f, args) x = call f(a, b) (args is a list)
Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""
from dataclasses import dataclass, field
import re
OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")
@dataclass
class Block:
instrs: list = field(default_factory=list)
term: tuple = ("ret", 0)
@dataclass
class Program:
params: list
blocks: dict
@property
def entry(self):
return next(iter(self.blocks))
class UndefinedName(Exception):
"""A name was read before any definition."""
# ---------------------------------------------------------------- text form
_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"
def _operand(tok):
if re.fullmatch(_INT, tok):
return int(tok)
if re.fullmatch(_NAME, tok):
return tok
raise ValueError("bad operand: %r" % tok)
def _name(tok):
if not re.fullmatch(_NAME, tok):
raise ValueError("bad name: %r" % tok)
return tok
def _parse_instr(line):
toks = line.split()
if toks[0] == "jump" and len(toks) == 2:
return "term", ("jump", _name(toks[1]))
if toks[0] == "br" and len(toks) == 4:
return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
if toks[0] == "ret" and len(toks) == 2:
return "term", ("ret", _operand(toks[1]))
lhs, eq, rhs = line.partition("=")
if not eq:
raise ValueError("bad line: %r" % line)
lhs, rhs = lhs.strip(), rhs.strip()
if lhs.startswith("*"):
return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
x = _name(lhs)
if rhs.startswith("phi"):
body = rhs[3:].strip()
if not (body.startswith("[") and body.endswith("]")):
raise ValueError("bad phi: %r" % line)
args = {}
inner = body[1:-1].strip()
if inner:
for part in inner.split(","):
pred, colon, a = part.partition(":")
if not colon:
raise ValueError("bad phi: %r" % line)
args[_name(pred.strip())] = _operand(a.strip())
return "instr", ("phi", x, args)
if rhs.startswith("call "):
m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
if not m:
raise ValueError("bad call: %r" % line)
inner = m.group(2).strip()
args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
return "instr", ("call", x, m.group(1), args)
if rhs == "alloc":
return "instr", ("alloc", x)
if rhs.startswith("&"):
return "instr", ("addr", x, _name(rhs[1:].strip()))
if rhs.startswith("*"):
return "instr", ("load", x, _name(rhs[1:].strip()))
parts = rhs.split()
if len(parts) == 1:
a = _operand(parts[0])
if isinstance(a, int):
return "instr", ("const", x, a)
return "instr", ("copy", x, a)
if len(parts) == 3 and parts[1] in OPS:
return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
raise ValueError("bad instruction: %r" % line)
def parse(text):
"""Parse the text form. A line "# params: a, b" gives the parameters;
without it, the parameters are the names that are read and never
defined, in the order of their first use."""
params = None
blocks = {}
cur = None
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
if line.startswith("#"):
m = re.fullmatch(r"#\s*params:(.*)", line)
if m:
inner = m.group(1).strip()
params = [_name(p.strip()) for p in inner.split(",")] if inner else []
continue
if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
label = line[:-1]
if label in blocks:
raise ValueError("duplicate label: %r" % label)
cur = label
blocks[label] = Block([], None)
continue
if cur is None:
raise ValueError("instruction outside a block: %r" % line)
if blocks[cur].term is not None:
raise ValueError("instruction after the terminator in %r" % cur)
kind, item = _parse_instr(line)
if kind == "term":
blocks[cur].term = item
else:
blocks[cur].instrs.append(item)
for label, b in blocks.items():
if b.term is None:
raise ValueError("block %r has no terminator" % label)
if not blocks:
raise ValueError("empty program")
prog = Program([], blocks)
if params is None:
params = _free_names(prog)
prog.params = params
return prog
def _free_names(prog):
defined = set()
for b in prog.blocks.values():
for ins in b.instrs:
d = defs(ins)
if d is not None:
defined.add(d)
out = []
for b in prog.blocks.values():
for ins in b.instrs:
for a in uses(ins):
if a not in defined and a not in out:
out.append(a)
for a in term_uses(b.term):
if a not in defined and a not in out:
out.append(a)
return out
def _show_instr(ins):
k = ins[0]
if k == "const":
return "%s = %d" % (ins[1], ins[2])
if k == "copy":
return "%s = %s" % (ins[1], ins[2])
if k == "op":
return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
if k == "phi":
return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
if k == "addr":
return "%s = &%s" % (ins[1], ins[2])
if k == "load":
return "%s = *%s" % (ins[1], ins[2])
if k == "store":
return "*%s = %s" % (ins[1], ins[2])
if k == "alloc":
return "%s = alloc" % ins[1]
if k == "call":
return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
raise ValueError("bad instruction: %r" % (ins,))
def _show_term(t):
if t[0] == "jump":
return "jump %s" % t[1]
if t[0] == "br":
return "br %s %s %s" % (t[1], t[2], t[3])
if t[0] == "ret":
return "ret %s" % (t[1],)
raise ValueError("bad terminator: %r" % (t,))
def show(prog):
lines = ["# params: " + ", ".join(prog.params)]
for label, b in prog.blocks.items():
lines.append(label + ":")
for ins in b.instrs:
lines.append(" " + _show_instr(ins))
lines.append(" " + _show_term(b.term))
return "\n".join(lines) + "\n"
# ---------------------------------------------------------- names and graph
def defs(ins):
"""The name an instruction defines, or None for a store."""
return None if ins[0] == "store" else ins[1]
def uses(ins):
"""The names an instruction reads, in order (phi operands included)."""
k = ins[0]
if k == "const" or k == "alloc" or k == "addr":
ops = []
elif k == "copy":
ops = [ins[2]]
elif k == "op":
ops = [ins[3], ins[4]]
elif k == "phi":
ops = list(ins[2].values())
elif k == "load":
ops = [ins[2]]
elif k == "store":
ops = [ins[1], ins[2]]
elif k == "call":
ops = list(ins[3])
else:
raise ValueError("bad instruction: %r" % (ins,))
return [a for a in ops if isinstance(a, str)]
def term_uses(t):
if t[0] == "br" or t[0] == "ret":
return [t[1]] if isinstance(t[1], str) else []
return []
def succs(prog, label):
"""Successor labels of a block, without repeats, in terminator order."""
t = prog.blocks[label].term
if t[0] == "jump":
return [t[1]]
if t[0] == "br":
return [t[2]] if t[2] == t[3] else [t[2], t[3]]
return []
def edges(prog):
return [(a, b) for a in prog.blocks for b in succs(prog, a)]
def preds(prog):
"""Dict from label to the list of predecessor labels, in block order."""
out = {label: [] for label in prog.blocks}
for a, b in edges(prog):
out[b].append(a)
return out
def is_acyclic(prog):
color = {label: 0 for label in prog.blocks}
for root in prog.blocks:
if color[root]:
continue
color[root] = 1
stack = [(root, iter(succs(prog, root)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
color[v] = 2
stack.pop()
elif color[w] == 1:
return False
elif color[w] == 0:
color[w] = 1
stack.append((w, iter(succs(prog, w))))
return True
def paths(prog):
"""Every path from the entry to a ret block, as a list of labels.
The CFG must be acyclic."""
if not is_acyclic(prog):
raise ValueError("paths needs an acyclic CFG")
out = []
def walk(path):
last = path[-1]
s = succs(prog, last)
if not s:
out.append(list(path))
for w in s:
path.append(w)
walk(path)
path.pop()
walk([prog.entry])
return out
# ------------------------------------------------------------------ running
class _Trap(Exception):
pass
class _Fuel(Exception):
pass
def _binop(op, a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("arithmetic on a pointer")
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/" or op == "%":
if b == 0:
raise _Trap()
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if op == "/" else a - b * q
if op == "&":
return a & b
if op == "|":
return a | b
if op == "^":
return a ^ b
if op == "<<" or op == ">>":
if b < 0 or b > 63:
raise _Trap()
return a << b if op == "<<" else a >> b
if op == "<":
return int(a < b)
if op == "<=":
return int(a <= b)
if op == "==":
return int(a == b)
if op == "!=":
return int(a != b)
raise ValueError("bad operator: %r" % op)
class _Frame:
"""One activation: its program, its variables and its position."""
def __init__(self, prog, args, fid):
if len(args) != len(prog.params):
raise ValueError("expected %d arguments" % len(prog.params))
self.prog = prog
self.env = dict(zip(prog.params, args))
self.fid = fid
self.label = prog.entry
self.prev = None
self.pc = 0 # 0 means: the phis of the block have not run yet
self.dest = None # the name that receives the value of a pending call
def val(self, a):
if isinstance(a, int):
return a
if a not in self.env:
raise UndefinedName(a)
return self.env[a]
def _run(prog, args, fuel, funcs):
"""Run with an explicit stack of frames, so deep recursion in the toy
program does not use Python recursion."""
heap = {}
envs = {}
stack = []
fr = _Frame(prog, args, 0)
envs[0] = fr.env
nframes = 1
def tick():
nonlocal fuel
if fuel <= 0:
raise _Fuel()
fuel -= 1
while True:
block = fr.prog.blocks[fr.label]
instrs = block.instrs
if fr.pc == 0:
# Phis at the top of the block read all operands first, then assign.
incoming = []
i = 0
while i < len(instrs) and instrs[i][0] == "phi":
tick()
ins = instrs[i]
if fr.prev not in ins[2]:
raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
incoming.append((ins[1], fr.val(ins[2][fr.prev])))
i += 1
for x, v in incoming:
fr.env[x] = v
fr.pc = i if i > 0 else -1
start = fr.pc if fr.pc > 0 else 0
called = False
env = fr.env
for j in range(start, len(instrs)):
ins = instrs[j]
tick()
k = ins[0]
if k == "const":
env[ins[1]] = ins[2]
elif k == "copy":
env[ins[1]] = fr.val(ins[2])
elif k == "op":
env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
elif k == "addr":
env[ins[1]] = ("var", fr.fid, ins[2])
elif k == "alloc":
cell = ("heap", len(heap))
heap[cell] = None
env[ins[1]] = cell
elif k == "load":
p = fr.val(ins[2])
if p[0] == "var":
if p[2] not in envs[p[1]]:
raise UndefinedName(p[2])
env[ins[1]] = envs[p[1]][p[2]]
else:
if heap[p] is None:
raise UndefinedName(repr(p))
env[ins[1]] = heap[p]
elif k == "store":
p = fr.val(ins[1])
if p[0] == "var":
envs[p[1]][p[2]] = fr.val(ins[2])
else:
heap[p] = fr.val(ins[2])
elif k == "call":
if funcs is None or ins[2] not in funcs:
raise ValueError("unknown function %r" % ins[2])
vals = [fr.val(a) for a in ins[3]]
fr.pc = j + 1
fr.dest = ins[1]
stack.append(fr)
fr = _Frame(funcs[ins[2]], vals, nframes)
envs[nframes] = fr.env
nframes += 1
called = True
break
elif k == "phi":
raise ValueError("phi after a non-phi instruction")
else:
raise ValueError("bad instruction: %r" % (ins,))
if called:
continue
tick()
t = block.term
if t[0] == "jump" or t[0] == "br":
if t[0] == "jump":
nxt = t[1]
else:
nxt = t[2] if fr.val(t[1]) != 0 else t[3]
fr.prev, fr.label, fr.pc = fr.label, nxt, 0
continue
v = fr.val(t[1])
if not stack:
return ("ret", v), fuel
fr = stack.pop()
fr.env[fr.dest] = v
def run(prog, args, fuel=10000, funcs=None):
"""Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
Each instruction, phi and terminator uses one unit of fuel. funcs is an
optional dict from function name to Program, used by call; deep
recursion in the toy program is fine, because the frames are kept on an
explicit stack."""
try:
out, _ = _run(prog, list(args), fuel, funcs)
return out
except _Trap:
return ("trap",)
except _Fuel:
return ("fuel",)
# ------------------------------------------------------------ random programs
_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")
def random_program(rng, nvars, nblocks, acyclic):
"""A random program with blocks B0 .. B(nblocks-1) and variables
x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
others, so no run reads an undefined name. A division by a variable can
trap. Every block is reachable from
B0 and B0 has no predecessor. With acyclic=False, each loop has its own
counter c that is set to 0 in B0 and never reset, and the back edge is
taken only while c < m and c < 4, where m is the first parameter. So the
whole run takes each back edge at most 3 times."""
nvars = max(nvars, 1)
nblocks = max(nblocks, 1)
xs = ["x%d" % i for i in range(nvars)]
params = xs[:2]
labels = ["B%d" % i for i in range(nblocks)]
def operand():
if rng.random() < 0.25:
return rng.randint(-3, 9)
return rng.choice(xs)
def instr():
x = rng.choice(xs)
r = rng.random()
if r < 0.15:
return ("const", x, rng.randint(-5, 9))
if r < 0.25:
return ("copy", x, rng.choice(xs))
if r < 0.3:
# A division by a variable may trap.
return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
if r < 0.4:
op = rng.choice(_CONST_RIGHT)
k = rng.randint(1, 5)
return ("op", x, op, rng.choice(xs), k)
return ("op", x, rng.choice(_SAFE), operand(), operand())
blocks = {}
has_pred = [False] * nblocks
has_pred[0] = True
for i in range(nblocks):
instrs = [instr() for _ in range(rng.randint(1, 3))]
if i == 0:
instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
if i == nblocks - 1:
term = ("ret", rng.choice(xs))
elif has_pred[i + 1] and rng.random() < 0.2:
term = ("ret", rng.choice(xs))
else:
first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
if rng.random() < 0.5:
term = ("jump", labels[first])
has_pred[first] = True
else:
second = rng.randrange(i + 1, nblocks)
if second == first:
term = ("jump", labels[first])
else:
term = ("br", rng.choice(xs), labels[first], labels[second])
has_pred[second] = True
has_pred[first] = True
blocks[labels[i]] = Block(instrs, term)
if not acyclic and nblocks > 1:
nloops = rng.randint(1, max(1, nblocks // 3))
for k in range(nloops):
latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
if not latches:
break
t = rng.choice(latches)
h = labels[rng.randint(1, labels.index(t))]
c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
out = blocks[t].term[1]
blocks[t].instrs += [
("op", c, "+", c, 1),
("op", w1, "<", c, m),
("op", w2, "<", c, 4),
("op", w, "&", w1, w2),
]
blocks[t].term = ("br", w, h, out)
return Program(list(params), blocks)
test_ide_framework.py 431 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ide-framework/. The authors are listed in prov/60PTYF.jsonl.
import random
import toyir
from toyir import parse, random_program
from ide_framework import (
BOT,
BOTF,
EXIT,
ID,
RET,
TOP,
TOPF,
ZERO,
Supergraph,
apply,
compose,
ide,
ide_framework,
meet_fn,
meet_val,
)
# The example of the page: add is linear in its first parameter, so each
# call with a constant first argument gives a constant, even though the
# first parameter is not a constant at the entry of add.
ADD = """
# params: a, b
B0:
t = a * 3
u = t + 1
ret u
"""
MAIN = """
# params: n
B0:
x = 2
y = call add(x, n)
z = call add(n, x)
v = 4
w = call add(v, y)
ret w
"""
def add_module():
return {"main": parse(MAIN), "add": parse(ADD)}
def leq(a, b):
"""a is below or equal to b in the value lattice."""
return a == BOT or b == TOP or a == b
# ---------------------------------------------------- micro-function algebra
DOMAIN = list(range(-40, 41)) + [BOT]
def table(f):
return [apply(f, l) for l in DOMAIN]
def random_fn(rng):
r = rng.random()
if r < 0.1:
return BOTF
if r < 0.3:
return ("const", rng.randint(-10, 10))
if r < 0.8:
return ("line", rng.choice([-3, -2, -1, 1, 2, 3]), rng.randint(-6, 6))
return ("point", rng.randint(-5, 5), rng.randint(-10, 10))
def canonical(f):
if f[0] == "line":
return f[1] != 0
if f[0] == "point":
return f[2] != BOT and f[2] != TOP
return f[0] in ("top", "bot", "const")
def test_micro_functions() -> None:
rng = random.Random(6001)
for _ in range(800):
f, g = random_fn(rng), random_fn(rng)
m = meet_fn(f, g)
assert canonical(m)
assert table(m) == [meet_val(x, y) for x, y in zip(table(f), table(g))]
assert meet_fn(g, f) == m
c = compose(g, f)
assert canonical(c)
assert table(c) == [apply(g, apply(f, l)) for l in DOMAIN]
# Distributive over the meet of two inputs.
l1, l2 = rng.choice(DOMAIN), rng.choice(DOMAIN)
assert apply(f, meet_val(l1, l2)) == meet_val(apply(f, l1), apply(f, l2))
# The same table means the same tuple.
if table(f) == table(g):
assert f == g
for f in [BOTF, ("const", 3), ("line", 2, 1), ("point", 1, 4)]:
assert meet_fn(TOPF, f) == f and compose(f, TOPF) == TOPF and compose(TOPF, f) == TOPF
assert compose(ID, f) == f and compose(f, ID) == f
assert apply(f, TOP) == TOP
# A chain of meets goes down at most three times from TOPF.
for _ in range(400):
f, steps = TOPF, 0
for _ in range(8):
g = meet_fn(f, random_fn(rng))
if g != f:
steps += 1
f = g
assert steps <= 3
# ------------------------------------------------------------ brute force
def step(env, flow):
"""Push an environment (fact -> value, TOP left out) over one edge."""
out = {}
for d, v in env.items():
for d2, g in flow(d):
out[d2] = meet_val(out.get(d2, TOP), apply(g, v))
return out
def start_env(sg, seeds):
env = {ZERO: BOT}
for x in sg.module[sg.main].params:
env[x] = (seeds or {}).get(x, BOT)
return env
def mvp_by_paths(sg, seeds=None, cap=20000, max_depth=None):
"""The meet over all valid paths, by walking each valid path from the
start of main with its own environment. At a call node the path either
enters the callee or takes the call-to-return edge; at an exit it goes
back to the call on top of its stack. Returns None after cap steps."""
M = {n: {} for n in sg.nodes}
todo = [(sg.start[sg.main], start_env(sg, seeds), ())]
steps = 0
while todo:
n, env, stack = todo.pop()
steps += 1
if steps > cap:
return None
for d, v in env.items():
M[n][d] = meet_val(M[n].get(d, TOP), v)
if n in sg.callee:
if max_depth is None or len(stack) < max_depth:
todo.append((sg.start[sg.callee[n]], step(env, lambda d: sg.call_flow(n, d)), stack + (n,)))
todo.append((sg.ret_site[n], step(env, lambda d: sg.c2r_flow(n, d)), stack))
elif n[1] == EXIT:
if stack:
c = stack[-1]
todo.append((sg.ret_site[c], step(env, lambda d: sg.ret_flow(c, d)), stack[:-1]))
else:
for m in sg.succ[n]:
todo.append((m, step(env, lambda d: sg.normal_flow(n, m, d)), stack))
for n in M:
M[n].pop(ZERO, None)
return M
def mfp_supergraph(sg, seeds=None):
"""Context-insensitive constant propagation on the supergraph: every
exit flows back to every caller."""
IN = {n: {} for n in sg.nodes}
work, queued = [], set()
def add(m, env):
changed = False
for d, v in env.items():
new = meet_val(IN[m].get(d, TOP), v)
if new != IN[m].get(d, TOP):
IN[m][d] = new
changed = True
if changed and m not in queued:
queued.add(m)
work.append(m)
add(sg.start[sg.main], start_env(sg, seeds))
while work:
n = work.pop()
queued.discard(n)
env = IN[n]
if n in sg.callee:
q = sg.callee[n]
add(sg.start[q], step(env, lambda d: sg.call_flow(n, d)))
add(sg.ret_site[n], step(env, lambda d: sg.c2r_flow(n, d)))
add(sg.ret_site[n], step(IN[sg.exit[q]], lambda d: sg.ret_flow(n, d)))
elif n[1] == EXIT:
for c in sg.callers[n[0]]:
if ZERO in IN[c]:
add(sg.ret_site[c], step(env, lambda d: sg.ret_flow(c, d)))
else:
for m in sg.succ[n]:
add(m, step(env, lambda d: sg.normal_flow(n, m, d)))
for n in IN:
IN[n].pop(ZERO, None)
return IN
def run_recorded(module, main, args, fuel=3000):
"""Run the module and record the variables before each node. Returns
the outcome, in the form of toyir.run, and a list of (node, env)."""
seen = []
stack = []
p = main
prog = module[p]
env = dict(zip(prog.params, args))
label, pc, dest = prog.entry, 0, None
def tick():
nonlocal fuel
if fuel <= 0:
raise toyir._Fuel()
fuel -= 1
def val(a):
return a if isinstance(a, int) else env[a]
try:
while True:
blk = module[p].blocks[label]
called = False
while pc < len(blk.instrs):
ins = blk.instrs[pc]
seen.append(((p, label, pc), dict(env)))
tick()
k = ins[0]
if k == "const":
env[ins[1]] = ins[2]
elif k == "copy":
env[ins[1]] = val(ins[2])
elif k == "op":
env[ins[1]] = toyir._binop(ins[2], val(ins[3]), val(ins[4]))
else:
q = module[ins[2]]
stack.append((p, label, pc + 1, ins[1], env))
env = dict(zip(q.params, [val(a) for a in ins[3]]))
p, label, pc = ins[2], q.entry, 0
called = True
break
pc += 1
if called:
continue
seen.append(((p, label, len(blk.instrs)), dict(env)))
tick()
t = blk.term
if t[0] == "jump":
label, pc = t[1], 0
continue
if t[0] == "br":
label, pc = (t[2] if val(t[1]) != 0 else t[3]), 0
continue
v = val(t[1])
seen.append(((p, EXIT, 0), dict(env, **{RET: v})))
if not stack:
return ("ret", v), seen
p, label, pc, dest, env = stack.pop()
env[dest] = v
except toyir._Trap:
return ("trap",), seen
except toyir._Fuel:
return ("fuel",), seen
# ---------------------------------------------------------- random modules
def random_module(rng, recursive=False):
"""Three procedures f0, f1 and f2 from random_program, with two to four
calls x = call fj(a, b) added. Without recursion, fi only calls fj with
j > i. A call in B0 goes after the constants that start B0."""
names = ["f0", "f1", "f2"]
module = {f: random_program(rng, 4, rng.randint(2, 4), True) for f in names}
xs = ["x%d" % i for i in range(4)]
for _ in range(rng.randint(2, 4)):
i = rng.randrange(0, 3 if recursive else 2)
j = rng.randrange(0, 3) if recursive else rng.randrange(i + 1, 3)
prog = module[names[i]]
label = rng.choice(list(prog.blocks))
instrs = prog.blocks[label].instrs
lo = 2 if label == prog.entry else 0
pos = rng.randint(lo, len(instrs))
args = [rng.choice(xs) if rng.random() < 0.6 else rng.randint(0, 5) for _ in range(2)]
instrs.insert(pos, ("call", rng.choice(xs), names[j], args))
return module
def bound_checks(sg, stats):
D1 = max(len(f) for f in sg.facts.values()) + 1
N = len(sg.nodes)
assert stats["path_edges"] <= N * D1 * D1
assert stats["jump_changes"] <= 3 * stats["path_edges"]
assert stats["pops"] <= stats["jump_changes"]
assert stats["summary_changes"] <= 3 * len(sg.callee) * D1 * D1
assert stats["value_changes"] <= 2 * N * D1
assert stats["meets"] <= 3 * sg.num_edges() * 3 * D1 ** 3
def check_sound(module, V, rng, fuel=3000):
for _ in range(3):
args = [rng.randint(-6, 9), rng.randint(-6, 9)]
out, seen = run_recorded(module, "f0", args, fuel)
assert out == toyir.run(module["f0"], args, fuel=fuel, funcs=module)
for n, env in seen:
for x, v in env.items():
assert x in V[n], (n, x)
assert V[n][x] == BOT or V[n][x] == v, (n, x, V[n][x], v)
# ------------------------------------------------------------------- tests
def test_add_example() -> None:
module = add_module()
sg = Supergraph(module, "main")
V, stats = ide(sg)
end = ("main", EXIT, 0)
assert V[end] == {"n": BOT, "x": 2, "y": 7, "z": BOT, "v": 4, "w": 13, RET: 13}
assert V[("add", "B0", 0)] == {"a": BOT, "b": BOT}
# The summary of add maps a to RET by l -> 3l + 1. The first argument
# is 2 at the first call and 4 at the third, so y = 7 and w = 13.
M = mvp_by_paths(sg)
assert M == V
MFP = mfp_supergraph(sg)
assert MFP[end]["y"] == BOT and MFP[end]["w"] == BOT
bound_checks(sg, stats)
assert run_recorded(module, "main", [5])[0] == ("ret", 13)
def test_seeded_main() -> None:
module = add_module()
sg = Supergraph(module, "main")
V, _ = ide(sg, {"n": 5})
end = ("main", EXIT, 0)
assert V[end]["z"] == 16 and V[end]["w"] == 13
assert V[("add", "B0", 0)]["a"] == BOT
assert mvp_by_paths(sg, {"n": 5}) == V
def test_point_function() -> None:
# Two branches give u = 3a + 1 and u = a + 5. The meet of the two
# lines is the point function 2 -> 7, so a call with a = 2 gives 7 and
# any other argument gives BOT.
f = parse("# params: a, b\nB0:\n br b L R\nL:\n t = a * 3\n u = t + 1\n jump J\nR:\n u = a + 5\n jump J\nJ:\n ret u\n")
main = parse("# params: n\nB0:\n x = 2\n y = call f(x, n)\n z = call f(3, n)\n ret y\n")
module = {"main": main, "f": f}
sg = Supergraph(module, "main")
V, _ = ide(sg)
end = ("main", EXIT, 0)
assert V[end]["y"] == 7 and V[end]["z"] == BOT
assert mvp_by_paths(sg) == V
def test_recursion_keeps_linear_relation() -> None:
# The analysis does not follow the branch, so it sees every depth d. At
# depth d the base case returns k - d, and each of the d returns adds
# 1, so down(k) returns k on every valid path. The summary of down is
# the identity, and b = 3.
down = parse("# params: k\nB0:\n c = k < 1\n br c done more\nmore:\n j = k - 1\n r = call down(j)\n s = r + 1\n ret s\ndone:\n ret k\n")
main = parse("# params: n\nB0:\n a = 3\n b = call down(a)\n ret b\n")
module = {"main": main, "down": down}
V = ide_framework(module, "main")
assert V[("main", EXIT, 0)]["b"] == 3
MFP = mfp_supergraph(Supergraph(module, "main"))
assert MFP[("main", EXIT, 0)]["b"] == BOT
def test_random_acyclic_modules() -> None:
rng = random.Random(6101)
srng = random.Random(6201)
compared = strict = 0
for _ in range(300):
module = random_module(rng)
sg = Supergraph(module, "f0")
V, stats = ide(sg)
bound_checks(sg, stats)
M = mvp_by_paths(sg)
if M is not None:
compared += 1
assert V == M
MFP = mfp_supergraph(sg)
for n in sg.nodes:
assert set(MFP[n]) == set(V[n])
assert all(leq(MFP[n][d], V[n][d]) for d in V[n])
if any(MFP[n] != V[n] for n in sg.nodes):
strict += 1
check_sound(module, V, srng)
assert compared >= 290
assert strict >= 12
def test_random_recursive_modules() -> None:
rng = random.Random(6102)
srng = random.Random(6202)
compared = 0
for _ in range(100):
module = random_module(rng, recursive=True)
sg = Supergraph(module, "f0")
V, stats = ide(sg)
bound_checks(sg, stats)
MFP = mfp_supergraph(sg)
for n in sg.nodes:
assert set(MFP[n]) == set(V[n])
assert all(leq(MFP[n][d], V[n][d]) for d in V[n])
# Paths with at most three open calls are some of the valid paths,
# so their meet is above or equal to the result.
M = mvp_by_paths(sg, cap=5000, max_depth=3)
if M is not None:
compared += 1
for n in sg.nodes:
assert set(M[n]) <= set(V[n])
assert all(leq(V[n][d], M[n][d]) for d in M[n])
check_sound(module, V, srng, fuel=400)
assert compared >= 85
def test_bad_input() -> None:
bad = {"main": parse("# params: a\nB0:\n x = call nope(a)\n ret x\n")}
try:
Supergraph(bad)
except ValueError:
pass
else:
raise AssertionError("unknown callee accepted")
History
Callahan, Cooper, Kennedy and Torczon (1986) introduced jump functions and return functions to carry constants across calls in a practical compiler. Sharir and Pnueli (1981) had defined the meet over valid paths and the functional approach, in which each procedure is summarized as a function. Reps, Horwitz and Sagiv (POPL 1995) turned the functional approach for finite distributive subset problems into reachability on the exploded supergraph. Sagiv, Reps and Horwitz then generalized it to environments. They presented IDE at TAPSOFT 1995, and the journal version appeared in Theoretical Computer Science in 1996. It gave the two phases, linear constant propagation as the main example, and the bound. Later tools such as Heros (2012) and PhASAR (2019) made IDE available for Java and for C and C++.
References
- Mooly Sagiv, Thomas Reps and Susan Horwitz, Precise interprocedural dataflow analysis with applications to constant propagation, Theoretical Computer Science 167(1-2), 131 to 170, 1996, the IDE problem, environment transformers, the exploded supergraph with micro-functions, the two-phase algorithm, linear constant propagation and its O(E D^3) bound
- Mooly Sagiv, Thomas Reps and Susan Horwitz, Precise interprocedural dataflow analysis with applications to constant propagation, TAPSOFT '95: Theory and Practice of Software Development, Lecture Notes in Computer Science, 651 to 665, 1995, the conference version of the same work
- Thomas Reps, Susan Horwitz and Mooly Sagiv, Precise interprocedural dataflow analysis via graph reachability, Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '95), 49 to 61, 1995, the IFDS tabulation algorithm that Phase I generalizes
- David Callahan, Keith D. Cooper, Ken Kennedy and Linda Torczon, Interprocedural constant propagation, Proceedings of the 1986 SIGPLAN Symposium on Compiler Construction, 152 to 161, 1986, jump functions and return functions for constants across calls, the earlier practical approach
- Eric Bodden, Inter-procedural data-flow analysis with IFDS/IDE and Soot, Proceedings of the ACM SIGPLAN International Workshop on State of the Art in Java Program Analysis (SOAP '12), 3 to 8, 2012, the Heros solver for IFDS and IDE problems
- Philipp Dominik Schubert, Ben Hermann and Eric Bodden, PhASAR: an inter-procedural static analysis framework for C/C++, Tools and Algorithms for the Construction and Analysis of Systems (TACAS 2019), Lecture Notes in Computer Science, 393 to 410, 2019, an IFDS and IDE solver on LLVM IR
- Micha Sharir and Amir Pnueli, Two approaches to interprocedural data flow analysis, in Steven S. Muchnick and Neil D. Jones (eds.), Program Flow Analysis: Theory and Applications, Prentice-Hall, 1981, the meet over valid paths and the functional approach with procedure summaries
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 60PTYF Edit this page History Report an error Markdown