Algorithm Search⌘K

Algorithmadvanced

IFDS framework

Also called IFDS, Reps-Horwitz-Sagiv algorithm.

Solves interprocedural, finite, distributive, subset problems exactly in O(E D^3) time by graph reachability on an exploded supergraph.

Time
O(E D^3) worst · averageΘ(N + E) best
Space
O(N D^2 + C D^2) extra
Where
C = the number of call sites; D = the largest number of facts of one procedure; E = the number of edges of the supergraph; N = the number of nodes of the supergraph
Properties
deterministiciterative

The IFDS framework of Reps, Horwitz and Sagiv solves a large class of interprocedural dataflow problems exactly. The class is in the name: Interprocedural, Finite, Distributive, Subset. The facts form a finite set DD, an analysis result at a point is a subset of DD, and every flow function distributes over union. Taint analysis, reaching definitions, possibly uninitialized variables and all gen-kill problems fit. The algorithm turns the problem into reachability in an exploded supergraph, which has one node for each pair of a program point and a fact. A fact holds at a point exactly when its node can be reached along a path whose calls and returns match. The tabulation algorithm finds these nodes with a worklist. It records path edges inside procedures and summary edges across calls, so it never walks through a procedure twice for the same fact. The answer is the meet over all valid paths, the best answer that ignores branch conditions, even with recursion. The time is O(ED3)O(E D^3), where EE is the number of edges of the supergraph.

In plain words

Many questions about a program are yes or no questions about a fixed list of facts, such as "this variable may hold a secret". IFDS answers them across procedure calls without mixing up the callers. It draws a big graph with one copy of every program point for each fact. An edge says that a fact at one point causes a fact at the next point. Then "does this fact hold here" becomes "can we walk to this node". The walk must leave each procedure back to the call it came in by. To avoid walking through a procedure again and again, the algorithm remembers, for each fact at the entry of a procedure, which facts come out at its exit. These shortcuts are the summary edges. The cost grows with the size of the program times the cube of the number of facts.

The problem

An IFDS instance is a supergraph G∗G^* with a finite set of facts DpD_p for each procedure pp, a seed set S⊆DmainS \subseteq D_{main}, and a flow function fe:2Dp→2Dqf_e : 2^{D_p} \to 2^{D_q} for each edge ee with fe(X∪Y)=fe(X)∪fe(Y)f_e(X \cup Y) = f_e(X) \cup f_e(Y). The supergraph has the call edge, the return edge and the call-to-return edge of each call site, as on the interprocedural dataflow analysis page. The output is, for every node nn,

MVP(n)=⋃{fπ(S):π a valid path from smain to n},\mathrm{MVP}(n) = \bigcup \{ f_\pi(S) : \pi \text{ a valid path from } s_{main} \text{ to } n \},

where a path is valid when every return goes back to the call that its procedure was entered from. Sets of facts are ordered by ⊇\supseteq, so union is the meet and ∅\emptyset is ⊤\top: this is the meet convention of Kildall, and the result is the greatest solution. In the join convention of Cousot the order flips, union is the join, and the same set is the least solution. A problem whose meet is intersection, such as available expressions, fits after a change to the complement facts, since the complement of a distributive intersection problem is a distributive union problem.

The implementation solves a taint problem on the toy IR. The question is which variables may depend on the first parameter of main. It follows data flow only, not branches.

item choice
facts of pp the variables of pp, and RET for its return value
seed the first parameter of main
x = k kills x
x = a a gives a and x; x itself dies unless it is a
x = a op b each operand gives itself and x; x itself dies unless it is an operand
ret a every fact stays; a also gives RET
call edge of x = call q(a, b) an argument gives the parameters it is passed to
call-to-return edge every fact of the caller stays, except x
return edge RET gives x; nothing else crosses
jump, br every fact stays

The algorithm

The exploded supergraph. A distributive function on subsets is fixed by what it does to each single fact and to the empty set. So draw it as a bipartite graph on D∪{0}D \cup \{\mathbf{0}\}. The extra fact 0\mathbf{0} always holds. There is an edge 0→0\mathbf{0} \to \mathbf{0}, an edge 0→d′\mathbf{0} \to d' for every d′d' that ff makes from nothing, and an edge d→d′d \to d' for every d′∈f({d})d' \in f(\{d\}). The facts reachable from X∪{0}X \cup \{\mathbf{0}\} are then f(X)∪{0}f(X) \cup \{\mathbf{0}\}, and composing two functions is joining their graphs end to end. The exploded supergraph G#G^\# puts these small graphs on every edge of G∗G^*. Its nodes are the pairs ⟨n,d⟩\langle n, d \rangle.

flow function edges out of ⟨n,d⟩\langle n, d \rangle
identity d→dd \to d for every dd
kill x d→dd \to d for d≠xd \ne x; no edge out of x
gen x 0→x\mathbf{0} \to x, plus the identity
copy x = a a →\to a, a →\to x, d→dd \to d for d≠xd \ne x

Tabulation. The algorithm does not build G#G^\#. It finds the reachable part with a worklist. A path edge (n,d1,d2)(n, d_1, d_2) says that ⟨n,d2⟩\langle n, d_2 \rangle can be reached from ⟨sp,d1⟩\langle s_p, d_1 \rangle, the start of its own procedure, by a same-level path, which is a path whose calls all return inside it. A summary edge (c,d4,d5)(c, d_4, d_5) says that a call at cc with the fact d4d_4 can come back at the return site with the fact d5d_5. Summary edges are found once per call site and used by every caller context that reaches the call with the same fact.

  1. TABULATE(G*, F, S) F gives the flow of each edge one fact at a time; S is the seed set
  2. 1PathEdge ← ∅; WorkList ← []; Summary ← ∅; Through ← ∅
  3. 2for each d in S ∪ {0} do PROPAGATE(s_main, d, d)
  4. 3while WorkList is not empty do
  5. 4(n, d1, d2) ← remove the first item of WorkList (n is in procedure p)
  6. 5if n is a call node c, with callee q and return site r then
  7. 6for each d3 in F_call(c)(d2) do PROPAGATE(s_q, d3, d3)
  8. 7for each d3 in F_c2r(c)(d2) ∪ Summary[c, d2] do PROPAGATE(r, d1, d3)
  9. 8else if n is the exit node e_p then
  10. 9for each call node c of p, with return site r, and each d5 in F_ret(c)(d2) do
  11. 10if (c, d1, d5) is in Through then skip it, else add it to Through
  12. 11for each d4 with d1 in F_call(c)(d4) do
  13. 12if d5 is not in Summary[c, d4] then add it
  14. 13for each d3 with (c, d3, d4) in PathEdge do PROPAGATE(r, d3, d5)
  15. 14else for each successor m of n and each d3 in F_(n,m)(d2) do PROPAGATE(m, d1, d3)
  16. 15return X, with X[n] = {d ≠ 0 : (n, d1, d) is in PathEdge for some d1}
  17. PROPAGATE(n, d1, d2)
  18. 16if (n, d1, d2) is not in PathEdge then add it to PathEdge and append it to WorkList

Line L6 starts the callee with a self loop, so the callee is analysed once per entry fact, not once per caller. Line L7 does two things. It carries the caller's facts around the call, and it reuses every summary that is already known. When a fact reaches the exit (L8 to L13), the algorithm turns it into summary edges at every call site of the procedure. It then extends every path edge that already reaches that call with the matching fact.

The set ThroughThrough of line L10 is not in the pseudocode of the paper. Without it, a direct count of the exit case gives D4D^4 steps per call site. Line L13 needs, for each pair (c,d4)(c, d_4), the set of d3d_3 with a path edge to ⟨c,d4⟩\langle c, d_4 \rangle. The implementation keeps this index next to PathEdgePathEdge.

Example

This is the program of the interprocedural dataflow analysis page, in the toy IR. The seed is secret.

id(a):          B0: ret a
main(secret):   B0: x = call id(secret)      c1
                    y = call id(0)           c2, also the return site of c1
                    ret y                    the return site of c2

The worklist is a queue. The steps, with 0\mathbf{0} written as 0:

step item taken new path edges and summary edges
L2 (c1,secret,secret)(c_1, secret, secret), (c1,0,0)(c_1, 0, 0)
1 (c1,secret,secret)(c_1, secret, secret) L6: (sid,a,a)(s_{id}, a, a). L7: (c2,secret,secret)(c_2, secret, secret)
2 (c1,0,0)(c_1, 0, 0) L6: (sid,0,0)(s_{id}, 0, 0). L7: (c2,0,0)(c_2, 0, 0)
3 (sid,a,a)(s_{id}, a, a) L14 through ret a: (eid,a,a)(e_{id}, a, a), (eid,a,RET)(e_{id}, a, RET)
4 (c2,secret,secret)(c_2, secret, secret) L6: none, the argument is a constant. L7: (r2,secret,secret)(r_2, secret, secret)
5, 6 (sid,0,0)(s_{id}, 0, 0), (c2,0,0)(c_2, 0, 0) (eid,0,0)(e_{id}, 0, 0), (r2,0,0)(r_2, 0, 0)
7 (eid,a,a)(e_{id}, a, a) none: the return edge passes only RETRET
8 (eid,a,RET)(e_{id}, a, RET) at c1c_1: RETRET gives x, and aa came from secret. Summary (c1,secret,x)(c_1, secret, x), path edge (c2,secret,x)(c_2, secret, x). At c2c_2: no fact of main gives aa, so no summary
9, 10 (r2,secret,secret)(r_2, secret, secret), (eid,0,0)(e_{id}, 0, 0) (emain,secret,secret)(e_{main}, secret, secret); summaries (c1,0,0)(c_1, 0, 0) and (c2,0,0)(c_2, 0, 0)
11 to 16 the rest (r2,secret,x)(r_2, secret, x) from L7 at c2c_2, then the exit of main

In total there are 16 path edges, 3 summary edges and 24 flow steps.

The result is {secret,x}\{secret, x\} after each call, and y is never tainted. A context-insensitive analysis of the same supergraph lets RET flow from the exit of id to both return sites, so it reports y as tainted. The tabulation avoids this. A summary edge exists only at a call site whose own arguments reach the fact at the entry of id.

Correctness

The full proof is in the proof file. Its steps:

  1. One path, many facts. Following a path π\pi of the supergraph through the exploded graph from X∪{0}X \cup \{\mathbf{0}\} reaches exactly fπ(X)∪{0}f_\pi(X) \cup \{\mathbf{0}\}. The proof is an induction on the length of π\pi.
  2. MVP is reachability. Valid paths of G#G^\# are the valid paths of G∗G^* with a fact at each node. So d∈MVP(n)d \in \mathrm{MVP}(n) exactly when a valid path reaches ⟨n,d⟩\langle n, d \rangle from a seed or from ⟨smain,0⟩\langle s_{main}, \mathbf{0} \rangle.
  3. Path edges and summary edges are sound. Each insertion extends a path that already exists by one edge or by a summary edge, and each summary edge is a call edge, a same-level path in the callee and the return edge of the same call site. The proof is an induction on the order of insertion.
  4. Path edges are complete. Every valid path to ⟨n,d2⟩\langle n, d_2 \rangle ends with a same-level part that starts at some ⟨sp,d1⟩\langle s_p, d_1 \rangle, and (n,d1,d2)(n, d_1, d_2) is found. The proof is an induction on the length of the path. The hard case ends with a return edge. Then the summary edge is found at the exit, and it meets the path edge at the call either at L7 or at L13, whichever runs later.
  5. The result. Steps 3 and 4 show that the targets of the path edges are exactly the reachable nodes of G#G^\#. With step 2 this gives X=MVPX = \mathrm{MVP}.
  6. Termination and cost. Each path edge enters the worklist once, and there are at most (D+1)2(D+1)^2 per node. The cost bound counts the work of each kind of node.
Proof: The tabulation algorithm computes the meet over all valid paths in O(E D^3) timefull

Setting. G∗G^* is the supergraph of the program, as on the page. Every procedure pp has a start node sps_p and an exit node epe_p. A call site has a call node cc and a return site rr, and three edges: the call edge c→sqc \to s_q, the return edge eq→re_q \to r and the intraprocedural call-to-return edge c→rc \to r. The facts of pp form a finite set DpD_p, and D=max⁡p∣Dp∣D = \max_p |D_p|. 0\mathbf{0} is a new fact that is in no DpD_p. Every edge ee of G∗G^* has a flow function, given pointwise as a map FeF_e from Dsrc∪{0}D_{src} \cup \{\mathbf{0}\} to subsets of Ddst∪{0}D_{dst} \cup \{\mathbf{0}\} with 0∈Fe(0)\mathbf{0} \in F_e(\mathbf{0}) and 0∉Fe(d)\mathbf{0} \notin F_e(d) for d≠0d \ne \mathbf{0}. It stands for the function

fe(X)=⋃d∈X∪{0}Fe(d)∖{0}.f_e(X) = \bigcup_{d \in X \cup \{\mathbf{0}\}} F_e(d) \setminus \{\mathbf{0}\}.

These functions are exactly the functions with f(X∪Y)=f(X)∪f(Y)f(X \cup Y) = f(X) \cup f(Y): given such an ff, take F(0)=f(∅)∪{0}F(\mathbf{0}) = f(\emptyset) \cup \{\mathbf{0}\} and F(d)=f({d})F(d) = f(\{d\}). For a path π=e1…ek\pi = e_1 \dots e_k, fπ=fek∘⋯∘fe1f_\pi = f_{e_k} \circ \dots \circ f_{e_1}, and the empty path gives the identity. S⊆DmainS \subseteq D_{main} is the set of seed facts at smains_{main}.

A path of G∗G^* is valid if its call and return edges, read as brackets (c(_c and )c)_c, form a prefix of a word in which every )c)_c closes the last open (c(_c. A path is same-level if it is valid and every (c(_c is closed in it. A same-level path starts and ends in the same procedure. The meet over all valid paths is

MVP(n)=⋃{fπ(S):π a valid path from smain to n}.\mathrm{MVP}(n) = \bigcup \{ f_\pi(S) : \pi \text{ a valid path from } s_{main} \text{ to } n \}.

Sets of facts are ordered by ⊇\supseteq, so union is the meet and ∅\emptyset is ⊤\top, as in Kildall's convention. In Cousot's join convention the order flips and the same set is the least solution.

The exploded supergraph G#G^\# has a node ⟨n,d⟩\langle n, d \rangle for every node nn of G∗G^* in procedure pp and every d∈Dp∪{0}d \in D_p \cup \{\mathbf{0}\}. For every edge e=(n,m)e = (n, m) of G∗G^* and every d′∈Fe(d)d' \in F_e(d), it has the edge ⟨n,d⟩→⟨m,d′⟩\langle n, d \rangle \to \langle m, d' \rangle of the same kind as ee. Valid and same-level paths of G#G^\# are defined by the same brackets.

We use the lines L1 to L16 of the pseudocode. A path edge (n,d1,d2)(n, d_1, d_2) stands for ⟨sp,d1⟩→⟨n,d2⟩\langle s_p, d_1 \rangle \to \langle n, d_2 \rangle, where pp is the procedure of nn. A summary edge (c,d4,d5)(c, d_4, d_5) stands for ⟨c,d4⟩→⟨r,d5⟩\langle c, d_4 \rangle \to \langle r, d_5 \rangle. Through\mathit{Through} is the set of triples of line L10, and invc(d1)={d4:d1∈Fc(d4)}\mathit{inv}_c(d_1) = \{ d_4 : d_1 \in F_c(d_4) \} for the call edge of cc.

Lemma 1 (one path, many facts). For a path π\pi of G∗G^* from nn to mm and a set XX, the facts d′d' such that G#G^\# has a path that follows π\pi from some ⟨n,d⟩\langle n, d \rangle with d∈X∪{0}d \in X \cup \{\mathbf{0}\} to ⟨m,d′⟩\langle m, d' \rangle are exactly fπ(X)∪{0}f_\pi(X) \cup \{\mathbf{0}\}.

Proof. Induction on the length kk of π\pi. For k=0k = 0 both sides are X∪{0}X \cup \{\mathbf{0}\}. Let π=π′e\pi = \pi' e. By induction, the facts reached after π′\pi' are Y∪{0}Y \cup \{\mathbf{0}\} with Y=fπ′(X)Y = f_{\pi'}(X). One more edge reaches ⋃d∈Y∪{0}Fe(d)\bigcup_{d \in Y \cup \{\mathbf{0}\}} F_e(d). This contains 0\mathbf{0}, because 0∈Fe(0)\mathbf{0} \in F_e(\mathbf{0}), and without 0\mathbf{0} it is fe(Y)f_e(Y). So it is fe(Y)∪{0}=fπ(X)∪{0}f_e(Y) \cup \{\mathbf{0}\} = f_\pi(X) \cup \{\mathbf{0}\}. □\square

A path of G#G^\# is valid exactly when its shadow in G∗G^* is valid, since the brackets are the same. So Lemma 1 gives:

Corollary 2 (MVP is reachability). Let Reach\mathit{Reach} be the set of nodes of G#G^\# that a valid path reaches from some ⟨smain,d0⟩\langle s_{main}, d_0 \rangle with d0∈S∪{0}d_0 \in S \cup \{\mathbf{0}\}. Then for every d≠0d \ne \mathbf{0}, d∈MVP(n)d \in \mathrm{MVP}(n) if and only if ⟨n,d⟩∈Reach\langle n, d \rangle \in \mathit{Reach}.

Decomposition. Cut a valid path π\pi of G#G^\# from ⟨smain,d0⟩\langle s_{main}, d_0 \rangle at its call edges that are never closed. The part after the last such call edge (or all of π\pi, if there is none) is a same-level path. It starts at ⟨sp,d1⟩\langle s_p, d_1 \rangle, where pp is the procedure of the end of π\pi, and d1d_1 is d0d_0 or the target fact of that call edge. We call d1d_1 the entry fact of π\pi.

Let PE\mathit{PE} be the set of path edges at the end and SE\mathit{SE} the set of summary edges at the end.

Lemma 3 (path edges are sound). Every path edge (n,d1,d2)(n, d_1, d_2) that L16 inserts has a valid path of G#G^\# from some ⟨smain,d0⟩\langle s_{main}, d_0 \rangle, d0∈S∪{0}d_0 \in S \cup \{\mathbf{0}\}, to ⟨n,d2⟩\langle n, d_2 \rangle whose entry fact is d1d_1. Every summary edge (c,d4,d5)(c, d_4, d_5) that L12 inserts has a same-level path ⟨c,d4⟩→⟨sq,d1⟩⇝⟨eq,d2⟩→⟨r,d5⟩\langle c, d_4 \rangle \to \langle s_q, d_1 \rangle \leadsto \langle e_q, d_2 \rangle \to \langle r, d_5 \rangle in G#G^\#.

Proof. Induction on the order of insertion. The claim for a path edge says: ⟨sp,d1⟩\langle s_p, d_1 \rangle is reached by a valid path α\alpha that is empty or ends with a call edge that is never closed, and a same-level path σ\sigma goes from ⟨sp,d1⟩\langle s_p, d_1 \rangle to ⟨n,d2⟩\langle n, d_2 \rangle.

  • L2 inserts (smain,d,d)(s_{main}, d, d) with d∈S∪{0}d \in S \cup \{\mathbf{0}\}. Take the empty path.
  • L6 inserts (sq,d3,d3)(s_q, d_3, d_3) while it handles a path edge (c,d1,d2)(c, d_1, d_2), with d3∈Fc(d2)d_3 \in F_c(d_2) for the call edge. By induction, ασ\alpha \sigma reaches ⟨c,d2⟩\langle c, d_2 \rangle. Add the call edge. It is never closed, so it is the last open call, and the new entry fact is d3d_3. σ\sigma is now empty.
  • L7 extends σ\sigma for (c,d1,d2)(c, d_1, d_2) by the call-to-return edge, which is intraprocedural, or by a summary edge from ⟨c,d2⟩\langle c, d_2 \rangle. By induction, the summary edge stands for a same-level path. Either way σ\sigma stays same-level and the entry fact stays d1d_1.
  • L14 extends σ\sigma by one intraprocedural edge.
  • L13 inserts (r,d3,d5)(r, d_3, d_5) from a path edge (c,d3,d4)(c, d_3, d_4) and a new summary edge (c,d4,d5)(c, d_4, d_5). Both are older, and the same argument as for L7 applies.
  • L12 inserts (c,d4,d5)(c, d_4, d_5) when L10 meets a new triple (c,d1,d5)(c, d_1, d_5). At that time a path edge (eq,d1,d2)(e_q, d_1, d_2) exists with d5∈F(d2)d_5 \in F(d_2) for the return edge of cc, and L11 chose d4d_4 with d1∈F(d4)d_1 \in F(d_4) for the call edge of cc. By induction, σ\sigma for this path edge is a same-level path from ⟨sq,d1⟩\langle s_q, d_1 \rangle to ⟨eq,d2⟩\langle e_q, d_2 \rangle. The call edge, σ\sigma and the return edge of the same site cc form a same-level path. □\square

Lemma 4 (path edges are complete). If a valid path π\pi of G#G^\# goes from some ⟨smain,d0⟩\langle s_{main}, d_0 \rangle, d0∈S∪{0}d_0 \in S \cup \{\mathbf{0}\}, to ⟨n,d2⟩\langle n, d_2 \rangle and has the entry fact d1d_1, then (n,d1,d2)∈PE(n, d_1, d_2) \in \mathit{PE}.

Proof. Strong induction on the number of edges of π\pi. Every path edge that L16 inserts is put on the worklist, and the loop runs until the worklist is empty (L3). So every path edge in PE\mathit{PE} is taken off once, at L4.

  • π\pi is empty. Then n=smainn = s_{main} and d1=d2=d0d_1 = d_2 = d_0, and L2 inserts the edge.

  • The last edge is a call edge from ⟨c,d4⟩\langle c, d_4 \rangle. The prefix is shorter and reaches ⟨c,d4⟩\langle c, d_4 \rangle with some entry fact d′d', so (c,d′,d4)∈PE(c, d', d_4) \in \mathit{PE}. When it is taken off, L6 inserts (sq,d2,d2)(s_q, d_2, d_2), and d1=d2d_1 = d_2.

  • The last edge is intraprocedural, from ⟨m,d′⟩\langle m, d' \rangle. The prefix is shorter and has the same entry fact d1d_1, so (m,d1,d′)∈PE(m, d_1, d') \in \mathit{PE}. When it is taken off, L14 or (for a call-to-return edge) L7 inserts (n,d1,d2)(n, d_1, d_2).

  • The last edge is a return edge ⟨eq,d2′⟩→⟨r,d2⟩\langle e_q, d_2' \rangle \to \langle r, d_2 \rangle of a call site cc. It must close an open call edge ⟨c,d4⟩→⟨sq,d1′⟩\langle c, d_4 \rangle \to \langle s_q, d_1' \rangle, so π=α⋅call⋅β⋅ret\pi = \alpha \cdot \mathit{call} \cdot \beta \cdot \mathit{ret} with β\beta same-level. The path α⋅call⋅β\alpha \cdot \mathit{call} \cdot \beta is shorter and has the entry fact d1′d_1', so (eq,d1′,d2′)∈PE(e_q, d_1', d_2') \in \mathit{PE}. The path α\alpha is shorter and has the entry fact d1d_1, since call⋅β⋅ret\mathit{call} \cdot \beta \cdot \mathit{ret} is same-level. So (c,d1,d4)∈PE(c, d_1, d_4) \in \mathit{PE}.

    First, (c,d4,d2)∈SE(c, d_4, d_2) \in \mathit{SE}. When (eq,d1′,d2′)(e_q, d_1', d_2') is taken off, L9 looks at the site cc and at d2∈F(d2′)d_2 \in F(d_2') for its return edge. If the triple (c,d1′,d2)(c, d_1', d_2) is new, L11 runs over invc(d1′)\mathit{inv}_c(d_1'), which contains d4d_4, and L12 inserts (c,d4,d2)(c, d_4, d_2) unless it is there already. If the triple is old, the run of L11 that added it did the same.

    Next, the path edge (c,d1,d4)(c, d_1, d_4) was inserted at some time t1t_1 and taken off at a later time t2t_2. The summary edge (c,d4,d2)(c, d_4, d_2) was inserted at a time tst_s. If ts<t2t_s < t_2, L7 sees the summary edge at t2t_2. If ts>t1t_s > t_1, then d1d_1 is among the sources of ⟨c,d4⟩\langle c, d_4 \rangle at tst_s, and L13 uses it. One of the two holds, since t1<t2t_1 < t_2. Either way (r,d1,d2)(r, d_1, d_2) is inserted. □\square

Theorem (correctness). At the end, for every node nn, the set XnX_n of line L15 is MVP(n)\mathrm{MVP}(n).

Proof. By Lemma 3, every path edge (n,d1,d2)(n, d_1, d_2) gives a valid path to ⟨n,d2⟩\langle n, d_2 \rangle, so ⟨n,d2⟩∈Reach\langle n, d_2 \rangle \in \mathit{Reach}. By the decomposition, every node of Reach\mathit{Reach} has a valid path with some entry fact, and Lemma 4 gives a path edge to it. So {⟨n,d⟩:(n,d1,d)∈PE for some d1}=Reach\{ \langle n, d \rangle : (n, d_1, d) \in \mathit{PE} \text{ for some } d_1 \} = \mathit{Reach}. Leave out 0\mathbf{0} and use Corollary 2. □\square

Lemma 5 (termination). The algorithm stops.

Proof. L16 inserts each path edge at most once, and there are at most (D+1)2(D+1)^2 of them per node. So the loop of L3 runs at most ∑n(Dp(n)+1)2\sum_n (D_{p(n)}+1)^2 times. Each run does a finite amount of work, since each set it loops over is finite. □\square

Theorem (cost). Let NN be the number of nodes of G∗G^*, EE its number of edges, and Call\mathit{Call} the number of call sites. With hash sets of constant expected cost per operation, the algorithm runs in O(ED3)O(E D^3) time and uses O(ND2+Call D2)O(N D^2 + \mathit{Call}\, D^2) space.

Proof. Write D′=D+1D' = D + 1. Each PROPAGATE is O(1)O(1). Count the work by the kind of node that the taken-off path edge ends in. A node has at most D′2D'^2 path edges ending in it, and each is taken off once.

  • An ordinary node nn with deg⁡(n)\deg(n) successors. Each path edge gives at most deg⁡(n)⋅D′\deg(n) \cdot D' calls of PROPAGATE at L14. In total D′3deg⁡(n)D'^3 \deg(n). The sum over all nodes is at most ED′3E D'^3.
  • A call node cc. Each path edge gives at most D′D' calls at L6, D′D' at L7 for the call-to-return edge, and D′D' at L7 for the summary edges, since SE\mathit{SE} has at most D′D' edges out of ⟨c,d2⟩\langle c, d_2 \rangle. In total 3D′33 D'^3 per call site.
  • An exit node eqe_q. Each path edge and each call site cc of qq give at most D′D' tests at L10. In total D′3D'^3 per call site, since each call site calls one procedure. A triple (c,d1,d5)(c, d_1, d_5) passes L10 only once, there are at most D′2D'^2 of them per site, and each runs L11 over at most D′D' facts: D′3D'^3 per site. A summary edge is inserted at L12 only once, there are at most D′2D'^2 per site, and each runs L13 over at most D′D' sources: D′3D'^3 per site.

The set invc\mathit{inv}_c takes O(D′2)O(D'^2) time per site to build. A call site has three edges in EE, so Call≤E\mathit{Call} \le E, and the total is O(ED′3)=O(ED3)O(E D'^3) = O(E D^3), since D≥1D \ge 1. The path edges and their index of sources take O(ND′2)O(N D'^2) space. The summary edges, the triples and the sets invc\mathit{inv}_c take O(D′2)O(D'^2) per call site. □\square

Without L10, the exit case would combine every path edge of eqe_q with every d4∈invc(d1)d_4 \in \mathit{inv}_c(d_1) and every source of ⟨c,d4⟩\langle c, d_4 \rangle. That is D′4D'^4 steps per call site in the worst case. The set of triples is what keeps this case at D′3D'^3.

Complexity

  • Ordinary nodes. A node has at most (D+1)2(D+1)^2 path edges. Each is taken once and gives at most D+1D + 1 new items per outgoing edge. Over all nodes this is O(ED3)O(E D^3).
  • Call nodes. Each path edge gives at most 3(D+1)3(D+1) items at L6 and L7, so O(D3)O(D^3) per call site.
  • Exit nodes. Each path edge gives at most D+1D + 1 tests at L10 per call site. Each new triple of ThroughThrough runs over at most D+1D + 1 facts at L11, and each new summary edge over at most D+1D + 1 sources at L13. Each of these costs O(D3)O(D^3) per call site.
  • Total. O(ED3)O(E D^3) time with hash sets. Space is O(ND2)O(N D^2) for the path edges and O(CD2)O(C D^2) for the summary edges, where CC is the number of call sites.
  • Special cases. Reps, Horwitz and Sagiv also give smaller bounds for special classes. For a gen-kill problem every fact flows only to itself, so a node has O(D)O(D) path edges, and the time is O(ED)O(E D). A flow function where each fact reaches only a few facts also costs less than D3D^3 per edge.
  • Best case. Building the supergraph reads the whole program, Θ(N+E)\Theta(N + E), even when only the fact 0\mathbf{0} is ever reached.

The tables below are measured, not proved. The first has random modules of the toy IR with loops and recursion. f0 calls f1, each fi calls f(i+1) and one random procedure, and the seeds are both parameters of f0.

procedures variables NN EE DD path edges summary edges flow steps E(D+1)3E (D+1)^3 ms
4 4 133 155 15 413 8 466 634880 0.6
16 4 517 605 15 1785 46 2047 2478080 3.2
64 4 2036 2401 15 6155 161 7153 9834496 8.2
64 8 2321 2696 19 2546 128 3195 21568000 3.7
64 16 2752 3111 27 2917 128 3543 68292672 4.5

The taint dies quickly in these programs, because constants and loop counters overwrite it. So the work grows with the program and stays far below the bound. The second table is a worst case for the number of path edges. A procedure g with kk parameters mixes all of them in a loop, so every entry fact reaches every variable. main calls g twice.

kk NN EE DD path edges N(D+1)2N (D+1)^2 flow steps E(D+1)3E (D+1)^3 ms
4 12 15 5 167 432 217 3240 0.3
8 16 19 9 811 1600 937 19000 1.0
16 24 27 17 5075 7776 5449 157464 5.4
32 40 43 33 36259 46240 37513 1690072 39.1

Here the path edges come close to N(D+1)2N (D+1)^2. The flow steps stay near the number of path edges, because a taint flow sends each fact to at most two facts. A problem whose flow functions send one fact to many facts pays the full factor DD on top.

Properties

  • Exact. For a distributive problem the result is the meet over all valid paths, with and without recursion. Context-insensitive analysis can only be less precise.
  • Order free. The set of path edges at the end does not depend on the order of the worklist.
  • Per fact. Facts are tracked one at a time. The seeds S∪TS \cup T give the union of the results for SS and for TT.
  • Reuse. A procedure is analysed once per entry fact, and its summary edges serve every caller that reaches the call with that fact.
  • Only what is reached. Procedures and facts that no valid path reaches cost nothing beyond building the supergraph.

Variants and improvements

  • IDE. The IDE framework puts a function on values on each exploded edge. It solves environment problems such as linear constant propagation in the same time bound.
  • Practical extensions. Naeem, Lhoták and Rodriguez build the supergraph on demand, return from the start procedure to all callers when a seed is not in main, and avoid repeated work for facts that pass into a callee.
  • Solvers. Heros (Bodden 2012) is a generic multi-threaded solver for IFDS and IDE on Soot. FlowDroid (Arzt et al. 2014) runs taint analysis of Android apps as an IFDS problem, with access paths such as x.f.g as facts, and adds an alias search on demand.
  • Demand queries. A query for one node and one fact can run the reachability backwards from that node, so only the part of the graph that can matter is explored.
  • Other forms. The same problems are CFL-reachability problems over the language of matched calls and returns, see CFL-reachability. They are also reachability in a pushdown system, and Datalog programs can express the tabulation directly.

When to use it

Use IFDS when the facts are a finite set that you can list per procedure, every flow function is a union of effects of single facts, and you need precision across calls. Taint and information flow, uninitialized variables, interprocedural reaching definitions, and typestate with a small set of states are typical. If you need values, such as constants, use IDE. If the flow functions are not distributive, a functional approach with general summaries or context sensitivity with call strings is the choice.

Pitfalls

  • Large fact sets. The bound has D3D^3, and DD can be large. With access paths as facts, the number of facts grows quickly, so tools cut access paths at a fixed length.
  • No 0\mathbf{0}. Without the fact 0\mathbf{0}, a fact that a statement makes from nothing never appears. Every edge must also map 0\mathbf{0} to 0\mathbf{0}, or whole regions of the graph go missing.
  • Locals through the callee. The caller's locals belong on the call-to-return edge. If the call edge passes them into the callee, every callee must carry every caller local back, which costs more and can lose precision.
  • Facts that need two inputs. A distributive function treats each fact alone. "x is constant if a and b are constant" needs two facts at once, and IFDS cannot express it. IDE cannot either, since x = a + b is not distributive over its value lattice and IDE sends x to ⊥\bot. Use a non-distributive method.
  • Seeds outside main. If the analysis starts inside a procedure, the facts at its exit must return to every caller, with no matching call. Forgetting this loses results.
  • Data flow only. The taint instance here does not follow branches. A secret that only decides which constant is stored does not taint the result.

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.

ifds_framework.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ifds-framework/. The authors are listed in prov/K1QASX.jsonl.
"""The IFDS tabulation algorithm of Reps, Horwitz and Sagiv on the toy IR.

A module is a dict from procedure name to toyir.Program. Calls are
("call", x, f, args) instructions. The supergraph has one node per
instruction and one per terminator, as (proc, label, i), where i is the
index of the instruction in its block and i = len(instrs) is the
terminator. Each procedure also has an exit node (proc, EXIT, 0). A call
node c has three edges: to the start of the callee, from the exit of the
callee to the return site (the next node), and the call-to-return edge.

The problem solved here is "which variables may depend on the secret
inputs" (a taint analysis that follows data flow, not branches). It is a
distributive subset problem. The facts of a procedure are its variables
and the slot RET for its return value. ZERO is the extra fact that is
always present; it is the Lambda of the exploded supergraph.

ifds() returns, for every node, the set of facts that hold there on some
valid path from the start of main, and a Counter of the work done.
"""

from collections import Counter, deque

import toyir

ZERO = "0"
RET = "RET"
EXIT = "$exit"


class Supergraph:
    """The supergraph of a module and the flow functions of the problem."""

    def __init__(self, module, main=None):
        self.module = module
        self.main = main if main is not None else next(iter(module))
        self.facts = {}
        self.start = {}
        self.exit = {}
        self.succ = {}
        self.callee = {}
        self.ret_site = {}
        self.callers = {p: [] for p in module}
        self.nodes = []
        self.proc = {}
        for p, prog in module.items():
            names = set(prog.params)
            for label, blk in prog.blocks.items():
                for i, ins in enumerate(blk.instrs):
                    if ins[0] not in ("const", "copy", "op", "call"):
                        raise ValueError("unsupported instruction: %r" % (ins,))
                    names.add(ins[1])
                    names.update(toyir.uses(ins))
                    node = (p, label, i)
                    self.nodes.append(node)
                    if ins[0] == "call":
                        q = ins[2]
                        if q not in module:
                            raise ValueError("unknown procedure %r" % q)
                        if len(ins[3]) != len(module[q].params):
                            raise ValueError("wrong number of arguments for %r" % q)
                        self.callee[node] = q
                        self.ret_site[node] = (p, label, i + 1)
                        self.callers[q].append(node)
                    else:
                        self.succ[node] = [(p, label, i + 1)]
                names.update(toyir.term_uses(blk.term))
                tnode = (p, label, len(blk.instrs))
                self.nodes.append(tnode)
                if blk.term[0] == "ret":
                    self.succ[tnode] = [(p, EXIT, 0)]
                else:
                    self.succ[tnode] = [(p, s, 0) for s in toyir.succs(prog, label)]
            if RET in names or ZERO in names:
                raise ValueError("reserved name used as a variable")
            self.facts[p] = sorted(names) + [RET]
            self.start[p] = (p, prog.entry, 0)
            self.exit[p] = (p, EXIT, 0)
            self.nodes.append(self.exit[p])
            self.succ[self.exit[p]] = []
        for n in self.nodes:
            self.proc[n] = n[0]

    def num_edges(self):
        """Edges of the supergraph: three per call site, the rest one each."""
        return sum(len(v) for v in self.succ.values()) + 3 * len(self.callee)

    def instr(self, n):
        p, label, i = n
        blk = self.module[p].blocks[label]
        return blk.instrs[i] if i < len(blk.instrs) else blk.term

    def normal_flow(self, n, m, d):
        """The facts at m that the fact d at n gives, for an edge n -> m that
        is not a call edge (the successor m does not change the result)."""
        if d == ZERO:
            return (ZERO,)
        ins = self.instr(n)
        k = ins[0]
        if k == "jump" or k == "br":
            return (d,)
        if k == "ret":
            return (d, RET) if d == ins[1] else (d,)
        x = ins[1]
        if k == "const":
            srcs = ()
        elif k == "copy":
            srcs = (ins[2],)
        else:
            srcs = (ins[3], ins[4])
        out = []
        if d != x:
            out.append(d)
        if d in srcs:
            out.append(x)
        return tuple(out)

    def call_flow(self, c, d):
        """From the fact d before the call c to the facts at the callee start."""
        if d == ZERO:
            return (ZERO,)
        ins = self.instr(c)
        params = self.module[ins[2]].params
        return tuple(params[j] for j, a in enumerate(ins[3]) if a == d)

    def c2r_flow(self, c, d):
        """The call-to-return edge: the caller's facts, minus the target."""
        if d == ZERO:
            return (ZERO,)
        return () if d == self.instr(c)[1] else (d,)

    def ret_flow(self, c, d):
        """From the fact d at the callee exit to the facts at the return site."""
        if d == ZERO:
            return (ZERO,)
        return (self.instr(c)[1],) if d == RET else ()


def ifds(sg, seeds=None):
    """Run the tabulation algorithm. seeds are the facts at the start of
    main; the default is the first parameter of main. Returns (X, stats)."""
    main = sg.main
    if seeds is None:
        seeds = [sg.module[main].params[0]]
    stats = Counter()
    path = set()  # @line L1
    sources = {}  # (n, d2) -> the set of d1 with a path edge <s_p,d1> -> <n,d2>
    summary = {}  # (c, d4) -> the set of d5 with a summary edge <c,d4> -> <r,d5>
    through = set()  # (c, d1, d5): <s_q,d1> reaches <e_q,d2> and d5 is in ret_c(d2)
    inv_call = {}  # c -> d1 -> the d4 with d1 in call_c(d4)
    for c in sg.callee:
        inv = {}
        for d4 in sg.facts[sg.proc[c]] + [ZERO]:
            for d1 in sg.call_flow(c, d4):
                inv.setdefault(d1, []).append(d4)
        inv_call[c] = inv
    work = deque()

    def propagate(d1, n, d2):
        key = (n, d1, d2)
        if key not in path:  # @line L16
            path.add(key)
            sources.setdefault((n, d2), set()).add(d1)
            work.append(key)
            stats["path_edges"] += 1

    s_main = sg.start[main]
    for d in list(seeds) + [ZERO]:  # @line L2
        propagate(d, s_main, d)
    while work:  # @line L3
        n, d1, d2 = work.popleft()  # @line L4
        stats["pops"] += 1
        p = sg.proc[n]
        if n in sg.callee:  # @line L5
            c, q, r = n, sg.callee[n], sg.ret_site[n]
            for d3 in sg.call_flow(c, d2):  # @line L6
                stats["flow"] += 1
                propagate(d3, sg.start[q], d3)
            for d3 in sg.c2r_flow(c, d2):  # @line L7
                stats["flow"] += 1
                propagate(d1, r, d3)
            for d3 in list(summary.get((c, d2), ())):
                stats["flow"] += 1
                propagate(d1, r, d3)
        elif n == sg.exit[p]:  # @line L8
            for c in sg.callers[p]:  # @line L9
                r = sg.ret_site[c]
                for d5 in sg.ret_flow(c, d2):
                    stats["flow"] += 1
                    if (c, d1, d5) in through:  # @line L10
                        continue
                    through.add((c, d1, d5))
                    for d4 in inv_call[c].get(d1, ()):  # @line L11
                        stats["flow"] += 1
                        sset = summary.setdefault((c, d4), set())
                        if d5 in sset:
                            continue
                        sset.add(d5)  # @line L12
                        stats["summary_edges"] += 1
                        for d3 in list(sources.get((c, d4), ())):  # @line L13
                            stats["flow"] += 1
                            propagate(d3, r, d5)
        else:
            for m in sg.succ[n]:  # @line L14
                for d3 in sg.normal_flow(n, m, d2):
                    stats["flow"] += 1
                    propagate(d1, m, d3)
    X = {n: set() for n in sg.nodes}  # @line L15
    for n, _d1, d2 in path:
        if d2 != ZERO:
            X[n].add(d2)
    return X, stats


def ifds_framework(module, main=None, seeds=None):
    """Convenience wrapper: the facts at every node of the module."""
    sg = Supergraph(module, main)
    X, _ = ifds(sg, seeds)
    return X
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.

A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:

    ("const", x, k)          x = k
    ("copy", x, a)           x = y
    ("op", x, op, a, b)      x = a op b
    ("phi", x, {pred: a})    x = phi [pred: a, ...]
    ("addr", p, x)           p = &x
    ("load", x, p)           x = *p
    ("store", p, a)          *p = a
    ("alloc", p)             p = alloc
    ("call", x, f, args)     x = call f(a, b)   (args is a list)

Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""

from dataclasses import dataclass, field
import re

OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")


@dataclass
class Block:
    instrs: list = field(default_factory=list)
    term: tuple = ("ret", 0)


@dataclass
class Program:
    params: list
    blocks: dict

    @property
    def entry(self):
        return next(iter(self.blocks))


class UndefinedName(Exception):
    """A name was read before any definition."""


# ---------------------------------------------------------------- text form

_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"


def _operand(tok):
    if re.fullmatch(_INT, tok):
        return int(tok)
    if re.fullmatch(_NAME, tok):
        return tok
    raise ValueError("bad operand: %r" % tok)


def _name(tok):
    if not re.fullmatch(_NAME, tok):
        raise ValueError("bad name: %r" % tok)
    return tok


def _parse_instr(line):
    toks = line.split()
    if toks[0] == "jump" and len(toks) == 2:
        return "term", ("jump", _name(toks[1]))
    if toks[0] == "br" and len(toks) == 4:
        return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
    if toks[0] == "ret" and len(toks) == 2:
        return "term", ("ret", _operand(toks[1]))
    lhs, eq, rhs = line.partition("=")
    if not eq:
        raise ValueError("bad line: %r" % line)
    lhs, rhs = lhs.strip(), rhs.strip()
    if lhs.startswith("*"):
        return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
    x = _name(lhs)
    if rhs.startswith("phi"):
        body = rhs[3:].strip()
        if not (body.startswith("[") and body.endswith("]")):
            raise ValueError("bad phi: %r" % line)
        args = {}
        inner = body[1:-1].strip()
        if inner:
            for part in inner.split(","):
                pred, colon, a = part.partition(":")
                if not colon:
                    raise ValueError("bad phi: %r" % line)
                args[_name(pred.strip())] = _operand(a.strip())
        return "instr", ("phi", x, args)
    if rhs.startswith("call "):
        m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
        if not m:
            raise ValueError("bad call: %r" % line)
        inner = m.group(2).strip()
        args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
        return "instr", ("call", x, m.group(1), args)
    if rhs == "alloc":
        return "instr", ("alloc", x)
    if rhs.startswith("&"):
        return "instr", ("addr", x, _name(rhs[1:].strip()))
    if rhs.startswith("*"):
        return "instr", ("load", x, _name(rhs[1:].strip()))
    parts = rhs.split()
    if len(parts) == 1:
        a = _operand(parts[0])
        if isinstance(a, int):
            return "instr", ("const", x, a)
        return "instr", ("copy", x, a)
    if len(parts) == 3 and parts[1] in OPS:
        return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
    raise ValueError("bad instruction: %r" % line)


def parse(text):
    """Parse the text form. A line "# params: a, b" gives the parameters;
    without it, the parameters are the names that are read and never
    defined, in the order of their first use."""
    params = None
    blocks = {}
    cur = None
    for raw in text.splitlines():
        line = raw.strip()
        if not line:
            continue
        if line.startswith("#"):
            m = re.fullmatch(r"#\s*params:(.*)", line)
            if m:
                inner = m.group(1).strip()
                params = [_name(p.strip()) for p in inner.split(",")] if inner else []
            continue
        if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
            label = line[:-1]
            if label in blocks:
                raise ValueError("duplicate label: %r" % label)
            cur = label
            blocks[label] = Block([], None)
            continue
        if cur is None:
            raise ValueError("instruction outside a block: %r" % line)
        if blocks[cur].term is not None:
            raise ValueError("instruction after the terminator in %r" % cur)
        kind, item = _parse_instr(line)
        if kind == "term":
            blocks[cur].term = item
        else:
            blocks[cur].instrs.append(item)
    for label, b in blocks.items():
        if b.term is None:
            raise ValueError("block %r has no terminator" % label)
    if not blocks:
        raise ValueError("empty program")
    prog = Program([], blocks)
    if params is None:
        params = _free_names(prog)
    prog.params = params
    return prog


def _free_names(prog):
    defined = set()
    for b in prog.blocks.values():
        for ins in b.instrs:
            d = defs(ins)
            if d is not None:
                defined.add(d)
    out = []
    for b in prog.blocks.values():
        for ins in b.instrs:
            for a in uses(ins):
                if a not in defined and a not in out:
                    out.append(a)
        for a in term_uses(b.term):
            if a not in defined and a not in out:
                out.append(a)
    return out


def _show_instr(ins):
    k = ins[0]
    if k == "const":
        return "%s = %d" % (ins[1], ins[2])
    if k == "copy":
        return "%s = %s" % (ins[1], ins[2])
    if k == "op":
        return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
    if k == "phi":
        return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
    if k == "addr":
        return "%s = &%s" % (ins[1], ins[2])
    if k == "load":
        return "%s = *%s" % (ins[1], ins[2])
    if k == "store":
        return "*%s = %s" % (ins[1], ins[2])
    if k == "alloc":
        return "%s = alloc" % ins[1]
    if k == "call":
        return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
    raise ValueError("bad instruction: %r" % (ins,))


def _show_term(t):
    if t[0] == "jump":
        return "jump %s" % t[1]
    if t[0] == "br":
        return "br %s %s %s" % (t[1], t[2], t[3])
    if t[0] == "ret":
        return "ret %s" % (t[1],)
    raise ValueError("bad terminator: %r" % (t,))


def show(prog):
    lines = ["# params: " + ", ".join(prog.params)]
    for label, b in prog.blocks.items():
        lines.append(label + ":")
        for ins in b.instrs:
            lines.append("  " + _show_instr(ins))
        lines.append("  " + _show_term(b.term))
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------- names and graph


def defs(ins):
    """The name an instruction defines, or None for a store."""
    return None if ins[0] == "store" else ins[1]


def uses(ins):
    """The names an instruction reads, in order (phi operands included)."""
    k = ins[0]
    if k == "const" or k == "alloc" or k == "addr":
        ops = []
    elif k == "copy":
        ops = [ins[2]]
    elif k == "op":
        ops = [ins[3], ins[4]]
    elif k == "phi":
        ops = list(ins[2].values())
    elif k == "load":
        ops = [ins[2]]
    elif k == "store":
        ops = [ins[1], ins[2]]
    elif k == "call":
        ops = list(ins[3])
    else:
        raise ValueError("bad instruction: %r" % (ins,))
    return [a for a in ops if isinstance(a, str)]


def term_uses(t):
    if t[0] == "br" or t[0] == "ret":
        return [t[1]] if isinstance(t[1], str) else []
    return []


def succs(prog, label):
    """Successor labels of a block, without repeats, in terminator order."""
    t = prog.blocks[label].term
    if t[0] == "jump":
        return [t[1]]
    if t[0] == "br":
        return [t[2]] if t[2] == t[3] else [t[2], t[3]]
    return []


def edges(prog):
    return [(a, b) for a in prog.blocks for b in succs(prog, a)]


def preds(prog):
    """Dict from label to the list of predecessor labels, in block order."""
    out = {label: [] for label in prog.blocks}
    for a, b in edges(prog):
        out[b].append(a)
    return out


def is_acyclic(prog):
    color = {label: 0 for label in prog.blocks}
    for root in prog.blocks:
        if color[root]:
            continue
        color[root] = 1
        stack = [(root, iter(succs(prog, root)))]
        while stack:
            v, it = stack[-1]
            w = next(it, None)
            if w is None:
                color[v] = 2
                stack.pop()
            elif color[w] == 1:
                return False
            elif color[w] == 0:
                color[w] = 1
                stack.append((w, iter(succs(prog, w))))
    return True


def paths(prog):
    """Every path from the entry to a ret block, as a list of labels.
    The CFG must be acyclic."""
    if not is_acyclic(prog):
        raise ValueError("paths needs an acyclic CFG")
    out = []

    def walk(path):
        last = path[-1]
        s = succs(prog, last)
        if not s:
            out.append(list(path))
        for w in s:
            path.append(w)
            walk(path)
            path.pop()

    walk([prog.entry])
    return out


# ------------------------------------------------------------------ running


class _Trap(Exception):
    pass


class _Fuel(Exception):
    pass


def _binop(op, a, b):
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("arithmetic on a pointer")
    if op == "+":
        return a + b
    if op == "-":
        return a - b
    if op == "*":
        return a * b
    if op == "/" or op == "%":
        if b == 0:
            raise _Trap()
        q = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            q = -q
        return q if op == "/" else a - b * q
    if op == "&":
        return a & b
    if op == "|":
        return a | b
    if op == "^":
        return a ^ b
    if op == "<<" or op == ">>":
        if b < 0 or b > 63:
            raise _Trap()
        return a << b if op == "<<" else a >> b
    if op == "<":
        return int(a < b)
    if op == "<=":
        return int(a <= b)
    if op == "==":
        return int(a == b)
    if op == "!=":
        return int(a != b)
    raise ValueError("bad operator: %r" % op)


class _Frame:
    """One activation: its program, its variables and its position."""

    def __init__(self, prog, args, fid):
        if len(args) != len(prog.params):
            raise ValueError("expected %d arguments" % len(prog.params))
        self.prog = prog
        self.env = dict(zip(prog.params, args))
        self.fid = fid
        self.label = prog.entry
        self.prev = None
        self.pc = 0  # 0 means: the phis of the block have not run yet
        self.dest = None  # the name that receives the value of a pending call

    def val(self, a):
        if isinstance(a, int):
            return a
        if a not in self.env:
            raise UndefinedName(a)
        return self.env[a]


def _run(prog, args, fuel, funcs):
    """Run with an explicit stack of frames, so deep recursion in the toy
    program does not use Python recursion."""
    heap = {}
    envs = {}
    stack = []
    fr = _Frame(prog, args, 0)
    envs[0] = fr.env
    nframes = 1

    def tick():
        nonlocal fuel
        if fuel <= 0:
            raise _Fuel()
        fuel -= 1

    while True:
        block = fr.prog.blocks[fr.label]
        instrs = block.instrs
        if fr.pc == 0:
            # Phis at the top of the block read all operands first, then assign.
            incoming = []
            i = 0
            while i < len(instrs) and instrs[i][0] == "phi":
                tick()
                ins = instrs[i]
                if fr.prev not in ins[2]:
                    raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
                incoming.append((ins[1], fr.val(ins[2][fr.prev])))
                i += 1
            for x, v in incoming:
                fr.env[x] = v
            fr.pc = i if i > 0 else -1
        start = fr.pc if fr.pc > 0 else 0
        called = False
        env = fr.env
        for j in range(start, len(instrs)):
            ins = instrs[j]
            tick()
            k = ins[0]
            if k == "const":
                env[ins[1]] = ins[2]
            elif k == "copy":
                env[ins[1]] = fr.val(ins[2])
            elif k == "op":
                env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
            elif k == "addr":
                env[ins[1]] = ("var", fr.fid, ins[2])
            elif k == "alloc":
                cell = ("heap", len(heap))
                heap[cell] = None
                env[ins[1]] = cell
            elif k == "load":
                p = fr.val(ins[2])
                if p[0] == "var":
                    if p[2] not in envs[p[1]]:
                        raise UndefinedName(p[2])
                    env[ins[1]] = envs[p[1]][p[2]]
                else:
                    if heap[p] is None:
                        raise UndefinedName(repr(p))
                    env[ins[1]] = heap[p]
            elif k == "store":
                p = fr.val(ins[1])
                if p[0] == "var":
                    envs[p[1]][p[2]] = fr.val(ins[2])
                else:
                    heap[p] = fr.val(ins[2])
            elif k == "call":
                if funcs is None or ins[2] not in funcs:
                    raise ValueError("unknown function %r" % ins[2])
                vals = [fr.val(a) for a in ins[3]]
                fr.pc = j + 1
                fr.dest = ins[1]
                stack.append(fr)
                fr = _Frame(funcs[ins[2]], vals, nframes)
                envs[nframes] = fr.env
                nframes += 1
                called = True
                break
            elif k == "phi":
                raise ValueError("phi after a non-phi instruction")
            else:
                raise ValueError("bad instruction: %r" % (ins,))
        if called:
            continue
        tick()
        t = block.term
        if t[0] == "jump" or t[0] == "br":
            if t[0] == "jump":
                nxt = t[1]
            else:
                nxt = t[2] if fr.val(t[1]) != 0 else t[3]
            fr.prev, fr.label, fr.pc = fr.label, nxt, 0
            continue
        v = fr.val(t[1])
        if not stack:
            return ("ret", v), fuel
        fr = stack.pop()
        fr.env[fr.dest] = v


def run(prog, args, fuel=10000, funcs=None):
    """Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
    Each instruction, phi and terminator uses one unit of fuel. funcs is an
    optional dict from function name to Program, used by call; deep
    recursion in the toy program is fine, because the frames are kept on an
    explicit stack."""
    try:
        out, _ = _run(prog, list(args), fuel, funcs)
        return out
    except _Trap:
        return ("trap",)
    except _Fuel:
        return ("fuel",)


# ------------------------------------------------------------ random programs

_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")


def random_program(rng, nvars, nblocks, acyclic):
    """A random program with blocks B0 .. B(nblocks-1) and variables
    x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
    others, so no run reads an undefined name. A division by a variable can
    trap. Every block is reachable from
    B0 and B0 has no predecessor. With acyclic=False, each loop has its own
    counter c that is set to 0 in B0 and never reset, and the back edge is
    taken only while c < m and c < 4, where m is the first parameter. So the
    whole run takes each back edge at most 3 times."""
    nvars = max(nvars, 1)
    nblocks = max(nblocks, 1)
    xs = ["x%d" % i for i in range(nvars)]
    params = xs[:2]
    labels = ["B%d" % i for i in range(nblocks)]

    def operand():
        if rng.random() < 0.25:
            return rng.randint(-3, 9)
        return rng.choice(xs)

    def instr():
        x = rng.choice(xs)
        r = rng.random()
        if r < 0.15:
            return ("const", x, rng.randint(-5, 9))
        if r < 0.25:
            return ("copy", x, rng.choice(xs))
        if r < 0.3:
            # A division by a variable may trap.
            return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
        if r < 0.4:
            op = rng.choice(_CONST_RIGHT)
            k = rng.randint(1, 5)
            return ("op", x, op, rng.choice(xs), k)
        return ("op", x, rng.choice(_SAFE), operand(), operand())

    blocks = {}
    has_pred = [False] * nblocks
    has_pred[0] = True
    for i in range(nblocks):
        instrs = [instr() for _ in range(rng.randint(1, 3))]
        if i == 0:
            instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
        if i == nblocks - 1:
            term = ("ret", rng.choice(xs))
        elif has_pred[i + 1] and rng.random() < 0.2:
            term = ("ret", rng.choice(xs))
        else:
            first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
            if rng.random() < 0.5:
                term = ("jump", labels[first])
                has_pred[first] = True
            else:
                second = rng.randrange(i + 1, nblocks)
                if second == first:
                    term = ("jump", labels[first])
                else:
                    term = ("br", rng.choice(xs), labels[first], labels[second])
                    has_pred[second] = True
                has_pred[first] = True
        blocks[labels[i]] = Block(instrs, term)

    if not acyclic and nblocks > 1:
        nloops = rng.randint(1, max(1, nblocks // 3))
        for k in range(nloops):
            latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
            if not latches:
                break
            t = rng.choice(latches)
            h = labels[rng.randint(1, labels.index(t))]
            c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
            blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
            out = blocks[t].term[1]
            blocks[t].instrs += [
                ("op", c, "+", c, 1),
                ("op", w1, "<", c, m),
                ("op", w2, "<", c, 4),
                ("op", w, "&", w1, w2),
            ]
            blocks[t].term = ("br", w, h, out)
    return Program(list(params), blocks)
test_ifds_framework.py 378 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ifds-framework/. The authors are listed in prov/K1QASX.jsonl.

import random

import toyir
from toyir import parse, random_program
from ifds_framework import EXIT, RET, ZERO, Supergraph, ifds, ifds_framework

# The example of the page: id is called twice, once with the secret and
# once with a constant. Only the first result may depend on the secret.
ID = """
# params: a
B0:
  ret a
"""

MAIN = """
# params: secret
B0:
  x = call id(secret)
  y = call id(0)
  ret y
"""


def id_module():
    return {"main": parse(MAIN), "id": parse(ID)}


# ------------------------------------------------------------ brute force


def apply(fn, facts):
    """Apply a flow function given pointwise to a set of facts. ZERO is
    always in the set, as on every path of the exploded supergraph."""
    out = {ZERO}
    for d in facts:
        out.update(fn(d))
    return frozenset(out)


def mvp_by_paths(sg, seeds, cap=20000, max_depth=None):
    """The meet over all valid paths, by walking every valid path from the
    start of main one by one. A path is a list of nodes; its state is the
    set of facts and the stack of open calls. At a call node the path
    either enters the callee or takes the call-to-return edge. At an exit
    it returns to the call on top of the stack. The result at a node is the
    union of the facts at the node over all paths that reach it. Returns
    None when more than cap steps are needed. With max_depth, calls deeper
    than that are not entered, which gives a subset of the valid paths."""
    M = {n: set() for n in sg.nodes}
    start = (sg.start[sg.main], frozenset(list(seeds) + [ZERO]), ())
    todo = [start]
    steps = 0
    while todo:
        n, facts, stack = todo.pop()
        steps += 1
        if steps > cap:
            return None
        M[n].update(facts)
        if n in sg.callee:
            q = sg.callee[n]
            if max_depth is None or len(stack) < max_depth:
                todo.append((sg.start[q], apply(lambda d: sg.call_flow(n, d), facts), stack + (n,)))
            todo.append((sg.ret_site[n], apply(lambda d: sg.c2r_flow(n, d), facts), stack))
        elif n[1] == EXIT:
            if stack:
                c = stack[-1]
                todo.append((sg.ret_site[c], apply(lambda d: sg.ret_flow(c, d), facts), stack[:-1]))
        else:
            for m in sg.succ[n]:
                todo.append((m, apply(lambda d: sg.normal_flow(n, m, d), facts), stack))
    for n in M:
        M[n].discard(ZERO)
    return M


def mfp_supergraph(sg, seeds):
    """The context-insensitive solution: the supergraph is one big graph,
    and every exit flows back to every caller."""
    IN = {n: set() for n in sg.nodes}
    IN[sg.start[sg.main]] = set(seeds)
    work = list(sg.nodes)
    queued = set(work)

    def add(m, facts):
        if not facts <= IN[m]:
            IN[m] |= facts
            if m not in queued:
                queued.add(m)
                work.append(m)

    while work:
        n = work.pop()
        queued.discard(n)
        X = IN[n]
        if n in sg.callee:
            q = sg.callee[n]
            add(sg.start[q], set(apply(lambda d: sg.call_flow(n, d), X)) - {ZERO})
            add(sg.ret_site[n], set(apply(lambda d: sg.c2r_flow(n, d), X)) - {ZERO})
            out = set(apply(lambda d: sg.ret_flow(n, d), IN[sg.exit[q]])) - {ZERO}
            add(sg.ret_site[n], out)
        elif n[1] == EXIT:
            for c in sg.callers[n[0]]:
                out = set(apply(lambda d: sg.ret_flow(c, d), X)) - {ZERO}
                add(sg.ret_site[c], out)
        else:
            for m in sg.succ[n]:
                add(m, set(apply(lambda d: sg.normal_flow(n, m, d), X)) - {ZERO})
    return IN


# ------------------------------------------------------- tainted execution


class Frame:
    def __init__(self, p, env, taint):
        self.p = p
        self.env = env
        self.taint = taint
        self.label = None
        self.pc = 0
        self.dest = None


def run_tainted(module, main, args, tainted, fuel=3000):
    """Run the module and track which values depend on the tainted
    arguments, following data flow only. Returns the outcome, in the form
    of toyir.run, and the list of (node, tainted facts) seen before each
    node runs. The fuel is counted as in toyir.run."""
    seen = []
    prog = module[main]
    fr = Frame(main, dict(zip(prog.params, args)), {x for x, t in zip(prog.params, tainted) if t})
    fr.label = prog.entry
    stack = []

    def val(fr, a):
        if isinstance(a, int):
            return a, False
        return fr.env[a], a in fr.taint

    def tick():
        nonlocal fuel
        if fuel <= 0:
            raise toyir._Fuel()
        fuel -= 1

    try:
        while True:
            blk = module[fr.p].blocks[fr.label]
            called = False
            while fr.pc < len(blk.instrs):
                ins = blk.instrs[fr.pc]
                seen.append(((fr.p, fr.label, fr.pc), frozenset(fr.taint)))
                tick()
                k, x = ins[0], ins[1]
                if k == "const":
                    v, t = ins[2], False
                elif k == "copy":
                    v, t = val(fr, ins[2])
                elif k == "op":
                    a, ta = val(fr, ins[3])
                    b, tb = val(fr, ins[4])
                    v, t = toyir._binop(ins[2], a, b), ta or tb
                else:
                    vals = [val(fr, a) for a in ins[3]]
                    q = module[ins[2]]
                    fr.dest = x
                    fr.pc += 1
                    stack.append(fr)
                    env = {pn: v for pn, (v, _t) in zip(q.params, vals)}
                    taint = {pn for pn, (_v, t) in zip(q.params, vals) if t}
                    fr = Frame(ins[2], env, taint)
                    fr.label = q.entry
                    called = True
                    break
                fr.env[x] = v
                if t:
                    fr.taint.add(x)
                else:
                    fr.taint.discard(x)
                fr.pc += 1
            if called:
                continue
            seen.append(((fr.p, fr.label, len(blk.instrs)), frozenset(fr.taint)))
            tick()
            term = blk.term
            if term[0] == "jump":
                fr.label, fr.pc = term[1], 0
                continue
            if term[0] == "br":
                v, _t = val(fr, term[1])
                fr.label, fr.pc = (term[2] if v != 0 else term[3]), 0
                continue
            v, t = val(fr, term[1])
            seen.append(((fr.p, EXIT, 0), frozenset(fr.taint | ({RET} if t else set()))))
            if not stack:
                return ("ret", v), seen
            fr = stack.pop()
            fr.env[fr.dest] = v
            if t:
                fr.taint.add(fr.dest)
            else:
                fr.taint.discard(fr.dest)
    except toyir._Trap:
        return ("trap",), seen
    except toyir._Fuel:
        return ("fuel",), seen


# ---------------------------------------------------------- random modules


def random_module(rng, recursive=False):
    """Three procedures f0, f1 and f2 from random_program, with two to four
    calls x = call fj(a, b) added. Without recursion, fi only calls fj with
    j > i. A call in B0 goes after the constants that start B0, so every
    name is defined before it is read."""
    names = ["f0", "f1", "f2"]
    module = {}
    for f in names:
        module[f] = random_program(rng, 4, rng.randint(2, 4), True)
    xs = ["x%d" % i for i in range(4)]
    for _ in range(rng.randint(2, 4)):
        i = rng.randrange(0, 3 if recursive else 2)
        j = rng.randrange(0, 3) if recursive else rng.randrange(i + 1, 3)
        prog = module[names[i]]
        label = rng.choice(list(prog.blocks))
        instrs = prog.blocks[label].instrs
        lo = 2 if label == prog.entry else 0
        pos = rng.randint(lo, len(instrs))
        args = [rng.choice(xs) if rng.random() < 0.85 else rng.randint(0, 5) for _ in range(2)]
        instrs.insert(pos, ("call", rng.choice(xs), names[j], args))
    return module


def bound_checks(sg, stats):
    D1 = max(len(f) for f in sg.facts.values()) + 1
    N = len(sg.nodes)
    E = sg.num_edges()
    assert stats["path_edges"] <= N * D1 * D1
    assert stats["pops"] == stats["path_edges"]
    assert stats["summary_edges"] <= len(sg.callee) * D1 * D1
    assert stats["flow"] <= 3 * E * D1 ** 3


def arg_lists(rng):
    out = [[0, 0], [1, 2], [-3, 7]]
    for _ in range(3):
        out.append([rng.randint(-6, 9), rng.randint(-6, 9)])
    return out


# ------------------------------------------------------------------- tests


def test_id_example() -> None:
    module = id_module()
    sg = Supergraph(module, "main")
    X, stats = ifds(sg)
    assert X[("id", "B0", 0)] == {"a"}
    assert X[("id", EXIT, 0)] == {"a", RET}
    assert X[("main", "B0", 1)] == {"secret", "x"}
    assert X[("main", "B0", 2)] == {"secret", "x"}
    assert X[("main", EXIT, 0)] == {"secret", "x"}
    # The context-insensitive solution leaks the secret into y.
    MFP = mfp_supergraph(sg, ["secret"])
    assert MFP[("main", "B0", 2)] == {"secret", "x", "y"}
    assert MFP[("main", EXIT, 0)] == {"secret", "x", "y", RET}
    assert mvp_by_paths(sg, ["secret"]) == X
    # Summary edges: secret to x and ZERO to ZERO at s1, and only ZERO to
    # ZERO at s2, since the argument of s2 is a constant.
    assert stats["summary_edges"] == 3
    bound_checks(sg, stats)
    assert run_tainted(module, "main", [5], [True])[0] == ("ret", 0)


def test_wrapper_chain() -> None:
    # The secret goes in through two levels of calls and comes back only on
    # the path where it went in.
    inner = parse("# params: a, b\nB0:\n  t = a + 1\n  ret t\n")
    outer = parse("# params: u, v\nB0:\n  r = call inner(u, v)\n  s = call inner(v, u)\n  ret r\n")
    main = parse("# params: p, q\nB0:\n  m = call outer(p, q)\n  n = call outer(q, p)\n  ret n\n")
    module = {"main": main, "outer": outer, "inner": inner}
    X = ifds_framework(module, "main", ["p"])
    assert X[("main", "B0", 1)] == {"p", "m"}
    assert X[("main", EXIT, 0)] == {"p", "m"}
    assert X[("outer", "B0", 1)] == {"u", "v", "r"}
    assert X[("outer", "B0", 2)] == {"u", "v", "r", "s"}
    sg = Supergraph(module, "main")
    assert mvp_by_paths(sg, ["p"]) == X
    MFP = mfp_supergraph(sg, ["p"])
    assert "n" in MFP[("main", EXIT, 0)]


def test_random_acyclic_modules() -> None:
    rng = random.Random(4101)
    compared = strict = runs = 0
    for _ in range(400):
        module = random_module(rng)
        sg = Supergraph(module, "f0")
        X, stats = ifds(sg)
        bound_checks(sg, stats)
        M = mvp_by_paths(sg, ["x0"])
        if M is not None:
            compared += 1
            assert X == M
        MFP = mfp_supergraph(sg, ["x0"])
        assert all(X[n] <= MFP[n] for n in sg.nodes)
        if any(X[n] != MFP[n] for n in sg.nodes):
            strict += 1
        for args in arg_lists(rng):
            out, seen = run_tainted(module, "f0", args, [True, False])
            assert out == toyir.run(module["f0"], args, fuel=3000, funcs=module)
            runs += 1
            for n, t in seen:
                assert t <= X[n], (n, t, X[n])
    assert compared >= 380
    assert strict >= 15
    assert runs == 2400


def test_random_recursive_modules() -> None:
    rng = random.Random(4102)
    for _ in range(150):
        module = random_module(rng, recursive=True)
        sg = Supergraph(module, "f0")
        X, stats = ifds(sg)
        bound_checks(sg, stats)
        MFP = mfp_supergraph(sg, ["x0"])
        assert all(X[n] <= MFP[n] for n in sg.nodes)
        # Valid paths with at most three open calls are a subset of all
        # valid paths, so their union must be inside the result.
        M = mvp_by_paths(sg, ["x0"], cap=20000, max_depth=3)
        if M is not None:
            assert all(M[n] <= X[n] for n in sg.nodes)
        for args in arg_lists(rng):
            out, seen = run_tainted(module, "f0", args, [True, False], fuel=400)
            assert out == toyir.run(module["f0"], args, fuel=400, funcs=module)
            for n, t in seen:
                assert t <= X[n]


def test_seeds_and_zero() -> None:
    # With no seed, nothing is tainted, but ZERO still reaches every node
    # that some valid path reaches.
    module = id_module()
    sg = Supergraph(module, "main")
    X, stats = ifds(sg, seeds=[])
    assert all(not v for v in X.values())
    assert stats["path_edges"] == len(sg.nodes)
    # Both parameters as seeds: the union of the two single-seed results.
    rng = random.Random(4103)
    for _ in range(60):
        module = random_module(rng)
        sg = Supergraph(module, "f0")
        A, _ = ifds(sg, ["x0"])
        B, _ = ifds(sg, ["x1"])
        AB, _ = ifds(sg, ["x0", "x1"])
        assert all(AB[n] == A[n] | B[n] for n in sg.nodes)


def test_bad_input() -> None:
    bad = {"main": parse("# params: a\nB0:\n  x = call nope(a)\n  ret x\n")}
    try:
        Supergraph(bad)
    except ValueError:
        pass
    else:
        raise AssertionError("unknown callee accepted")
    bad = {"main": parse("# params: a\nB0:\n  RET = a\n  ret a\n")}
    try:
        Supergraph(bad)
    except ValueError:
        pass
    else:
        raise AssertionError("reserved name accepted")

History

Sharir and Pnueli (1981) defined the meet over valid paths and the functional approach, which computes the effect of each procedure as a function. Knoop and Steffen (1992) proved the interprocedural coincidence theorem for distributive problems. Horwitz, Reps and Binkley (1990) had already used summary edges at call sites for interprocedural slicing. Reps, Horwitz and Sagiv (POPL 1995) combined these ideas. They noted that a distributive function on a finite set of facts is a small graph, so the functional approach becomes reachability in an exploded supergraph, and they gave the tabulation algorithm with its O(ED3)O(E D^3) bound. Sagiv, Reps and Horwitz (1996) extended it to IDE. Reps (1998) presented both as CFL-reachability. Naeem, Lhoták and Rodriguez (2010) made the algorithm practical for large programs. The Heros solver (2012) and FlowDroid (2014) brought it into wide use for Java and Android.

References

  1. Thomas Reps, Susan Horwitz and Mooly Sagiv, Precise interprocedural dataflow analysis via graph reachability, Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '95), 49 to 61, 1995, the IFDS problem, the exploded supergraph, the tabulation algorithm with path edges and summary edges, and its O(E D^3) bound
  2. Mooly Sagiv, Thomas Reps and Susan Horwitz, Precise interprocedural dataflow analysis with applications to constant propagation, Theoretical Computer Science 167(1-2), 131 to 170, 1996, the IDE generalization, where the edges of the exploded supergraph carry functions on values
  3. Thomas Reps, Program analysis via graph reachability, Information and Software Technology 40(11-12), 701 to 726, 1998, IFDS as an instance of CFL-reachability, and its relation to interprocedural slicing
  4. Susan Horwitz, Thomas Reps and David Binkley, Interprocedural slicing using dependence graphs, ACM Transactions on Programming Languages and Systems 12(1), 26 to 60, 1990, summary edges at call sites, the earlier form of the same idea for slicing
  5. Nomair A. Naeem, Ondřej Lhoták and Jonathan Rodriguez, Practical extensions to the IFDS algorithm, Compiler Construction (CC 2010), Lecture Notes in Computer Science, 124 to 144, 2010, the supergraph built on demand, unbalanced returns, and faster handling of flows into callees
  6. Eric Bodden, Inter-procedural data-flow analysis with IFDS/IDE and Soot, Proceedings of the ACM SIGPLAN International Workshop on State of the Art in Java Program Analysis (SOAP '12), 3 to 8, 2012, the Heros solver, a generic IFDS and IDE solver with multi-threading
  7. Steven Arzt, Siegfried Rasthofer, Christian Fritz, Eric Bodden, Alexandre Bartel, Jacques Klein, Yves Le Traon, Damien Octeau and Patrick McDaniel, FlowDroid: precise context, flow, field, object-sensitive and lifecycle-aware taint analysis for Android apps, Proceedings of the 35th ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '14), 259 to 269, 2014, taint analysis as an IFDS problem with access paths as facts
  8. Micha Sharir and Amir Pnueli, Two approaches to interprocedural data flow analysis, in Steven S. Muchnick and Neil D. Jones (eds.), Program Flow Analysis: Theory and Applications, Prentice-Hall, 1981, the meet over valid paths and the functional approach that the tabulation algorithm makes concrete

Where this leads

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.average
  • a full proof of time.best
  • 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
  • History with a source
  • a scene preset for the example