Algorithm Search⌘K

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.

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
Properties
deterministicexecutable resultofflineiterative
Origin
Mark Weiser, 1981

Weiser's algorithm solves the program slicing problem with backward dataflow equations. For a criterion ⟨p,V⟩\langle p, V \rangle it computes, at each statement, the set of relevant variables: the variables whose values at that statement can flow into VV at pp. 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 pp. 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 n=(ℓ,i)n = (\ell, i) is instruction ii of block ℓ\ell, or its terminator when ii 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. DEF(n)DEF(n) is the variable that nn writes (∅\emptyset for terminators) and REF(n)REF(n) is the set of variables it reads. Every block reaches a ret. There are nn statements, mm edges between them, vv variables and cc branches.

The input is a program PP and a criterion C=⟨p,V⟩C = \langle p, V \rangle, where pp is a statement (the point just before it) and VV is a set of variables. The output is the set SS of instructions and branches in the slice, and the executable slice: the projection of PP on SS as defined on the problem page. Branches outside SS become jumps to the immediate post-dominator of their block, all jumps stay, and a ret a keeps aa only when pp is that return and a∈Va \in V.

The algorithm

For a branch bb at the end of block ℓ\ell, let dd be the immediate post-dominator of ℓ\ell, computed with a virtual EXIT after every ret. The influence set INFL(b)INFL(b) is the set of blocks that can be reached from a successor of ℓ\ell by a path that does not enter dd. These are the blocks whose execution bb decides.

For a seed map σ\sigma that gives a set of variables to some statements, the relevant sets are the least solution of

R(n)=σ(n)∪⋃n→m((R(m)∖DEF(n))∪(REF(n) if DEF(n)∩R(m)≠∅)).R(n) = \sigma(n) \cup \bigcup_{n \to m} \Bigl( (R(m) \setminus DEF(n)) \cup \bigl( REF(n) \text{ if } DEF(n) \cap R(m) \ne \emptyset \bigr) \Bigr).

A variable relevant after nn stays relevant before nn unless nn writes it, and if nn writes a relevant variable, the variables nn reads become relevant.

  1. WEISER-SLICE(P, p, V)
  2. 1compute ipdom(l) for every block l, with a virtual EXIT after every ret
  3. 2for each branch b at the end of a block l do
  4. 3INFL(b) <- the blocks reachable from the successors of l without entering ipdom(l)
  5. 4B <- empty
  6. 5repeat
  7. 6seeds(p) <- V; seeds(b) <- REF(b) for every b in B; seeds(n) <- empty for all other n
  8. 7R <- RELEVANT-SETS(P, seeds)
  9. 8S <- B union { instructions n : DEF(n) meets R(m) for the successor m of n }
  10. 9newB <- { branches b : INFL(b) holds the block of p or the block of a statement of S }
  11. 10done <- (newB = B); B <- newB
  12. 11until done
  13. 12return S, R
  14. RELEVANT-SETS(P, seeds)
  15. 13R(n) <- seeds(n) for every statement n
  16. 14W <- the set of all statements
  17. 15while W is not empty do
  18. 16remove a statement m from W
  19. 17for each predecessor n of m do
  20. 18X <- R(m) minus DEF(n)
  21. 19if DEF(n) meets R(m) then X <- X union REF(n)
  22. 20if X is not a subset of R(n) then R(n) <- R(n) union X; add n to W
  23. 21return R

Round kk of lines L5 to L11 is Weiser's step from Rk−1R^{k-1} to RkR^k. By distributivity, solving once with all the seeds gives the same sets as Weiser's union of one solution for CC and one for each branch criterion ⟨b,REF(b)⟩\langle b, REF(b) \rangle. A branch is in SS exactly when it is in BB, because a branch writes nothing. Line L9 also tests the block of pp, so that a test which decides whether pp is reached joins the slice even when no statement of SS lies under it. The executable slice is then built from SS as in the problem section.

In the implementation, weiser_slice returns SS, RR, BB and the number of rounds, executable_slice builds the projection, slice_point maps pp to its place in the projection, and observe runs a program like toyir.run and records the values of VV 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 h=vh = v at each statement
order and meet X⊑YX \sqsubseteq Y when X⊇YX \supseteq Y; meet is union
⊤\top and ⊥\bot ⊤=∅\top = \emptyset, ⊥\bot = all variables
boundary the seeds: VV at pp, REF(b)REF(b) at each branch of BB; ∅\emptyset after every ret
initial value elsewhere ⊤=∅\top = \emptyset
transfer of nn fn(X)=(X∖DEF(n))∪(REF(n)f_n(X) = (X \setminus DEF(n)) \cup (REF(n) if DEF(n)∩X≠∅)DEF(n) \cap X \ne \emptyset), applied to the facts of the successors; at a seeded statement, σ(n)\sigma(n) is added
monotone yes
distributive yes: fn(X∪Y)=fn(X)∪fn(Y)f_n(X \cup Y) = f_n(X) \cup f_n(Y)

The transfer is not of gen-kill form, because the variables that nn reads are added only when DEF(n)DEF(n) 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): x∈R(n)x \in R(n) exactly when some path from nn carries xx to a seed through a chain of writes to relevant variables. With the order turned upside down, this is the least solution under ⊆\subseteq reached by iterating up from ∅\emptyset, 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 pp as PP for every input on which PP 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 C=⟨(B3,0),{y}⟩C = \langle (B3, 0), \{y\} \rangle, the path through B2 makes y = 2 relevant, the branch on cc joins through INFLINFL, 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 nn in ss and computes p=n!p = n!, with the criterion ⟨(B6,0),{p}⟩\langle (B6, 0), \{p\} \rangle.

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 INFL(br t)={B2,B3,B4,B5}INFL(\texttt{br t}) = \{B2, B3, B4, B5\} (the loop, entered from B3 and left only through B6) and INFL(br u)={B4}INFL(\texttt{br u}) = \{B4\}.

round seeds relevant sets (some points) SS new BB
1 pp at (B6, 0) {p}\{p\} at (B6, 0); {i,p}\{i, p\} from (B1, 3) to (B5, 1); {i}\{i\} at (B1, 1) and (B1, 2); ∅\emptyset at (B1, 0) i = 1, p = 1, p = p * i, i = i + 1 br t, since INFLINFL of it holds B3 and B5
2 also tt at (B2, 1) tt added at (B2, 1); nn added at every point from (B1, 0) to (B5, 1); R(B2,1)={i,n,p,t}R(B2, 1) = \{i, n, p, t\} also t = i <= n and br t br t only, since INFL(br u)={B4}INFL(\texttt{br u}) = \{B4\} holds no statement of SS

Round 2 changes nothing in BB, so the algorithm stops after 2 rounds, with c=2c = 2 branches. In round 1, p = p * i writes pp, which is relevant after it, so ii and pp become relevant before it, and around the loop ii 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 uu became jump B5, its immediate post-dominator, and ret s became ret 0, because ss is not relevant at the return. On the inputs n=0n = 0 to 66, both programs have p=1,1,2,6,24,120,720p = 1, 1, 2, 6, 24, 120, 720 at B6. For the criterion ⟨(B6,0),{s}⟩\langle (B6, 0), \{s\} \rangle 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:

  1. 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.
  2. Termination. BB only grows from round to round, by step 1, so the loop stops after at most c+1c + 1 rounds. At the end: a kept instruction has REF(n)⊆R(n)REF(n) \subseteq R(n); a dropped instruction writes no variable of RR at its successor; a kept branch has REF(b)⊆R(b)REF(b) \subseteq R(b); and no INFLINFL of a dropped branch holds a kept statement or pp.
  3. INFL is control dependence. For every branch, INFL(b)INFL(b) 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.
  4. Dependence slice. SS is exactly the dependence slice of the problem page. SS satisfies its three rules, so it contains the least such set. Conversely, the sets R∗R^\ast 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.
  5. The projection is a slice. Relate a state of PP at statement nn to a state of the projection at the image of nn when the two environments agree on R(n)R(n). 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, PP stays inside INFLINFL 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 pp are the same, and if PP 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. PP 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 n→mn \to m between statements, DEFDEF, REFREF, the criterion C=⟨p,V⟩C = \langle p, V \rangle, the sets RR, SS, BB and INFLINFL and the projection are as on the page. There are cc branches. Post-dominance is taken on the blocks with a virtual EXIT after every ret. For a block ℓ\ell that ends in a branch, dℓd_\ell is its immediate post-dominator. For a set XX of statements, blk(X)\mathrm{blk}(X) is the set of their blocks.

Two standard facts about post-dominance are used. (PD1) If aa post-dominates bb and bb post-dominates aa, then a=ba = b: otherwise take a shortest path from aa to EXIT; it meets bb after aa, and the rest of it, from bb, meets aa again, which gives a shorter path from aa 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 σ\sigma (a set of names at each statement), the equations are

R(n)=σ(n)∪⋃n→mfn(R(m)),fn(X)=(X∖DEF(n))∪{REF(n)if DEF(n)∩X≠∅∅otherwise.R(n) = \sigma(n) \cup \bigcup_{n \to m} f_n(R(m)), \qquad f_n(X) = (X \setminus DEF(n)) \cup \begin{cases} REF(n) & \text{if } DEF(n) \cap X \ne \emptyset \\ \emptyset & \text{otherwise.} \end{cases}

Lemma 1. Each fnf_n is monotone and distributive: fn(X∪Y)=fn(X)∪fn(Y)f_n(X \cup Y) = f_n(X) \cup f_n(Y) and fn(∅)=∅f_n(\emptyset) = \emptyset. The function RELEVANT-SETS returns the least solution RσR_\sigma, and σ⊆σ′\sigma \subseteq \sigma' (pointwise) implies Rσ⊆Rσ′R_\sigma \subseteq R_{\sigma'}.

Proof. (X∪Y)∖D=(X∖D)∪(Y∖D)(X \cup Y) \setminus D = (X \setminus D) \cup (Y \setminus D), and D∩(X∪Y)≠∅D \cap (X \cup Y) \ne \emptyset holds if and only if D∩X≠∅D \cap X \ne \emptyset or D∩Y≠∅D \cap Y \ne \emptyset; 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 R(m)R(m) puts mm back on the worklist and so recomputes fn(R(m))f_n(R(m)) for every predecessor nn. A solution below the least solution is the least solution. For the last claim, the least solution for σ′\sigma' satisfies R(n)⊇σ(n)∪⋃fn(R(m))R(n) \supseteq \sigma(n) \cup \bigcup f_n(R(m)), and by the Knaster-Tarski theorem the least solution for σ\sigma is below every such set. □\square

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 kk give the same sets as Weiser's RC0∪⋃b∈BR⟨b,REF(b)⟩0R^0_C \cup \bigcup_{b \in B} R^0_{\langle b, REF(b) \rangle}.

Lemma 2 (paths). Let TT be a set of statements and let σ(u)=REF(u)\sigma(u) = REF(u) for u∈Tu \in T, with σ(p)⊇V\sigma(p) \supseteq V added. Define R∗(n)R^\ast(n) as the set of xx such that some path n=n0→⋯→nkn = n_0 \to \cdots \to n_k (k≥0k \ge 0) has no definition of xx among n0,…,nk−1n_0, \ldots, n_{k-1} and either nk=pn_k = p and x∈Vx \in V, or nk∈Tn_k \in T and x∈REF(nk)x \in REF(n_k). Then for every statement nn and successor mm, x∈R∗(m)x \in R^\ast(m) and x∉DEF(n)x \notin DEF(n) imply x∈R∗(n)x \in R^\ast(n).

Proof. Put nn in front of the path for xx from mm. □\square

2. Termination

Number the rounds k=1,2,…k = 1, 2, \ldots. Round kk uses Bk−1B_{k-1} (with B0=∅B_0 = \emptyset), computes RkR_k from the seeds VV at pp and REF(b)REF(b) at each b∈Bk−1b \in B_{k-1}, then Sk={n:DEF(n)∩Rk(m)≠∅ for its successor m}∪Bk−1S_k = \{n : DEF(n) \cap R_k(m) \ne \emptyset \text{ for its successor } m\} \cup B_{k-1}, then Bk={b:INFL(b)∩blk(Sk∪{p})≠∅}B_k = \{b : INFL(b) \cap \mathrm{blk}(S_k \cup \{p\}) \ne \emptyset\}, and it stops when Bk=Bk−1B_k = B_{k-1}.

Lemma 3. Bk−1⊆BkB_{k-1} \subseteq B_k for all kk, and the algorithm stops after at most c+1c + 1 rounds.

Proof. B0=∅⊆B1B_0 = \emptyset \subseteq B_1. If Bk−1⊆BkB_{k-1} \subseteq B_k, the seeds of round k+1k + 1 contain those of round kk, so Rk⊆Rk+1R_k \subseteq R_{k+1} by Lemma 1, then Sk⊆Sk+1S_k \subseteq S_{k+1}, and Bk⊆Bk+1B_k \subseteq B_{k+1}, since the test on INFLINFL is monotone in SS. Each round that does not stop adds at least one branch to BB, and there are cc branches, so at most cc rounds do not stop. □\square

At the last round Bk=Bk−1B_k = B_{k-1}. Write RR, SS and BB for its values. Then:

  • (F1) An instruction nn with successor mm is in SS if and only if DEF(n)∩R(m)≠∅DEF(n) \cap R(m) \ne \emptyset; then REF(n)⊆R(n)REF(n) \subseteq R(n) by the equation.
  • (F2) An instruction n∉Sn \notin S with successor mm has DEF(n)∩R(m)=∅DEF(n) \cap R(m) = \emptyset, so R(m)⊆R(n)R(m) \subseteq R(n) and nn writes no name of R(m)R(m).
  • (F3) A terminator nn has DEF(n)=∅DEF(n) = \emptyset, so R(m)⊆R(n)R(m) \subseteq R(n) for every successor mm.
  • (F4) A branch is in SS if and only if it is in BB; then REF(b)⊆R(b)REF(b) \subseteq R(b), since REF(b)REF(b) is a seed at bb.
  • (F5) A branch b∉Bb \notin B has no block of blk(S∪{p})\mathrm{blk}(S \cup \{p\}) in INFL(b)INFL(b).
  • (F6) V⊆R(p)V \subseteq R(p).

3. INFL is the transitive control dependence

For blocks, yy is control dependent on xx, written y∈CD(x)y \in CD(x), if some successor ss of xx is post-dominated by yy (with y=sy = s allowed) and yy does not strictly post-dominate xx.

Lemma 4. For every block ℓ\ell that ends in a branch, INFL(ℓ)INFL(\ell) is the transitive closure CD+(ℓ)CD^+(\ell).

Proof. Let d=dℓd = d_\ell. First, (KF): dd strictly post-dominates every y∈INFL(ℓ)y \in INFL(\ell). Indeed y≠dy \ne d, and for a path from yy to EXIT, put in front of it the path from ℓ\ell to yy that avoids dd after ℓ\ell. The result is a path from ℓ\ell to EXIT, so it meets dd, and it can only meet dd in the part from yy.

A step. Let x∈{ℓ}∪INFL(ℓ)x \in \{\ell\} \cup INFL(\ell), let z∈CD(x)z \in CD(x) by the successor ss, and suppose that every path from ss to zz meets dd before zz. Every path from ss to EXIT meets zz, so it meets dd first. A path from ss to the first dd followed by any path from dd to EXIT is a path from ss to EXIT, and it has zz only after that dd, so zz post-dominates dd. Since dd post-dominates xx (for x=ℓx = \ell by definition, else by KF), zz post-dominates xx. If z=xz = x, then xx and dd post-dominate each other and x=dx = d by PD1, which is false (d≠ℓd \ne \ell and KF). If z≠xz \ne x, then zz strictly post-dominates xx, against z∈CD(x)z \in CD(x). So some path from ss to zz avoids dd before zz, and z≠dz \ne d, because z=dz = d would strictly post-dominate xx. With the path from ℓ\ell to xx, this gives z∈INFL(ℓ)z \in INFL(\ell).

Applied to x=ℓx = \ell, the step gives CD(ℓ)⊆INFL(ℓ)CD(\ell) \subseteq INFL(\ell), and applied to x∈INFL(ℓ)x \in INFL(\ell) it gives CD(x)⊆INFL(ℓ)CD(x) \subseteq INFL(\ell). So CD+(ℓ)⊆INFL(ℓ)CD^+(\ell) \subseteq INFL(\ell).

Converse. Let y∈INFL(ℓ)y \in INFL(\ell) by the path ℓ=s0,s1,…,sk=y\ell = s_0, s_1, \ldots, s_k = y, k≥1k \ge 1, with s1,…,sk≠ds_1, \ldots, s_k \ne d. Induction on kk. Let jj be the largest index in 0,…,k−10, \ldots, k - 1 such that yy does not post-dominate sjs_j. If jj exists, then yy post-dominates sj+1s_{j+1} and does not post-dominate sjs_j, so y∈CD(sj)y \in CD(s_j). For j=0j = 0 this is y∈CD(ℓ)y \in CD(\ell), and for j≥1j \ge 1, sj∈INFL(ℓ)s_j \in INFL(\ell) by a shorter path, so sj∈CD+(ℓ)s_j \in CD^+(\ell) and y∈CD+(ℓ)y \in CD^+(\ell). If jj does not exist, yy post-dominates ℓ\ell and s1s_1. If y=ℓy = \ell, then y∈CD(ℓ)y \in CD(\ell) by s1s_1. If y≠ℓy \ne \ell, then yy and dd both strictly post-dominate ℓ\ell, so yy post-dominates dd by PD2, and dd post-dominates yy by KF, so y=dy = d by PD1, which is false. □\square

4. The result is the dependence slice

Let K∗K^\ast 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 xx when its block is in CD(x)CD(x).

Lemma 5. S=K∗S = K^\ast.

Proof. (K∗⊆SK^\ast \subseteq S.) It is enough to show that SS satisfies the three rules. Rule 1: if ss defines x∈Vx \in V and a path from the successor mm of ss to pp has no definition of xx, then by F6 and by F2, F3 and the equations along the path, x∈R(m)x \in R(m), so s∈Ss \in S by F1. Rule 2: if the block of pp is in CD(x)CD(x) for a branch bb ending xx, it is in INFL(b)INFL(b) by Lemma 4, so b∈B⊆Sb \in B \subseteq S by F5. Rule 3: let t∈St \in S. If tt reads xx and ss defines xx with a path from the successor mm of ss to tt that has no definition of xx before tt, then x∈REF(t)⊆R(t)x \in REF(t) \subseteq R(t) by F1 or F4, and as for rule 1, x∈R(m)x \in R(m), so s∈Ss \in S. If the block of tt is in CD(x)CD(x) for the branch bb of xx, then b∈Sb \in S as for rule 2.

(S⊆K∗S \subseteq K^\ast.) By induction on the rounds, Sk⊆K∗S_k \subseteq K^\ast and Bk⊆K∗B_k \subseteq K^\ast. Suppose Bk−1⊆K∗B_{k-1} \subseteq K^\ast. Take T=K∗T = K^\ast in Lemma 2. Then R∗R^\ast contains the seeds of round kk (VV at pp by a path of length 0, and REF(b)REF(b) at b∈Bk−1⊆K∗b \in B_{k-1} \subseteq K^\ast). Let y∈DEF(n)∩R∗(m)y \in DEF(n) \cap R^\ast(m) for a successor mm of nn. The path for yy from mm ends at pp with y∈Vy \in V, and then n∈K∗n \in K^\ast by rule 1, or at some u∈K∗u \in K^\ast that reads yy, and then uu is data dependent on nn and n∈K∗n \in K^\ast by rule 3. In both cases REF(n)⊆R∗(n)REF(n) \subseteq R^\ast(n) by a path of length 0. With Lemma 2, R∗R^\ast satisfies R∗(n)⊇σ(n)∪⋃mfn(R∗(m))R^\ast(n) \supseteq \sigma(n) \cup \bigcup_m f_n(R^\ast(m)), so Rk⊆R∗R_k \subseteq R^\ast by Lemma 1 (Knaster-Tarski). Hence every nn with DEF(n)∩Rk(m)≠∅DEF(n) \cap R_k(m) \ne \emptyset is in K∗K^\ast, by the same argument, and Sk⊆K∗S_k \subseteq K^\ast. Last, a branch b∈Bkb \in B_k has some u∈Sk∪{p}u \in S_k \cup \{p\} whose block is in INFL(b)=CD+(b)INFL(b) = CD^+(b) by Lemma 4. Follow the chain of control dependences from bb down to the block of uu: each branch on it is in K∗K^\ast by rule 2 (when u=pu = p and the branch is the last one) or rule 3, going up the chain from uu. So b∈K∗b \in K^\ast. □\square

5. The projection is a slice

Let QQ be the projection: the instructions of SS stay, every jump stays, a branch in BB stays, a branch b∉Bb \notin B at the end of block ℓ\ell becomes jump dℓd_\ell (or ret 0 if dℓd_\ell is EXIT), and a ret a keeps aa only if a∈Ra \in R at that return. For a statement n=(ℓ,i)n = (\ell, i) of PP, let π(n)=(ℓ,j)\pi(n) = (\ell, j), where jj is the number of instructions of SS in ℓ\ell before position ii; it is the position in QQ of the first kept statement of ℓ\ell at or after nn. The point pQp_Q of the page is π(p)\pi(p).

We consider runs of PP that never read an undefined name. A configuration is a statement and an environment (a partial map from names to integers). Say (n,σ)∼(q,τ)(n, \sigma) \sim (q, \tau) when q=π(n)q = \pi(n) and, for every x∈R(n)x \in R(n), either both σ(x)\sigma(x) and τ(x)\tau(x) are undefined or both are defined and equal.

Lemma 6 (one step). Suppose (n,σ)∼(q,τ)(n, \sigma) \sim (q, \tau).

  1. If nn is an instruction not in SS and PP does not trap at nn, then PP moves to (m,σ′)(m, \sigma'), QQ does not move, and (m,σ′)∼(q,τ)(m, \sigma') \sim (q, \tau).
  2. If nn is an instruction in SS, then PP traps at nn if and only if QQ traps at qq. Otherwise PP moves to (m,σ′)(m, \sigma'), QQ moves to (q′,τ′)(q', \tau'), and (m,σ′)∼(q′,τ′)(m, \sigma') \sim (q', \tau').
  3. If nn is a jump or a branch in BB, both move to the start of the same block, with unchanged environments, and the relation holds there.
  4. If nn is a ret, both runs end. If QQ kept the operand, both return the same value.

Proof. 1. π(m)=π(n)=q\pi(m) = \pi(n) = q, because nn is not kept. By F2, nn writes no name of R(m)⊆R(n)R(m) \subseteq R(n), so σ′\sigma' and σ\sigma agree on R(m)R(m), and σ\sigma agrees with τ\tau there. 2. QQ runs the same instruction. By F1, REF(n)⊆R(n)REF(n) \subseteq R(n), so the operands have the same values, and the two runs trap together or compute the same value vv for x=DEF(n)x = DEF(n). Then π(m)=q′\pi(m) = q', and R(m)⊆R(n)∪{x}R(m) \subseteq R(n) \cup \{x\} by the equation; σ′\sigma' and τ′\tau' agree on R(n)∖{x}R(n) \setminus \{x\} and both map xx to vv. 3. By F4, REF(b)⊆R(b)REF(b) \subseteq R(b), so the branch goes the same way in both. By F3, R(m)⊆R(n)R(m) \subseteq R(n) for the target mm, whose position in QQ is π(m)\pi(m). 4. If the operand aa is kept, a∈R(n)a \in R(n). □\square

Lemma 7 (a skipped branch). Suppose (n,σ)∼(q,τ)(n, \sigma) \sim (q, \tau), where nn is a branch b∉Bb \notin B at the end of block ℓ\ell, and let d=dℓd = d_\ell. Then QQ makes one step: it jumps to the start of dd with τ\tau unchanged, or returns 0 when dd is EXIT. From nn on, until PP first enters dd, the run of PP makes no observation, and if it enters dd, at that moment its configuration ((d,0),σ′′)((d, 0), \sigma'') satisfies ((d,0),σ′′)∼(π((d,0)),τ)((d, 0), \sigma'') \sim (\pi((d, 0)), \tau). If d≠d \ne EXIT, PP cannot reach a ret before it enters dd.

Proof. Until it enters dd, PP visits only blocks of INFL(ℓ)INFL(\ell), by the definition of INFLINFL. By F5, these blocks hold no statement of SS and not the point pp, so PP makes no observation there, and every statement it runs there is an instruction not in SS or a terminator. By F2 and F3, along the run n=n0,n1,…,nr=(d,0)n = n_0, n_1, \ldots, n_r = (d, 0) we get R(n0)⊇R(n1)⊇⋯⊇R(nr)R(n_0) \supseteq R(n_1) \supseteq \cdots \supseteq R(n_r), and no njn_j writes a name of R(nj+1)⊇R(nr)R(n_{j+1}) \supseteq R(n_r). So σ′′\sigma'' agrees with σ\sigma on R(nr)R(n_r), and σ\sigma agrees with τ\tau on R(n)⊇R(nr)R(n) \supseteq R(n_r). If d≠d \ne EXIT, a ret block in INFL(ℓ)INFL(\ell) would give a path from ℓ\ell to EXIT that avoids dd, which is impossible. □\square

Theorem. For every input II on which the run of PP reads no undefined name: if the run of PP reaches a ret, then the run of QQ reaches a ret and obsQ(I,⟨pQ,V⟩)=obsP(I,⟨p,V⟩)\mathrm{obs}_Q(I, \langle p_Q, V \rangle) = \mathrm{obs}_P(I, \langle p, V \rangle). If the run of PP traps or does not end, obsP\mathrm{obs}_P is a prefix of obsQ\mathrm{obs}_Q.

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 PP into pieces, each matched with zero or one step of QQ, and keep the relation at the end of each piece. Each step of QQ is matched with at least one step of PP.

Observations. PP observes when it is at pp. The block ℓp\ell_p of pp is never inside a skipped region (F5), so the visits of PP and QQ to ℓp\ell_p match one to one. In a visit, PP passes pp exactly once unless it traps before pp, and QQ arrives at π(p)\pi(p) exactly once, before PP passes the instructions of ℓp\ell_p at positions from its last kept statement before pp up to pp, none of which is kept. At PP's observation, the relation holds with QQ at π(p)\pi(p) and QQ's environment as it was when QQ arrived there, and V⊆R(p)V \subseteq R(p) by F6, so both see the same tuple.

If PP reaches a ret, then by Lemma 6 (4) or Lemma 7 (when PP returns inside a skipped region with dd = EXIT, QQ returns at its ret 0), QQ returns at the matching moment, after no more steps than PP, and neither run observes again. So the sequences are equal. If PP traps, it traps in a non-kept instruction (then QQ may go on and observe more) or in a kept one (then QQ traps at the same moment). If PP does not end, every observation of PP is matched by one of QQ, in order. In both cases obsP\mathrm{obs}_P is a prefix of obsQ\mathrm{obs}_Q. □\square

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 vv times, so each statement is removed at most v+1v + 1 times and each edge is handled at most v+1v + 1 times, with O(1)O(1) set operations each. A round costs O(v(n+m))O(v (n + m)) set operations, and line L8 adds O(n+m)O(n + m) more. There are at most c+1c + 1 rounds. The INFLINFL sets cost one search each, O(c(n+m))O(c (n + m)) in total, and line L9 tests them once per round, O(cn)O(c n) per round with an array of flags for the blocks of SS. With sets of vv variables as arrays of flags, a set operation costs O(v)O(v) word operations, or O(⌈v/w⌉)O(\lceil v / w \rceil) with words of ww flags each. The total is O((c+1)((n+m)v2+cn))O((c + 1)((n + m) v^2 + c n)) time, plus the post-dominators, which take O((n+m) α(n+m))O((n + m)\, \alpha(n + m)) time with Lengauer and Tarjan on the reverse graph. The space is O(nv)O(n v) for the relevant sets and O(cn)O(c n) for the influence sets.

Reached. The bound of c+1c + 1 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 c+1c + 1 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 O(n+e)O(n + e) per criterion, where ee 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. SS 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 PP 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, break and continue, 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 0 when 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 pp. If line L9 tests only SS, 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 pp and records nothing, while PP does. Some statements of the algorithm test SS alone; the test of rule 2 of the problem page is needed.
  • Stopping after one round. One round finds only the data dependences of VV. 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.

toyir.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example