Algorithmcore
Weiser's slicing algorithm
Also called dataflow-based slicing.
Computes a backward slice by iterating relevant-variable sets over the flow graph and adding the branches that control included statements.
- Solves
- Program slicing
- Time
- O((c + 1) ((n + m) v^2 + c n)) worst
- Space
- O(n v + c n) extra
- Where
- c = the number of branches; m = the number of control flow edges between statements; n = the number of statements; v = the number of variables
- Model
- Word RAM
- Properties
- deterministicexecutable resultofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mark Weiser, 1981
Weiser's algorithm solves the program slicing problem with backward dataflow equations. For a criterion it computes, at each statement, the set of relevant variables: the variables whose values at that statement can flow into at . A statement that writes a relevant variable joins the slice. A branch joins the slice when one of the statements it controls is in the slice, and then the variables that the branch reads become relevant too. The algorithm repeats this until no new branch joins. The result is the dependence slice of the problem page, and deleting the other statements gives a program that runs and gives the same values at . Mark Weiser gave the algorithm in his thesis (1979), at ICSE 1981 and in IEEE TSE (1984).
In plain words
Pick a line and a few variables. Walk backward through the program and keep a list, at each line, of the variables that still matter. At the chosen line, the list holds the chosen variables. Going back over a line that writes a variable on the list, keep that line, take the variable off the list and put on the variables the line reads. Other lines are dropped, and the list passes through them. A loop brings the walk back to lines already seen, so it goes on until no list grows. Then look at the tests. A test that decides whether a kept line runs must be kept too, and the variables it reads start new lists. Repeat the whole walk with these extra starting points until no new test is added. The kept lines form a smaller program that still computes the chosen variables.
The problem
Programs are in the toy IR of the control flow graph pages, with the conventions of the program slicing page. A statement is instruction of block , or its terminator when equals the number of instructions. The statements form a graph: an instruction has the next statement of its block as its only successor, and a terminator has the first statements of its target blocks. is the variable that writes ( for terminators) and is the set of variables it reads. Every block reaches a ret. There are statements, edges between them, variables and branches.
The input is a program and a criterion , where is a statement (the point just before it) and is a set of variables. The output is the set of instructions and branches in the slice, and the executable slice: the projection of on as defined on the problem page. Branches outside become jumps to the immediate post-dominator of their block, all jumps stay, and a ret a keeps only when is that return and .
The algorithm
For a branch at the end of block , let be the immediate post-dominator of , computed with a virtual EXIT after every ret. The influence set is the set of blocks that can be reached from a successor of by a path that does not enter . These are the blocks whose execution decides.
For a seed map that gives a set of variables to some statements, the relevant sets are the least solution of
A variable relevant after stays relevant before unless writes it, and if writes a relevant variable, the variables reads become relevant.
WEISER-SLICE(P, p, V)- 1
compute ipdom(l) for every block l, with a virtual EXIT after every ret - 2
for each branch b at the end of a block l do - 3
INFL(b) <- the blocks reachable from the successors of l without entering ipdom(l) - 4
B <- empty - 5
repeat - 6
seeds(p) <- V; seeds(b) <- REF(b) for every b in B; seeds(n) <- empty for all other n - 7
R <- RELEVANT-SETS(P, seeds) - 8
S <- B union { instructions n : DEF(n) meets R(m) for the successor m of n } - 9
newB <- { branches b : INFL(b) holds the block of p or the block of a statement of S } - 10
done <- (newB = B); B <- newB - 11
until done - 12
return S, R RELEVANT-SETS(P, seeds)- 13
R(n) <- seeds(n) for every statement n - 14
W <- the set of all statements - 15
while W is not empty do - 16
remove a statement m from W - 17
for each predecessor n of m do - 18
X <- R(m) minus DEF(n) - 19
if DEF(n) meets R(m) then X <- X union REF(n) - 20
if X is not a subset of R(n) then R(n) <- R(n) union X; add n to W - 21
return R
Round of lines L5 to L11 is Weiser's step from to . By distributivity, solving once with all the seeds gives the same sets as Weiser's union of one solution for and one for each branch criterion . A branch is in exactly when it is in , because a branch writes nothing. Line L9 also tests the block of , so that a test which decides whether is reached joins the slice even when no statement of lies under it. The executable slice is then built from as in the problem section.
In the implementation, weiser_slice returns , , and the number of rounds, executable_slice builds the projection, slice_point maps to its place in the projection, and observe runs a program like toyir.run and records the values of at each visit of a point. Post-dominators come from the plain iteration over sets.
Analysis summary
The relevant sets are a backward dataflow problem, in the Kildall convention of the dataflow pages, like live variable analysis.
| item | value |
|---|---|
| direction | backward |
| may or must | may (a variable is relevant if it is relevant along some path) |
| domain | sets of variables at each statement; height at each statement |
| order and meet | when ; meet is union |
| and | , = all variables |
| boundary | the seeds: at , at each branch of ; after every ret |
| initial value elsewhere | |
| transfer of | if , applied to the facts of the successors; at a seeded statement, is added |
| monotone | yes |
| distributive | yes: |
The transfer is not of gen-kill form, because the variables that reads are added only when is relevant. This is the transfer of strong liveness (faint variables), seeded at the criterion instead of at the exit. Since the framework is distributive, the maximal fixed point equals the meet over all paths (MOP and MFP coincidence): exactly when some path from carries to a seed through a chain of writes to relevant variables. With the order turned upside down, this is the least solution under reached by iterating up from , which is how the code and the proof describe it.
Soundness is against the runs of the program: the theorem in the proof file says that the projection gives the same values at as for every input on which returns. Every real run follows a path of the control flow graph, so every path counts. Precision is lost because every path counts, even paths that no input can take. In the program
B1:
y = 1
t = a * a
c = t < 0
br c B2 B3
B2:
y = 2
jump B3
B3:
ret y
with , the path through B2 makes y = 2 relevant, the branch on joins through , and the slice keeps all 5 instructions and branches. No input reaches B2, so y = 1 alone is a slice.
Example
Take the program of the problem page, which sums the odd numbers up to in and computes , with the criterion .
B1:
i = 1
s = 0
p = 1
jump B2
B2:
t = i <= n
br t B3 B6
B3:
p = p * i
u = i % 2
br u B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
The immediate post-dominators are B1 to B2, B2 to B6, B3 to B5, B4 to B5, B5 to B2 and B6 to EXIT. So (the loop, entered from B3 and left only through B6) and .
| round | seeds | relevant sets (some points) | new | |
|---|---|---|---|---|
| 1 | at (B6, 0) | at (B6, 0); from (B1, 3) to (B5, 1); at (B1, 1) and (B1, 2); at (B1, 0) | i = 1, p = 1, p = p * i, i = i + 1 |
br t, since of it holds B3 and B5 |
| 2 | also at (B2, 1) | added at (B2, 1); added at every point from (B1, 0) to (B5, 1); | also t = i <= n and br t |
br t only, since holds no statement of |
Round 2 changes nothing in , so the algorithm stops after 2 rounds, with branches. In round 1, p = p * i writes , which is relevant after it, so and become relevant before it, and around the loop stays relevant up to i = 1. The statements s = 0, u = i % 2 and s = s + i write variables that are never relevant, so they stay out. The executable slice is
B1:
i = 1
p = 1
jump B2
B2:
t = i <= n
br t B3 B6
B3:
p = p * i
jump B5
B4:
jump B5
B5:
i = i + 1
jump B2
B6:
ret 0
The branch on became jump B5, its immediate post-dominator, and ret s became ret 0, because is not relevant at the return. On the inputs to , both programs have at B6. For the criterion the algorithm keeps 8 statements, all but p = 1 and p = p * i, also in 2 rounds, and ret s keeps its operand.
Correctness
The full proof is in the proof file. Its steps:
- Least solution. Each transfer is monotone and distributive. The worklist only adds variables that the equations force, and it stops with all equations true, so it returns the least solution. A larger seed map gives larger sets.
- Termination. only grows from round to round, by step 1, so the loop stops after at most rounds. At the end: a kept instruction has ; a dropped instruction writes no variable of at its successor; a kept branch has ; and no of a dropped branch holds a kept statement or .
- INFL is control dependence. For every branch, equals the transitive closure of control dependence in the sense of Ferrante, Ottenstein and Warren. The proof uses two facts about post-dominance: it is antisymmetric, and the strict post-dominators of a block form a chain.
- Dependence slice. is exactly the dependence slice of the problem page. satisfies its three rules, so it contains the least such set. Conversely, the sets defined by def-clear paths to the dependence slice are a solution of each round's equations, so by step 1 each round stays inside the dependence slice.
- The projection is a slice. Relate a state of at statement to a state of the projection at the image of when the two environments agree on . A dropped instruction keeps the relation without a step of the projection. A kept instruction or branch runs on equal operands. At a dropped branch, stays inside until it reaches the post-dominator, makes no observation there and writes no relevant variable, while the projection jumps there in one step. So the observations at are the same, and if returns, so does the projection.
Proof: Weiser's algorithm stops after at most c + 1 rounds, finds the dependence slice, and its projection is a slicefull
Setting. is a toy IR program with instructions x = k, x = y and x = a op b, and terminators jump, br and ret. Every block reaches a ret. Statements, the successor relation between statements, , , the criterion , the sets , , and and the projection are as on the page. There are branches. Post-dominance is taken on the blocks with a virtual EXIT after every ret. For a block that ends in a branch, is its immediate post-dominator. For a set of statements, is the set of their blocks.
Two standard facts about post-dominance are used. (PD1) If post-dominates and post-dominates , then : otherwise take a shortest path from to EXIT; it meets after , and the rest of it, from , meets again, which gives a shorter path from to EXIT. (PD2) The strict post-dominators of a block form a chain, and the immediate one is post-dominated by all the others (see post-dominance).
1. The equations and their least solution
For seeds (a set of names at each statement), the equations are
Lemma 1. Each is monotone and distributive: and . The function RELEVANT-SETS returns the least solution , and (pointwise) implies .
Proof. , and holds if and only if or ; this gives distributivity, and monotonicity follows. The sets in the code only grow, inside the finite set of names, so the loop stops. Each name it adds is forced by an equation from values that are already below the least solution, so by induction on the number of additions the result is below the least solution. When the loop stops, every equation holds, because each change of puts back on the worklist and so recomputes for every predecessor . A solution below the least solution is the least solution. For the last claim, the least solution for satisfies , and by the Knaster-Tarski theorem the least solution for is below every such set.
By distributivity, the least solution for a union of seeds is the union of the least solutions for each seed, so the seeds of round give the same sets as Weiser's .
Lemma 2 (paths). Let be a set of statements and let for , with added. Define as the set of such that some path () has no definition of among and either and , or and . Then for every statement and successor , and imply .
Proof. Put in front of the path for from .
2. Termination
Number the rounds . Round uses (with ), computes from the seeds at and at each , then , then , and it stops when .
Lemma 3. for all , and the algorithm stops after at most rounds.
Proof. . If , the seeds of round contain those of round , so by Lemma 1, then , and , since the test on is monotone in . Each round that does not stop adds at least one branch to , and there are branches, so at most rounds do not stop.
At the last round . Write , and for its values. Then:
- (F1) An instruction with successor is in if and only if ; then by the equation.
- (F2) An instruction with successor has , so and writes no name of .
- (F3) A terminator has , so for every successor .
- (F4) A branch is in if and only if it is in ; then , since is a seed at .
- (F5) A branch has no block of in .
- (F6) .
3. INFL is the transitive control dependence
For blocks, is control dependent on , written , if some successor of is post-dominated by (with allowed) and does not strictly post-dominate .
Lemma 4. For every block that ends in a branch, is the transitive closure .
Proof. Let . First, (KF): strictly post-dominates every . Indeed , and for a path from to EXIT, put in front of it the path from to that avoids after . The result is a path from to EXIT, so it meets , and it can only meet in the part from .
A step. Let , let by the successor , and suppose that every path from to meets before . Every path from to EXIT meets , so it meets first. A path from to the first followed by any path from to EXIT is a path from to EXIT, and it has only after that , so post-dominates . Since post-dominates (for by definition, else by KF), post-dominates . If , then and post-dominate each other and by PD1, which is false ( and KF). If , then strictly post-dominates , against . So some path from to avoids before , and , because would strictly post-dominate . With the path from to , this gives .
Applied to , the step gives , and applied to it gives . So .
Converse. Let by the path , , with . Induction on . Let be the largest index in such that does not post-dominate . If exists, then post-dominates and does not post-dominate , so . For this is , and for , by a shorter path, so and . If does not exist, post-dominates and . If , then by . If , then and both strictly post-dominate , so post-dominates by PD2, and post-dominates by KF, so by PD1, which is false.
4. The result is the dependence slice
Let be the dependence slice of the page program slicing: the least set of instructions and branches closed under its rules 1 to 3. In block terms, a statement is control dependent on the branch of block when its block is in .
Lemma 5. .
Proof. (.) It is enough to show that satisfies the three rules. Rule 1: if defines and a path from the successor of to has no definition of , then by F6 and by F2, F3 and the equations along the path, , so by F1. Rule 2: if the block of is in for a branch ending , it is in by Lemma 4, so by F5. Rule 3: let . If reads and defines with a path from the successor of to that has no definition of before , then by F1 or F4, and as for rule 1, , so . If the block of is in for the branch of , then as for rule 2.
(.) By induction on the rounds, and . Suppose . Take in Lemma 2. Then contains the seeds of round ( at by a path of length 0, and at ). Let for a successor of . The path for from ends at with , and then by rule 1, or at some that reads , and then is data dependent on and by rule 3. In both cases by a path of length 0. With Lemma 2, satisfies , so by Lemma 1 (Knaster-Tarski). Hence every with is in , by the same argument, and . Last, a branch has some whose block is in by Lemma 4. Follow the chain of control dependences from down to the block of : each branch on it is in by rule 2 (when and the branch is the last one) or rule 3, going up the chain from . So .
5. The projection is a slice
Let be the projection: the instructions of stay, every jump stays, a branch in stays, a branch at the end of block becomes jump (or ret 0 if is EXIT), and a ret a keeps only if at that return. For a statement of , let , where is the number of instructions of in before position ; it is the position in of the first kept statement of at or after . The point of the page is .
We consider runs of that never read an undefined name. A configuration is a statement and an environment (a partial map from names to integers). Say when and, for every , either both and are undefined or both are defined and equal.
Lemma 6 (one step). Suppose .
- If is an instruction not in and does not trap at , then moves to , does not move, and .
- If is an instruction in , then traps at if and only if traps at . Otherwise moves to , moves to , and .
- If is a jump or a branch in , both move to the start of the same block, with unchanged environments, and the relation holds there.
- If is a
ret, both runs end. If kept the operand, both return the same value.
Proof. 1. , because is not kept. By F2, writes no name of , so and agree on , and agrees with there. 2. runs the same instruction. By F1, , so the operands have the same values, and the two runs trap together or compute the same value for . Then , and by the equation; and agree on and both map to . 3. By F4, , so the branch goes the same way in both. By F3, for the target , whose position in is . 4. If the operand is kept, .
Lemma 7 (a skipped branch). Suppose , where is a branch at the end of block , and let . Then makes one step: it jumps to the start of with unchanged, or returns 0 when is EXIT. From on, until first enters , the run of makes no observation, and if it enters , at that moment its configuration satisfies . If EXIT, cannot reach a ret before it enters .
Proof. Until it enters , visits only blocks of , by the definition of . By F5, these blocks hold no statement of and not the point , so makes no observation there, and every statement it runs there is an instruction not in or a terminator. By F2 and F3, along the run we get , and no writes a name of . So agrees with on , and agrees with on . If EXIT, a ret block in would give a path from to EXIT that avoids , which is impossible.
Theorem. For every input on which the run of reads no undefined name: if the run of reaches a ret, then the run of reaches a ret and . If the run of traps or does not end, is a prefix of .
Proof. At the start both runs are at the first statement of the entry block with the same environment, so the relation holds. Lemmas 6 and 7 cut the run of into pieces, each matched with zero or one step of , and keep the relation at the end of each piece. Each step of is matched with at least one step of .
Observations. observes when it is at . The block of is never inside a skipped region (F5), so the visits of and to match one to one. In a visit, passes exactly once unless it traps before , and arrives at exactly once, before passes the instructions of at positions from its last kept statement before up to , none of which is kept. At 's observation, the relation holds with at and 's environment as it was when arrived there, and by F6, so both see the same tuple.
If reaches a ret, then by Lemma 6 (4) or Lemma 7 (when returns inside a skipped region with = EXIT, returns at its ret 0), returns at the matching moment, after no more steps than , and neither run observes again. So the sequences are equal. If traps, it traps in a non-kept instruction (then may go on and observe more) or in a kept one (then traps at the same moment). If does not end, every observation of is matched by one of , in order. In both cases is a prefix of .
With Lemma 5, this proves the claim of the page program slicing that the dependence slice, used as the kept set, is a slice.
Complexity
Proved. Each round runs RELEVANT-SETS once. A statement is added to the worklist only when its set grows, and a set grows at most times, so each statement is removed at most times and each edge is handled at most times, with set operations each. A round costs set operations, and line L8 adds more. There are at most rounds. The sets cost one search each, in total, and line L9 tests them once per round, per round with an array of flags for the blocks of . With sets of variables as arrays of flags, a set operation costs word operations, or with words of flags each. The total is time, plus the post-dominators, which take time with Lengauer and Tarjan on the reverse graph. The space is for the relevant sets and for the influence sets.
Reached. The bound of rounds is reached when each test reads a variable that is written only under the next test, so that each round adds one more test. In a seeded run over 300 random programs, some programs needed exactly rounds and none needed more.
Compared. To slice for many criteria, building the program dependence graph once and using slicing by dependence graph reachability costs per criterion, where is the number of dependence edges. Weiser's algorithm needs no dependence graph, but it runs the whole iteration again for each criterion.
Properties
- Executable result. The output is a program in the same language that runs and keeps the criterion values. A dependence graph slice is a set of nodes and needs this rebuilding step.
- Same set as the dependence graph. is the dependence slice, so for one criterion Weiser's algorithm and backward reachability in the program dependence graph keep the same statements.
- Distributive equations. The solution for a set of seeds is the union of the solutions for each seed, so slices for a union of criteria are unions of slices.
- Static. The slice works for every input on which returns. It may hold statements that no input needs, as in the precision example.
- Deterministic. The order of the worklist changes the work, not the result.
Variants and improvements
- Dependence graphs. Ottenstein and Ottenstein (1984) replaced the iteration by one backward search in the program dependence graph; see slicing by dependence graph reachability. For one procedure it gives the same statements.
- Procedures. Weiser sliced across calls by mapping the criterion into the called procedure and out to the callers. This mixes calling contexts and can give large slices. System dependence graph slicing of Horwitz, Reps and Binkley keeps the contexts apart.
- Unstructured jumps. Weiser's programs had structured statements. With
goto,breakandcontinue, deleting statements can change where control goes. Ball and Horwitz (1993) and Agrawal (1994) add the needed jumps to the slice. In the toy IR every jump stays and dropped branches jump to their post-dominator, so the problem does not arise. - Dynamic slices. The same idea on one recorded run gives dynamic slicing, with much smaller slices that hold for one input only.
- Dead code. With the outputs of the program as the criterion, the dropped statements are the dead code that aggressive dead code elimination removes.
When to use it
Use it when one or a few slices are needed and an executable program is wanted, for example to cut a program down for debugging or to extract one computation. It reuses the machinery of a dataflow framework and needs only post-dominators besides. For many slices of the same program, or for forward slices and chops, build the program dependence graph once and use graph reachability.
Pitfalls
- Deleting without rerouting. If a dropped branch is simply removed, control falls into one of its targets, and the slice can run statements the original skipped. The branch must become a jump to its immediate post-dominator, or
ret 0when that is the exit. - Dropping jumps. A jump writes nothing, so the equations never keep it. Dropping it would join blocks that are not adjacent. Keep every jump, or rebuild control flow as in the variants above.
- Forgetting the block of . If line L9 tests only , a criterion inside one arm of a test whose relevant variables are all written before the test loses that test. Then the projection never reaches and records nothing, while does. Some statements of the algorithm test alone; the test of rule 2 of the problem page is needed.
- Stopping after one round. One round finds only the data dependences of . The branches that control those statements, and the data that those branches read, come in later rounds.
- Reading a slice as minimal. The slice can hold statements that no run needs, because the equations count every path. A smaller slice may exist, and finding the smallest is not computable.
- Trusting a dependence graph slice to run. A slice from dependence graph reachability is a set of nodes. It runs only after jumps and block structure are rebuilt as in this algorithm.
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
# 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)
weiser_slicing.py 267 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weiser-slicing/. The authors are listed in prov/S2FQ4Y.jsonl.
"""Weiser's slicing algorithm on the toy IR.
A statement is a pair (label, i): instruction i of block label, or the
terminator of the block when i == len(instrs). A slicing criterion is
(label, i, V): the values of the names in V at the point just before
statement (label, i).
weiser_slice(prog, crit) returns a dict with the slice S (a set of
statements), the relevant sets R, the branch set B and the number of rounds.
executable_slice(prog, crit) returns the slice as a runnable toy IR program,
and slice_point(prog, crit, S) gives the criterion point inside it.
observe(prog, args, point, names) runs a program and records the values of
names each time control reaches point.
The programs use only x = k, x = y and x = a op b, with the terminators jump,
br and ret, and every block must reach a ret.
"""
import toyir
EXIT = "<exit>"
# ------------------------------------------------------------ statements
def statements(prog):
return [(lab, i) for lab, b in prog.blocks.items() for i in range(len(b.instrs) + 1)]
def stmt_succs(prog, node):
lab, i = node
b = prog.blocks[lab]
if i < len(b.instrs):
return [(lab, i + 1)]
return [(s, 0) for s in toyir.succs(prog, lab)]
def DEF(prog, node):
lab, i = node
b = prog.blocks[lab]
if i == len(b.instrs):
return set()
ins = b.instrs[i]
if ins[0] not in ("const", "copy", "op"):
raise ValueError("unsupported instruction: %r" % (ins,))
return {ins[1]}
def REF(prog, node):
lab, i = node
b = prog.blocks[lab]
if i == len(b.instrs):
return set(toyir.term_uses(b.term))
return set(toyir.uses(b.instrs[i]))
# ------------------------------------------------------- post-dominators
def postdominators(prog):
"""Post-dominator sets of the blocks, with a virtual EXIT after every
ret, by the iterative set method."""
labels = list(prog.blocks)
succ = {lab: (toyir.succs(prog, lab) or [EXIT]) for lab in labels}
reach = {EXIT}
changed = True
while changed:
changed = False
for lab in labels:
if lab not in reach and any(s in reach for s in succ[lab]):
reach.add(lab)
changed = True
if len(reach) != len(labels) + 1:
raise ValueError("every block must reach a ret")
full = set(labels) | {EXIT}
pdom = {lab: set(full) for lab in labels}
pdom[EXIT] = {EXIT}
changed = True
while changed:
changed = False
for lab in reversed(labels):
new = {lab} | set.intersection(*(pdom[s] for s in succ[lab]))
if new != pdom[lab]:
pdom[lab] = new
changed = True
return pdom
def ipdom(prog):
"""Immediate post-dominator of each block (EXIT for a ret block)."""
pdom = postdominators(prog)
out = {}
for lab in prog.blocks:
strict = pdom[lab] - {lab}
# The immediate one is post-dominated by all the others.
out[lab] = max(strict, key=lambda x: len(pdom[x]))
return out
def influence(prog, lab, ip=None):
"""INFL of the branch ending block lab: the blocks reachable from its
successors without passing through its immediate post-dominator."""
if ip is None:
ip = ipdom(prog)
stop = ip[lab]
seen = set()
stack = [s for s in toyir.succs(prog, lab) if s != stop]
while stack:
x = stack.pop()
if x in seen:
continue
seen.add(x)
stack.extend(s for s in toyir.succs(prog, x) if s != stop and s not in seen)
return seen
# --------------------------------------------------------------- slicing
def relevant_sets(prog, seeds):
"""Least solution of R(n) = seeds(n) together with, for each successor m,
(R(m) - DEF(n)), plus REF(n) when DEF(n) meets R(m)."""
nodes = statements(prog)
R = {n: set(seeds.get(n, ())) for n in nodes} # @line L13
pred = {n: [] for n in nodes}
for n in nodes:
for m in stmt_succs(prog, n):
pred[m].append(n)
D = {n: DEF(prog, n) for n in nodes}
U = {n: REF(prog, n) for n in nodes}
work = list(nodes) # @line L14
while work: # @line L15
m = work.pop() # @line L16
for n in pred[m]: # @line L17
new = R[m] - D[n] # @line L18
if D[n] & R[m]: # @line L19
new |= U[n]
if not new <= R[n]: # @line L20
R[n] |= new
work.append(n)
return R # @line L21
def weiser_slice(prog, crit):
lab, i, V = crit
point = (lab, i)
nodes = statements(prog)
ip = ipdom(prog) # @line L1
branches = [(b, len(blk.instrs)) for b, blk in prog.blocks.items() if blk.term[0] == "br"] # @line L2
infl = {br: influence(prog, br[0], ip) for br in branches} # @line L3
B = set() # @line L4
rounds = 0
while True: # @line L5 L11
rounds += 1
seeds = {point: set(V)} # @line L6
for br in B:
seeds.setdefault(br, set()).update(REF(prog, br))
R = relevant_sets(prog, seeds) # @line L7
S = {n for n in nodes if any(DEF(prog, n) & R[m] for m in stmt_succs(prog, n))} | B # @line L8
hit = {x for (x, _) in S | {point}}
newB = {br for br in branches if infl[br] & hit} # @line L9
if newB == B: # @line L10
return {"S": S, "R": R, "B": B, "rounds": rounds} # @line L12
B = newB
def executable_slice(prog, crit, result=None):
"""Delete the statements outside the slice. A branch outside the slice
becomes a jump to its immediate post-dominator (or ret 0 when that is
EXIT); jumps stay; a ret keeps its operand only if it is relevant."""
if result is None:
result = weiser_slice(prog, crit)
S, R = result["S"], result["R"]
ip = ipdom(prog)
blocks = {}
for lab, b in prog.blocks.items():
n = len(b.instrs)
instrs = [ins for i, ins in enumerate(b.instrs) if (lab, i) in S]
t = b.term
if t[0] == "br" and (lab, n) not in S:
t = ("ret", 0) if ip[lab] == EXIT else ("jump", ip[lab])
elif t[0] == "ret" and isinstance(t[1], str) and t[1] not in R[(lab, n)]:
t = ("ret", 0)
blocks[lab] = toyir.Block(instrs, t)
return toyir.Program(list(prog.params), blocks)
def slice_point(prog, crit, S):
"""The criterion point in the executable slice."""
lab, i, _ = crit
return (lab, sum(1 for j in range(i) if (lab, j) in S))
# --------------------------------------------------------------- running
class _Trap(Exception):
pass
def _binop(op, a, b):
if op in ("/", "%"):
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 in ("<<", ">>"):
if b < 0 or b > 63:
raise _Trap()
return a << b if op == "<<" else a >> b
return {
"+": lambda: a + b, "-": lambda: a - b, "*": lambda: a * b,
"&": lambda: a & b, "|": lambda: a | b, "^": lambda: a ^ b,
"<": lambda: int(a < b), "<=": lambda: int(a <= b),
"==": lambda: int(a == b), "!=": lambda: int(a != b),
}[op]()
def observe(prog, args, point, names, fuel=10000):
"""Run prog like toyir.run. Return (outcome, obs), where obs has one
tuple of the values of names (None if undefined) for each time control
is about to run the statement at point."""
env = dict(zip(prog.params, args))
plab, pi = point
obs = []
def val(a):
if isinstance(a, int):
return a
if a not in env:
raise toyir.UndefinedName(a)
return env[a]
lab = prog.entry
while True:
b = prog.blocks[lab]
n = len(b.instrs)
for i in range(n + 1):
if lab == plab and i == pi:
obs.append(tuple(env.get(v) for v in names))
if fuel <= 0:
return ("fuel",), obs
fuel -= 1
if i == n:
break
ins = b.instrs[i]
if ins[0] == "const":
env[ins[1]] = ins[2]
elif ins[0] == "copy":
env[ins[1]] = val(ins[2])
else:
try:
env[ins[1]] = _binop(ins[2], val(ins[3]), val(ins[4]))
except _Trap:
return ("trap",), obs
t = b.term
if t[0] == "jump":
lab = t[1]
elif t[0] == "br":
lab = t[2] if val(t[1]) != 0 else t[3]
else:
return ("ret", val(t[1])), obs
test_weiser_slicing.py 284 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weiser-slicing/. The authors are listed in prov/S2FQ4Y.jsonl.
import random
import toyir
from weiser_slicing import (
DEF,
EXIT,
REF,
executable_slice,
influence,
ipdom,
observe,
relevant_sets,
slice_point,
statements,
stmt_succs,
weiser_slice,
)
# The sum and product program of the page.
PAGE = """
B1:
i = 1
s = 0
p = 1
jump B2
B2:
t = i <= n
br t B3 B6
B3:
p = p * i
u = i % 2
br u B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
"""
PAGE_SLICE = """# params: n
B1:
i = 1
p = 1
jump B2
B2:
t = i <= n
br t B3 B6
B3:
p = p * i
jump B5
B4:
jump B5
B5:
i = i + 1
jump B2
B6:
ret 0
"""
def test_page_example():
prog = toyir.parse(PAGE)
crit = ("B6", 0, {"p"})
res = weiser_slice(prog, crit)
assert res["S"] == {("B1", 0), ("B1", 2), ("B2", 0), ("B2", 1), ("B3", 0), ("B5", 0)}
assert res["B"] == {("B2", 1)}
assert res["rounds"] == 2
assert res["R"][("B1", 0)] == {"n"}
assert res["R"][("B2", 1)] == {"i", "n", "p", "t"}
sl = executable_slice(prog, crit, res)
assert toyir.show(sl) == PAGE_SLICE
point = slice_point(prog, crit, res["S"])
for n in range(-2, 9):
o1, ob1 = observe(prog, [n], ("B6", 0), ["p"])
o2, ob2 = observe(sl, [n], point, ["p"])
assert ob1 == ob2
assert observe(prog, [5], ("B6", 0), ["p"])[1] == [(120,)]
def _random_criterion(rng, prog):
nodes = statements(prog)
lab, i = rng.choice(nodes)
names = sorted({v for n in nodes for v in DEF(prog, n)})
V = set(rng.sample(names, rng.randint(1, min(2, len(names)))))
return (lab, i, V)
def test_slice_keeps_criterion_values():
rng = random.Random(2024)
runs = 0
for trial in range(400):
prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 8), trial % 2 == 0)
crit = _random_criterion(rng, prog)
res = weiser_slice(prog, crit)
nbr = sum(1 for b in prog.blocks.values() if b.term[0] == "br")
assert res["rounds"] <= nbr + 1
sl = executable_slice(prog, crit, res)
point = slice_point(prog, crit, res["S"])
names = sorted(crit[2])
for _ in range(8):
args = [rng.randint(-5, 9), rng.randint(-5, 9)]
o1, ob1 = observe(prog, args, crit[:2], names)
assert o1 == toyir.run(prog, args)
o2, ob2 = observe(sl, args, point, names)
if o1[0] == "ret":
assert ob2 == ob1
else:
# The original stopped early; the slice may go further.
assert ob2[: len(ob1)] == ob1
runs += 1
assert runs == 3200
def _postdominates(prog, y, x):
"""y post-dominates x, by definition: every path from x to EXIT meets y."""
if x == y:
return True
seen = {x}
stack = [x]
while stack:
a = stack.pop()
s = toyir.succs(prog, a)
if not s:
return False # reached a ret, so EXIT, without meeting y
for b in s:
if b != y and b not in seen:
seen.add(b)
stack.append(b)
return True
def test_influence_is_control_dependence_closure():
rng = random.Random(7)
for trial in range(300):
prog = toyir.random_program(rng, 3, rng.randint(2, 8), trial % 3 == 0)
ip = ipdom(prog)
labels = list(prog.blocks)
for x in labels:
strict = {y for y in labels if y != x and _postdominates(prog, y, x)}
if strict:
assert ip[x] in strict
assert all(_postdominates(prog, z, ip[x]) for z in strict)
else:
assert ip[x] == EXIT
cd = {
x: {
y
for y in labels
for s in toyir.succs(prog, x)
if _postdominates(prog, y, s) and not (y != x and _postdominates(prog, y, x))
}
for x in labels
}
for x in labels:
if prog.blocks[x].term[0] != "br":
continue
closure = set(cd[x])
stack = list(closure)
while stack:
y = stack.pop()
for z in cd[y]:
if z not in closure:
closure.add(z)
stack.append(z)
assert influence(prog, x, ip) == closure
def _control_deps(prog):
"""Block y is control dependent on block x, by the definition."""
labels = list(prog.blocks)
return {
x: {
y
for y in labels
for s in toyir.succs(prog, x)
if _postdominates(prog, y, s) and not (y != x and _postdominates(prog, y, x))
}
for x in labels
}
def _def_clear_reach(prog, start, x, target):
"""Some path from statement start to target has no definition of x
before target (start itself is checked too)."""
seen = set()
stack = [start]
while stack:
n = stack.pop()
if n == target:
return True
if n in seen or x in DEF(prog, n):
continue
seen.add(n)
stack.extend(stmt_succs(prog, n))
return False
def _dependence_slice(prog, crit):
"""The dependence slice of the page program-slicing, by its rules."""
lab, i, V = crit
nodes = statements(prog)
cd = _control_deps(prog)
parents = {}
for n in nodes:
ps = set()
for s in nodes:
d = DEF(prog, s)
if d and d & REF(prog, n) and any(_def_clear_reach(prog, m, x, n) for x in d for m in stmt_succs(prog, s)):
ps.add(s)
for x in prog.blocks:
if n[0] in cd[x]:
ps.add((x, len(prog.blocks[x].instrs)))
parents[n] = ps
K = set()
for s in nodes:
d = DEF(prog, s)
if d & V and any(_def_clear_reach(prog, m, x, (lab, i)) for x in d & V for m in stmt_succs(prog, s)):
K.add(s)
for x in prog.blocks:
if lab in cd[x]:
K.add((x, len(prog.blocks[x].instrs)))
stack = list(K)
while stack:
n = stack.pop()
for s in parents[n]:
if s not in K:
K.add(s)
stack.append(s)
return K
def test_weiser_slice_equals_dependence_slice():
rng = random.Random(5)
for trial in range(250):
prog = toyir.random_program(rng, rng.randint(2, 4), rng.randint(1, 7), trial % 2 == 0)
crit = _random_criterion(rng, prog)
assert weiser_slice(prog, crit)["S"] == _dependence_slice(prog, crit)
def test_relevant_sets_are_least_solution():
rng = random.Random(11)
for trial in range(200):
prog = toyir.random_program(rng, 4, rng.randint(1, 7), trial % 2 == 1)
nodes = statements(prog)
seeds = {}
for _ in range(rng.randint(1, 3)):
lab, i, V = _random_criterion(rng, prog)
seeds.setdefault((lab, i), set()).update(V)
R = relevant_sets(prog, seeds)
# Round-robin iteration from the seeds gives the least solution.
L = {n: set(seeds.get(n, ())) for n in nodes}
changed = True
while changed:
changed = False
for n in nodes:
new = set(L[n])
for m in stmt_succs(prog, n):
new |= L[m] - DEF(prog, n)
if DEF(prog, n) & L[m]:
new |= REF(prog, n)
if new != L[n]:
L[n] = new
changed = True
assert R == L
def test_single_seed_union():
# The equations are distributive: the solution for two seeds is the union.
rng = random.Random(13)
for trial in range(150):
prog = toyir.random_program(rng, 4, rng.randint(1, 7), trial % 2 == 0)
a, b = _random_criterion(rng, prog), _random_criterion(rng, prog)
Ra = relevant_sets(prog, {a[:2]: a[2]})
Rb = relevant_sets(prog, {b[:2]: b[2]})
seeds = {a[:2]: set(a[2])}
seeds.setdefault(b[:2], set()).update(b[2])
Rab = relevant_sets(prog, seeds)
assert all(Rab[n] == Ra[n] | Rb[n] for n in statements(prog))
History
Mark Weiser defined program slices in his 1979 PhD thesis at the University of Michigan. His motivation was the way programmers debug: they read backward from a wrong value and keep in mind only the code that can affect it. He presented slices and this algorithm at ICSE 1981 and in IEEE Transactions on Software Engineering in 1984, where he also showed that minimal slices cannot be computed in general. His definitions used the nearest inverse dominator of a branch, which is the immediate post-dominator. In 1984 Ottenstein and Ottenstein showed that the same slices are reachability in the program dependence graph, and the graph method became the common one. Tip's survey of 1995 compares the two methods.
References
- Mark Weiser, Program slicing, Proceedings of the 5th International Conference on Software Engineering, San Diego, March 1981, pages 439-449, the relevant variables, the sets of included statements and branches, the INFL sets and the iteration
- Mark Weiser, Program slicing, IEEE Transactions on Software Engineering SE-10(4), 1984, pages 352-357, the equations for the directly relevant variables and statements, the influence sets of branches through the nearest inverse dominator, the iteration to a fixed point, and slices across procedures
- Mark Weiser, Program slices: formal, psychological, and practical investigations of an automatic program abstraction method, PhD thesis, University of Michigan, Ann Arbor, 1979, the first statement of slices and of the dataflow method
- Frank Tip, A survey of program slicing techniques, Journal of Programming Languages 3(3), 1995, pages 121-189, the section on static slicing with dataflow equations, the cost of Weiser's algorithm, and the problems with unstructured control flow
- Jeanne Ferrante, Karl J. Ottenstein and Joe D. Warren, The program dependence graph and its use in optimization, ACM Transactions on Programming Languages and Systems 9(3), 1987, pages 319-349, control dependence defined by post-dominance, which matches the influence sets of the algorithm
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 S2FQ4Y Edit this page History Report an error Markdown