Algorithm Search⌘K

Algorithmadvanced

Interprocedural constant propagation

Also called jump function constant propagation.

Finds parameters that are constant on every call by propagating jump functions over the call graph.

Time
O((v + 1)(n + b v) + (k + 1) n) worst
Space
O(n + b v) extra
Where
b = the total number of blocks; k = the largest number of formals of one procedure; n = the total size of all procedures (instructions and terminators and call arguments); v = the largest number of names in one procedure
Properties
deterministicofflineiterative

Interprocedural constant propagation finds the formal parameters of each procedure that receive the same constant on every call, in every run of the program. It looks at each procedure once and describes each argument of each call site by a jump function: the argument is a known constant, or it passes on the value of one of the caller's own formals unchanged, or it is unknown. Then it propagates values over the call graph with a worklist, the way an intraprocedural constant propagation moves values over a flow graph. A formal that is the constant cc on every call gets p = c at the entry of its procedure, and local passes fold the rest. The method is due to Callahan, Cooper, Kennedy and Torczon.

In plain words

A function often gets the same value for a parameter at every place where it is called, such as a buffer size of 4096. Inside the function, the compiler cannot know this, because it sees only the parameter.

This algorithm looks at every call in the program. For each argument it notes one of three things: it is a fixed number, it just passes on a parameter of the caller, or it is unknown. Then it starts at the main function and follows the calls. If all calls of a function pass 4096 for a parameter, that parameter is 4096. If a function passes its own parameter on to another function, the value travels along.

When two calls disagree, the parameter is unknown. At the end, every parameter that is still a single number is fixed in the code, so tests on it can be folded away.

The problem

The input is a whole program: a set of procedures in the toy IR, with one procedure main\mathit{main} where every run starts. A procedure has formals and uses const, copy, op and call instructions, so a callee cannot change the variables of its caller. The inputs of main\mathit{main} are unknown.

The output is a value VAL[f,p]\mathrm{VAL}[f, p] for each formal pp of each procedure ff, in the lattice ⊤\top (no call seen), Const(c)\mathrm{Const}(c), and ⊥\bot (not known to be constant), and a transformed program. The result must be sound: if VAL[f,p]=Const(c)\mathrm{VAL}[f, p] = \mathrm{Const}(c), then every activation of ff in every run starts with p=cp = c. Recursion is allowed.

The algorithm

Line L1 runs a forward constant analysis inside each procedure ff. Each formal qq starts as the symbol qq, meaning "the value of qq when ff was entered", and every other name starts as ⊥\bot. An operation on two constants is folded, and any other operation, as well as the result of a call, gives ⊥\bot. The local value of the ii-th argument at a call site ss is its jump function J(s,i)J(s, i): a constant kk, a symbol qq, or ⊥\bot. A jump function is evaluated in the values of the caller: kk gives Const(k)\mathrm{Const}(k), qq gives VAL[f,q]\mathrm{VAL}[f, q], and ⊥\bot gives ⊥\bot. The meet ⊓\sqcap keeps two equal values, turns two different ones into ⊥\bot, and has ⊤\top as its identity.

  1. IPCP(procedures, main)
  2. 1for each procedure f: analyze f locally and record the jump function J(s, i) of each argument i of each call site s in a block it reaches
  3. 2for each procedure f and each formal p of f: VAL[f, p] <- ⊤
  4. 3for each formal p of main: VAL[main, p] <- ⊥
  5. 4REACHED <- {main}; W <- [main]
  6. 5while W is not empty
  7. 6f <- take the first procedure out of W
  8. 7for each recorded call site s in f, with callee g
  9. 8if g is not in REACHED then add g to REACHED and to W
  10. 9for each argument position i, with p the i-th formal of g
  11. 10v <- J(s, i) evaluated in VAL[f, ·]
  12. 11if VAL[g, p] ⊓ v ≠ VAL[g, p] then VAL[g, p] <- VAL[g, p] ⊓ v and add g to W if it is not there
  13. 12for each procedure f and each formal p with VAL[f, p] = Const(c): insert p = c in a new entry block of f
  14. 13return VAL and the new procedures

The jump functions do not depend on VAL, so line L1 runs once per procedure. The worklist then touches only the call sites. A procedure goes back into WW only when one of its own values drops, because only then can the values it sends to its callees change.

Example

The program has four procedures, written one after another. The formals of main are n, of scale are x, k, of mul are u, v, and of count are i, lim.

main:                         scale:
B0:                           B0:
  w = 4                         t = call mul(x, k)
  a = call scale(n, w)          ret t
  b = call scale(a, 4)
  c = call count(0, 5)        mul:
  d = b + c                   B0:
  ret d                         t = u * v
                                ret t
count:
B0:
  c = i < lim
  br c B1 B2
B1:
  j = i + 1
  r = call count(j, lim)
  ret r
B2:
  ret i

Line L1 gives these jump functions.

call site first argument second argument
scale(n, w) in main n 4
scale(a, 4) in main ⊥ 4
count(0, 5) in main 0 5
mul(x, k) in scale x k
count(j, lim) in count ⊥ lim

The second argument of the first call is the constant 4 because the local analysis knows w = 4. a is the result of a call, so it is ⊥. j = i + 1 is not a plain pass-through, so it is ⊥ too.

The worklist starts with main, where n is ⊥. Processing main reaches scale with x=⊥x = \bot and k=4k = 4, and count with i=0i = 0 and lim=5\mathit{lim} = 5. Processing scale reaches mul with u=VAL[scale,x]=⊥u = \mathrm{VAL}[\mathit{scale}, x] = \bot and v=VAL[scale,k]=4v = \mathrm{VAL}[\mathit{scale}, k] = 4. Processing count meets i=0i = 0 with ⊥ from the recursive call, so ii drops to ⊥ and count goes back into the worklist, while lim\mathit{lim} meets 5 with VAL[count,lim]=5\mathrm{VAL}[\mathit{count}, \mathit{lim}] = 5 and stays 5. One more pass over count and one over mul change nothing.

procedure formals
main n=⊥n = \bot
scale x=⊥x = \bot, k=4k = 4
mul u=⊥u = \bot, v=4v = 4
count i=⊥i = \bot, lim=5\mathit{lim} = 5

Line L12 gives scale, mul and count a new entry block. For count it is:

ipcp.entry:
  lim = 5
  jump B0

Constant propagation inside mul then turns t = u * v into t = u * 4, which strength reduction can make a shift. The value 4 reached mul only through scale, which passes k on unchanged. On n=3n = 3 both versions return 53.

Correctness

The proof file has the full proof. It has three parts.

  • Local soundness. In an activation of ff that started with formals σ\sigma, at every point that the run reaches, a name with local value kk holds kk, and a name with local value qq holds σ(q)\sigma(q). This is the usual induction for a forward analysis at its fixed point. A call cannot change the caller's variables, so only its result becomes ⊥. So an argument with jump function kk is kk, and one with jump function qq is σ(q)\sigma(q).
  • Global fixed point. When WW is empty, every call site ss from ff to gg has VAL[g,pi]⊑J(s,i)\mathrm{VAL}[g, p_i] \sqsubseteq J(s, i) evaluated in VAL[f,⋅]\mathrm{VAL}[f, \cdot]. The reason is that ff was processed after its values last changed, and values only go down.
  • Soundness. By induction on the order in which activations start, every activation of ff starts with each formal pp in the set that VAL[f,p]\mathrm{VAL}[f, p] describes. The first activation of main has ⊥ formals. For an activation made by a call site, the two facts above give the step. Recursion needs no special care, because the induction is over activations, not over the call graph.

The new entry block writes into each constant formal the value that it already holds, so the transformed program runs the same steps and has the same outcome.

Proof: Interprocedural constant propagation with jump functions is soundfull

Setting. A whole program is a set of procedures with a distinguished procedure main\mathit{main}. Each procedure has formals and uses only const, copy, op and call instructions, so a callee cannot read or write a variable of its caller. A run starts with one activation of main\mathit{main} on any arguments. A call creates a new activation of the callee whose formals hold the argument values, and the caller waits until the callee returns. For an activation AA of a procedure ff, write σA(q)\sigma_A(q) for the value of formal qq when AA starts.

Lattices. The local analysis uses the values Const(k)\mathrm{Const}(k), Formal(q)\mathrm{Formal}(q) and ⊥\bot. Within one activation AA, a value describes a set of integers: γA(Const(k))={k}\gamma_A(\mathrm{Const}(k)) = \{k\}, γA(Formal(q))={σA(q)}\gamma_A(\mathrm{Formal}(q)) = \{\sigma_A(q)\}, and γA(⊥)\gamma_A(\bot) is every value, together with "not defined yet". The interprocedural values are ⊤\top, Const(k)\mathrm{Const}(k) and ⊥\bot, with γ(⊤)=∅\gamma(\top) = \emptyset, γ(Const(k))={k}\gamma(\mathrm{Const}(k)) = \{k\} and γ(⊥)\gamma(\bot) every integer. In both lattices, u⊑vu \sqsubseteq v means u=vu = v, or u=⊥u = \bot, or v=⊤v = \top. Then u⊓v⊑uu \sqcap v \sqsubseteq u and u⊓v⊑vu \sqcap v \sqsubseteq v, and u⊑vu \sqsubseteq v implies γ(v)⊆γ(u)\gamma(v) \subseteq \gamma(u).

What we prove. Let VAL be the result of lines L2 to L11.

  • Theorem 1 (soundness). If VAL[f,p]=Const(c)\mathrm{VAL}[f, p] = \mathrm{Const}(c), then in every run, every activation of ff starts with p=cp = c.
  • Theorem 2 (same behavior). The program of line L12 has the same outcome as the old one on every input: the same returned value, a trap, or no end.
  • Theorem 3 (termination). The worklist loop stops.

1. The local analysis

Fix a procedure ff. The analysis of line L1 assigns a state SBS_B, a map from names to local values, to each block BB that it reaches. The entry state maps each formal qq to Formal(q)\mathrm{Formal}(q) and every other name to ⊥\bot. The transfer of an instruction is: x = k gives Const(k)\mathrm{Const}(k), x = y copies the value of yy, x = a op b gives Const(aopb)\mathrm{Const}(a \mathbin{op} b) if both operands are constants and the operation does not trap, and ⊥\bot otherwise, and x = call g(...) gives ⊥\bot. Write TBT_B for the transfer of the whole block BB.

Lemma 1 (local fixed point). When the local worklist is empty, every successor tt of a reached block BB is reached and St⊑TB(SB)S_t \sqsubseteq T_B(S_B) for every name.

Proof. A block's state only goes down: the first time it is set, and later only by a meet with a new value. Every time SBS_B changes, BB goes into the worklist, if it is not already there. So after the last change of SBS_B, the block BB is taken out and processed with its final state. That step sets StS_t for an unreached tt, or replaces StS_t by St⊓TB(SB)S_t \sqcap T_B(S_B), which is ⊑TB(SB)\sqsubseteq T_B(S_B). Later changes only lower StS_t. Each name can lower at most once below its first value, since ⊥\bot is the only value below a constant or a symbol, so the number of changes is finite and the worklist empties. □\square

Lemma 2 (local soundness). Let AA be an activation of ff. Each time AA is at the start of a block BB, the block is reached by the analysis, and for every name xx the current value of xx in AA lies in γA(SB(x))\gamma_A(S_B(x)). The same holds at every instruction of BB for the state that the analysis computes at that instruction.

Proof. Induction on the steps of AA. At the start, AA is at the entry. A formal qq holds σA(q)∈γA(Formal(q))\sigma_A(q) \in \gamma_A(\mathrm{Formal}(q)), and any other name is in γA(⊥)\gamma_A(\bot). Inside a block, each kind of instruction keeps the property. For a constant, a copy or a folded operation this is direct: if both operands hold aa and bb, then xx gets aopba \mathbin{op} b, the value that the analysis computed. If the operation traps, AA ends and nothing more is claimed. A call writes only its target xx, whose value is ⊥\bot, because the callee works on its own variables and cannot change those of AA. No instruction changes σA\sigma_A. At the end of BB, control moves to a successor tt. The values satisfy TB(SB)T_B(S_B), and by Lemma 1 the block tt is reached and St⊑TB(SB)S_t \sqsubseteq T_B(S_B), so γA(TB(SB)(x))⊆γA(St(x))\gamma_A(T_B(S_B)(x)) \subseteq \gamma_A(S_t(x)). □\square

Corollary 3 (jump functions). Let ss be a call site in ff and Js,iJ_{s,i} the value of its ii-th argument in the state at ss. If an activation AA of ff executes ss, then ss is in a reached block, so line L1 records it, and the ii-th argument value aia_i lies in γA(Js,i)\gamma_A(J_{s,i}). That is, ai=ka_i = k if Js,i=Const(k)J_{s,i} = \mathrm{Const}(k), and ai=σA(q)a_i = \sigma_A(q) if Js,i=Formal(q)J_{s,i} = \mathrm{Formal}(q).

2. The propagation

For a jump function JJ and a map VV from the formals of ff to interprocedural values, let ev(J,V)\mathrm{ev}(J, V) be Const(k)\mathrm{Const}(k) for J=Const(k)J = \mathrm{Const}(k), V(q)V(q) for J=Formal(q)J = \mathrm{Formal}(q), and ⊥\bot for J=⊥J = \bot. This is line L10. It is monotone in VV.

Lemma 4 (global fixed point). When the loop of line L5 stops, for every procedure ff in REACHED and every recorded call site ss in ff with callee gg: gg is in REACHED, and VAL[g,pi]⊑ev(Js,i,VAL[f,⋅])\mathrm{VAL}[g, p_i] \sqsubseteq \mathrm{ev}(J_{s,i}, \mathrm{VAL}[f, \cdot]) for every argument position ii, where pip_i is the ii-th formal of gg.

Proof. Every value of VAL only goes down, since line L11 replaces a value by its meet with another. A procedure goes into WW when it enters REACHED (lines L4 and L8) and every time one of its values changes (line L11). Let tt be the last moment at which ff entered REACHED or a value VAL[f,⋅]\mathrm{VAL}[f, \cdot] changed. At tt, ff is in WW, so it is taken out later, at line L6, with its final values. Lines L7 to L11 then put gg into REACHED and make VAL[g,pi]⊑ev(Js,i,VAL[f,⋅])\mathrm{VAL}[g, p_i] \sqsubseteq \mathrm{ev}(J_{s,i}, \mathrm{VAL}[f, \cdot]). After that, the right side does not change and the left side only goes down, so the relation still holds at the end. □\square

Lemma 5 (no ⊤\top in a reached procedure). At the end, VAL[f,p]≠⊤\mathrm{VAL}[f, p] \ne \top for every ff in REACHED and every formal pp of ff.

Proof. Induction on the order in which procedures enter REACHED. The formals of main\mathit{main} are ⊥\bot. A procedure gg enters REACHED at line L8 for a call site ss in a procedure ff that is already in REACHED. In the same step, line L11 lowers each VAL[g,pi]\mathrm{VAL}[g, p_i] to at most ev(Js,i,VAL[f,⋅])\mathrm{ev}(J_{s,i}, \mathrm{VAL}[f, \cdot]), which is a constant, ⊥\bot, or a value VAL[f,q]\mathrm{VAL}[f, q] that is not ⊤\top by the induction hypothesis, since values only go down. □\square

3. Soundness

Theorem 1. In every run, every activation AA of a procedure ff has f∈REACHEDf \in \mathrm{REACHED}, and σA(p)∈γ(VAL[f,p])\sigma_A(p) \in \gamma(\mathrm{VAL}[f, p]) for every formal pp of ff. In particular, VAL[f,p]=Const(c)\mathrm{VAL}[f, p] = \mathrm{Const}(c) implies σA(p)=c\sigma_A(p) = c.

Proof. Induction on the order in which the activations start. The first activation is of main\mathit{main}, which is in REACHED with all formals ⊥\bot, and γ(⊥)\gamma(\bot) contains every integer.

Let an activation BB of gg start from a call site ss executed by an earlier activation AA of ff. By the induction hypothesis, f∈REACHEDf \in \mathrm{REACHED} and σA(q)∈γ(VAL[f,q])\sigma_A(q) \in \gamma(\mathrm{VAL}[f, q]) for every formal qq of ff. By Corollary 3, ss is recorded, and the argument aia_i is in γA(Js,i)\gamma_A(J_{s,i}). We show ai∈γ(ev(Js,i,VAL[f,⋅]))a_i \in \gamma(\mathrm{ev}(J_{s,i}, \mathrm{VAL}[f, \cdot])):

  • if Js,i=Const(k)J_{s,i} = \mathrm{Const}(k), then ai=ka_i = k and ev=Const(k)\mathrm{ev} = \mathrm{Const}(k);
  • if Js,i=Formal(q)J_{s,i} = \mathrm{Formal}(q), then ai=σA(q)∈γ(VAL[f,q])=γ(ev)a_i = \sigma_A(q) \in \gamma(\mathrm{VAL}[f, q]) = \gamma(\mathrm{ev});
  • if Js,i=⊥J_{s,i} = \bot, then ev=⊥\mathrm{ev} = \bot, which contains every integer.

By Lemma 4, g∈REACHEDg \in \mathrm{REACHED} and VAL[g,pi]⊑ev(Js,i,VAL[f,⋅])\mathrm{VAL}[g, p_i] \sqsubseteq \mathrm{ev}(J_{s,i}, \mathrm{VAL}[f, \cdot]), so γ(ev)⊆γ(VAL[g,pi])\gamma(\mathrm{ev}) \subseteq \gamma(\mathrm{VAL}[g, p_i]). Since σB(pi)=ai\sigma_B(p_i) = a_i, the claim holds for BB. □\square

The proof never uses that the call graph is acyclic, so recursion is covered. A procedure that no activation ever reaches may keep ⊤\top, and γ(⊤)=∅\gamma(\top) = \emptyset says correctly that no activation of it exists.

4. The transformation

Theorem 2. The program of line L12 has the same outcome as the old one on every input.

Proof. Line L12 changes a procedure ff only by a new entry block that runs p = c for each formal with VAL[f,p]=Const(c)\mathrm{VAL}[f, p] = \mathrm{Const}(c), and then jumps to the old entry. Run both programs side by side on the same input, and match each activation of the new program with the activation of the old one that the same call creates. By Theorem 1, in the old program every activation of ff starts with p=cp = c, so the new entry block writes to each such pp the value that it already holds. After the jump, the matched activations have equal variables and are at the same block, and they run the same instructions on the same values. A call in one is a call in the other, with the same arguments, so by induction on the order of the activations, the theorem applies to the callee too. So the two runs make the same calls, take the same branches, return the same values and trap at the same instruction. The only difference is the extra steps of the new entry blocks. □\square

Theorem 1 holds for the old program, and the matching shows that both programs create the same activations, so the claim also holds in the new program. A later pass may therefore replace uses of pp in ff by cc or fold them.

5. Termination

Theorem 3. The worklist loop stops after at most ∑f(1+2kf)\sum_f (1 + 2 k_f) iterations, where kfk_f is the number of formals of ff.

Proof. Each iteration takes one procedure out of WW. A procedure goes into WW once when it enters REACHED, and once each time one of its values goes down. A value goes down at most twice, from ⊤\top to a constant and from a constant to ⊥\bot, because a meet of two different constants is ⊥\bot. □\square

Complexity

The local analysis of a procedure with nfn_f size, bfb_f blocks and vfv_f names lowers each name in the start state of a block at most once below its first value. So each block is processed at most vf+2v_f + 2 times, at a cost of O(its length+vf)O(\text{its length} + v_f). Summed over all procedures, line L1 costs O((v+1)(n+bv))O((v + 1)(n + b v)). In the worklist, a value goes down at most twice, from ⊤\top to a constant and then to ⊥\bot. So a procedure with kfk_f formals is processed at most 1+2kf1 + 2 k_f times, and each time costs the size of its call sites. This gives O((k+1)n)O((k + 1) n) for lines L5 to L11. Line L12 is linear. The jump functions take O(n)O(n) space, the values one entry per formal, and the local analysis of one procedure O(bv)O(b v) at a time.

Properties

  • Sound. A claimed constant holds on every call in every run, for any inputs of main, with or without recursion.
  • Flow-insensitive between procedures. A formal gets one value for all calls. Two callers that pass 1 and 2 make it ⊥, even if each call alone could be specialized.
  • Monotone and terminating. Values only go down in a lattice of height 2.
  • Precision depends on the jump functions. A pass-through jump function moves constants along chains of calls. Without it, the constant 4 in the example never reaches mul.
  • Deterministic. The order of the worklist can change the number of steps, not the result, since the result is the greatest fixed point of the equations.

Variants and improvements

  • Kinds of jump functions. Grove and Torczon compared literal constant jump functions, which only see constants written at the call, intraprocedural constant ones as on this page, pass-through ones, and polynomial ones, which allow expressions such as q + 1 over the caller's formals. In their study, pass-through functions came close to the more expensive kinds at a much lower cost.
  • Return jump functions. Callahan and colleagues also describe the result of a procedure as a function of its formals, so that a = call scale(n, 4) can become a constant when scale returns a constant.
  • Conditional propagation. LLVM's ipsccp pass runs sparse conditional constant propagation over the whole module. It skips branches that cannot run and call sites in them, so it finds more constants, and it also tracks constant return values.
  • Cloning. When the callers disagree, a compiler can make a copy of the callee for the calls that pass a constant. This is procedure cloning, a middle ground between this algorithm and inlining.
  • Context-sensitive analysis. IDE and the functional approach give a result for each calling context instead of one value per formal.

When to use it

Use it in a compiler that sees the whole program or a whole module, such as at link time, before inlining decisions and cloning. It is cheap, because each procedure is analyzed once and the propagation touches only call sites. It pays most in programs with configuration parameters, flags and sizes passed down through several layers of calls. Inside one procedure after inlining, plain constant propagation is enough.

Pitfalls

  • Unknown callers. A procedure that can be called from outside the analyzed code, for example an exported function, a function whose address is taken, or a callback, must have all its formals at ⊥. Otherwise a call from outside can break the claim.
  • Indirect calls. A call through a function pointer or a virtual call must be resolved to its possible targets by call graph construction, and each target must get the meet of the arguments. A missed target makes the result unsound.
  • Memory. If a callee can write the caller's variables through pointers, a value that the local analysis keeps after a call may be wrong. The local analysis must treat names whose address is taken as ⊥ after calls, or use a mod-ref summary of the callee.
  • Starting at ⊥ by mistake. If every formal starts at ⊥, nothing is ever found. Only the entry points start at ⊥. The others start at ⊤ and drop as calls are seen.
  • Dead callers. A call site in code that never runs still lowers the values of its callee. A conditional variant avoids this.

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.

interprocedural_constant_propagation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/interprocedural-constant-propagation/. The authors are listed in prov/D7W565.jsonl.
"""Interprocedural constant propagation with jump functions, on the toy IR.

A whole program is a dict from procedure name to toyir.Program. The
procedures may use const, copy, op and call instructions. Without memory
instructions, a callee cannot change a variable of its caller, so a local
analysis of each procedure is enough to describe its call sites.

Step 1 runs a forward constant analysis inside each procedure. A formal q
starts as the symbol ("formal", q), which stands for the value that q had
when the procedure was entered. The value of each argument at each call site
is the jump function of that argument: ("const", k), ("formal", q) or BOT.

Step 2 propagates values over the call graph with a worklist. VAL[f][p] is
TOP (no call seen yet), ("const", k) or BOT. The formals of the main
procedure start at BOT, all others at TOP.

Step 3 gives each procedure with a constant formal p = k a new entry block
that sets p = k and jumps to the old entry. Later local passes can then fold
the constant into the body.
"""

from collections import deque

import toyir

TOP = ("top",)
BOT = ("bot",)

ALLOWED = ("const", "copy", "op", "call")


def meet(a, b):
    """The meet of two lattice values: TOP is the identity, two equal
    values stay, and two different values give BOT."""
    if a == TOP:
        return b
    if b == TOP:
        return a
    return a if a == b else BOT


def check(procs, main):
    if main not in procs:
        raise ValueError("no procedure %r" % main)
    for f, prog in procs.items():
        for blk in prog.blocks.values():
            for ins in blk.instrs:
                if ins[0] not in ALLOWED:
                    raise ValueError("%s: instruction %r is not supported" % (f, ins[0]))
                if ins[0] == "call":
                    if ins[2] not in procs:
                        raise ValueError("%s calls an unknown procedure %r" % (f, ins[2]))
                    if len(ins[3]) != len(procs[ins[2]].params):
                        raise ValueError("%s calls %s with a wrong number of arguments" % (f, ins[2]))


# ------------------------------------------------------- the local analysis


def _value(state, a):
    if isinstance(a, int):
        return ("const", a)
    return state[a]


def _step(state, ins):
    k = ins[0]
    if k == "const":
        state[ins[1]] = ("const", ins[2])
    elif k == "copy":
        state[ins[1]] = _value(state, ins[2])
    elif k == "op":
        a, b = _value(state, ins[3]), _value(state, ins[4])
        if a[0] == "const" and b[0] == "const":
            try:
                state[ins[1]] = ("const", toyir._binop(ins[2], a[1], b[1]))
            except toyir._Trap:
                state[ins[1]] = BOT
        else:
            state[ins[1]] = BOT
    elif k == "call":
        state[ins[1]] = BOT
    else:
        raise ValueError("bad instruction: %r" % (ins,))


def _names(prog):
    out = set(prog.params)
    for blk in prog.blocks.values():
        for ins in blk.instrs:
            out.add(toyir.defs(ins))
            out.update(toyir.uses(ins))
        out.update(toyir.term_uses(blk.term))
    return out


def local_states(prog):
    """The state at the start of each block that the analysis reaches. A
    state maps each name to ("const", k), ("formal", q) or BOT. Every edge
    is taken as possible, so a block is reached when the CFG reaches it."""
    params = set(prog.params)
    start = {x: ("formal", x) if x in params else BOT for x in _names(prog)}
    state_in = {prog.entry: start}
    work = deque([prog.entry])
    queued = {prog.entry}
    while work:
        label = work.popleft()
        queued.discard(label)
        s = dict(state_in[label])
        for ins in prog.blocks[label].instrs:
            _step(s, ins)
        for t in toyir.succs(prog, label):
            if t not in state_in:
                new = dict(s)
            else:
                old = state_in[t]
                new = {x: meet(old[x], s[x]) for x in old}
                if new == old:
                    continue
            state_in[t] = new
            if t not in queued:
                work.append(t)
                queued.add(t)
    return state_in


def jump_functions(prog):
    """The call sites of prog in reached blocks, as tuples (label, index,
    callee, jumps), where jumps holds the jump function of each argument."""
    state_in = local_states(prog)
    sites = []
    for label, blk in prog.blocks.items():
        if label not in state_in:
            continue
        s = dict(state_in[label])
        for i, ins in enumerate(blk.instrs):
            if ins[0] == "call":
                sites.append((label, i, ins[2], [_value(s, a) for a in ins[3]]))
            _step(s, ins)
    return sites


def evaluate(jump, val_f):
    """The value of a jump function, given the values of the caller's formals."""
    if jump[0] == "formal":
        return val_f[jump[1]]
    return jump


# ------------------------------------------------------- the main algorithm


def _fresh_label(prog, base):
    label, k = base, 0
    while label in prog.blocks:
        k += 1
        label = "%s%d" % (base, k)
    return label


def specialize(prog, val_f):
    """A copy of prog that sets each constant formal at a new entry block."""
    consts = [(p, val_f[p][1]) for p in prog.params if val_f[p][0] == "const"]
    blocks = {}
    if consts:
        label = _fresh_label(prog, "ipcp.entry")
        blocks[label] = toyir.Block([("const", p, k) for p, k in consts], ("jump", prog.entry))
    for label, blk in prog.blocks.items():
        blocks[label] = toyir.Block([tuple(ins) for ins in blk.instrs], blk.term)
    return toyir.Program(list(prog.params), blocks)


def ipcp(procs, main="main"):
    """Returns (val, out). val[f][p] is TOP, ("const", k) or BOT for each
    formal p of each procedure f, and out is the transformed program."""
    check(procs, main)
    sites = {f: jump_functions(prog) for f, prog in procs.items()}  # @line L1
    val = {f: {p: TOP for p in prog.params} for f, prog in procs.items()}  # @line L2
    for p in procs[main].params:  # @line L3
        val[main][p] = BOT
    reached = {main}  # @line L4
    work = deque([main])
    queued = {main}
    while work:  # @line L5
        f = work.popleft()  # @line L6
        queued.discard(f)
        for _, _, g, jumps in sites[f]:  # @line L7
            if g not in reached:  # @line L8
                reached.add(g)
                if g not in queued:
                    work.append(g)
                    queued.add(g)
            for p, jump in zip(procs[g].params, jumps):  # @line L9
                v = evaluate(jump, val[f])  # @line L10
                new = meet(val[g][p], v)
                if new != val[g][p]:  # @line L11
                    val[g][p] = new
                    if g not in queued:
                        work.append(g)
                        queued.add(g)
    out = {f: specialize(prog, val[f]) for f, prog in procs.items()}  # @line L12
    return val, out  # @line L13


def show_value(v):
    if v == TOP:
        return "⊤"
    if v == BOT:
        return "⊥"
    if v[0] == "formal":
        return v[1]
    return str(v[1])
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_interprocedural_constant_propagation.py 312 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/interprocedural-constant-propagation/. The authors are listed in prov/D7W565.jsonl.
import random

import toyir
import interprocedural_constant_propagation as I

PAGE = {
    "main": """# params: n
B0:
  w = 4
  a = call scale(n, w)
  b = call scale(a, 4)
  c = call count(0, 5)
  d = b + c
  ret d
""",
    "scale": """# params: x, k
B0:
  t = call mul(x, k)
  ret t
""",
    "mul": """# params: u, v
B0:
  t = u * v
  ret t
""",
    "count": """# params: i, lim
B0:
  c = i < lim
  br c B1 B2
B1:
  j = i + 1
  r = call count(j, lim)
  ret r
B2:
  ret i
""",
}

PAGE_COUNT_AFTER = """# params: i, lim
ipcp.entry:
  lim = 5
  jump B0
B0:
  c = i < lim
  br c B1 B2
B1:
  j = i + 1
  r = call count(j, lim)
  ret r
B2:
  ret i
"""

FUEL = 20000  # the random runs below finish in under 3000 steps


def parse_all(texts):
    return {f: toyir.parse(t) for f, t in texts.items()}


def outcome(procs, args, fuel=FUEL):
    return toyir.run(procs["main"], args, fuel=fuel, funcs=procs)


def with_checks(procs, val):
    """A copy of procs where each procedure first tests every claimed
    constant formal and spins forever if one of them is wrong."""
    out = {}
    for f, prog in procs.items():
        consts = [(p, v[1]) for p, v in val[f].items() if v[0] == "const"]
        if not consts:
            out[f] = prog
            continue
        instrs = [("const", "chk.ok", 1)]
        for i, (p, k) in enumerate(consts):
            instrs.append(("op", "chk.t%d" % i, "==", p, k))
            instrs.append(("op", "chk.ok", "&", "chk.ok", "chk.t%d" % i))
        blocks = {
            "chk.entry": toyir.Block(instrs, ("br", "chk.ok", prog.entry, "chk.spin")),
            "chk.spin": toyir.Block([], ("jump", "chk.spin")),
        }
        blocks.update(prog.blocks)
        out[f] = toyir.Program(list(prog.params), blocks)
    return out


def random_procs(rng, recursive):
    """Procedures main, P1, P2, P3 with the formals x0 and x1. A procedure
    calls only later ones, so the call graph is acyclic, except that with
    recursive=True some procedures also call themselves under a depth test
    on x0 that allows at most 3 nested self calls."""
    names = ["main", "P1", "P2", "P3"]
    procs = {}
    ncalls = 0
    for i, f in enumerate(names):
        nvars = rng.randint(2, 4)
        prog = toyir.random_program(rng, nvars, rng.randint(1, 4), rng.random() < 0.5)
        xs = ["x%d" % j for j in range(nvars)]
        later = names[i + 1:]
        for _ in range(rng.randint(1, 2) if later else 0):
            g = rng.choice(later)
            blk = prog.blocks[rng.choice(list(prog.blocks))]
            args = []
            for _ in range(2):
                r = rng.random()
                if r < 0.35:
                    args.append(rng.choice((2, 2, 3)))
                elif r < 0.5:
                    k = "k%d" % ncalls
                    ncalls += 1
                    blk.instrs.append(("const", k, rng.choice((2, 3))))
                    args.append(k)
                elif r < 0.8:
                    args.append(rng.choice(prog.params))
                else:
                    args.append(rng.choice(xs))
            blk.instrs.append(("call", rng.choice(xs), g, args))
        if recursive and i > 0 and rng.random() < 0.6:
            arg = rng.choice(("x1", "x1", 2, 3))
            dest = rng.choice(("rec.r", "x1"))
            blocks = {
                "R0": toyir.Block(
                    [("op", "rec.a", "<", 0, "x0"), ("op", "rec.b", "<", "x0", 4), ("op", "rec.g", "&", "rec.a", "rec.b")],
                    ("br", "rec.g", "R1", prog.entry),
                ),
                "R1": toyir.Block([("op", "rec.d", "-", "x0", 1), ("call", dest, f, ["rec.d", arg])], ("jump", prog.entry)),
            }
            blocks.update(prog.blocks)
            prog = toyir.Program(prog.params, blocks)
        procs[f] = prog
    return procs


def cases(seed, n, recursive):
    rng = random.Random(seed)
    for _ in range(n):
        procs = random_procs(rng, recursive)
        inputs = [[rng.randint(-4, 6), rng.choice((2, 3, rng.randint(-4, 6)))] for _ in range(4)]
        yield procs, inputs


def test_page_example():
    procs = parse_all(PAGE)
    sites = {f: I.jump_functions(p) for f, p in procs.items()}
    shown = {f: [[I.show_value(j) for j in s[3]] for s in sites[f]] for f in sites}
    assert shown == {
        "main": [["n", "4"], ["⊥", "4"], ["0", "5"]],
        "scale": [["x", "k"]],
        "mul": [],
        "count": [["⊥", "lim"]],
    }
    val, out = I.ipcp(procs)
    shown = {f: {p: I.show_value(v) for p, v in val[f].items()} for f in val}
    assert shown == {
        "main": {"n": "⊥"},
        "scale": {"x": "⊥", "k": "4"},
        "mul": {"u": "⊥", "v": "4"},
        "count": {"i": "⊥", "lim": "5"},
    }
    assert toyir.show(out["count"]) == PAGE_COUNT_AFTER
    assert toyir.show(out["main"]) == toyir.show(procs["main"])
    for n in range(-5, 8):
        assert outcome(out, [n]) == outcome(procs, [n])
    assert outcome(procs, [3]) == ("ret", 53)


def test_jump_functions_follow_the_local_values():
    procs = parse_all({
        "main": """# params: a, b
B0:
  c = a
  a = 1
  br b B1 B2
B1:
  d = 7
  e = b
  jump B3
B2:
  d = 7
  e = 5
  jump B3
B3:
  f = d * 2
  g = a + c
  r = call h(c, a, d, e, f, g)
  ret r
B4:
  s = call h(1, 1, 1, 1, 1, 1)
  ret s
""",
        "h": """# params: p, q, r, s, t, u
B0:
  ret p
""",
    })
    sites = I.jump_functions(procs["main"])
    assert len(sites) == 1  # B4 is not reachable
    assert [I.show_value(j) for j in sites[0][3]] == ["a", "1", "7", "⊥", "14", "⊥"]


def test_claims_hold_on_every_call():
    """Each procedure checks its claimed constants on entry and spins if one
    is wrong, so a false claim turns a finished run into a run out of fuel."""
    claimed = 0
    for recursive in (False, True):
        for procs, inputs in cases(11 + recursive, 250, recursive):
            val, _ = I.ipcp(procs)
            claimed += sum(v[0] == "const" for f in val for v in val[f].values())
            checked = with_checks(procs, val)
            for args in inputs:
                before = outcome(procs, args)
                if before == ("fuel",):
                    continue
                assert outcome(checked, args, fuel=4 * FUEL) == before
    assert claimed > 100


def test_checks_catch_a_wrong_claim():
    """The check in the test above has teeth: claiming k + 1 instead of k
    makes most runs that call the procedure spin."""
    caught = total = 0
    for procs, inputs in cases(5, 60, True):
        val, _ = I.ipcp(procs)
        bad = {f: {p: ("const", v[1] + 1) if v[0] == "const" else v for p, v in val[f].items()} for f in val}
        if bad == val:
            continue
        checked = with_checks(procs, bad)
        for args in inputs:
            total += 1
            caught += outcome(checked, args, fuel=6000) == ("fuel",)
    assert total > 50 and caught > total // 2


def test_same_outcome_on_random_programs():
    changed = 0
    for recursive in (False, True):
        for procs, inputs in cases(23 + recursive, 250, recursive):
            _, out = I.ipcp(procs)
            changed += sum(toyir.show(out[f]) != toyir.show(procs[f]) for f in procs)
            for args in inputs:
                before = outcome(procs, args)
                if before == ("fuel",):
                    continue
                assert outcome(out, args, fuel=4 * FUEL) == before
    assert changed > 100


def test_worklist_matches_one_pass_in_call_order():
    """Without recursion every caller comes before its callees in the list
    main, P1, P2, P3, so one pass in that order gives the final values."""
    for procs, _ in cases(37, 300, False):
        val, _ = I.ipcp(procs)
        ref = {f: {p: I.TOP for p in prog.params} for f, prog in procs.items()}
        ref["main"] = {p: I.BOT for p in procs["main"].params}
        reached = {"main"}
        for f in ("main", "P1", "P2", "P3"):
            if f not in reached:
                continue
            for _, _, g, jumps in I.jump_functions(procs[f]):
                reached.add(g)
                for p, j in zip(procs[g].params, jumps):
                    ref[g][p] = I.meet(ref[g][p], I.evaluate(j, ref[f]))
        assert val == ref


def test_unreached_procedure_stays_top_and_unchanged():
    procs = parse_all({
        "main": """# params: n
B0:
  ret n
""",
        "lost": """# params: a
B0:
  r = call leaf(3)
  ret r
""",
        "leaf": """# params: b
B0:
  ret b
""",
    })
    val, out = I.ipcp(procs)
    assert val["lost"] == {"a": I.TOP}
    assert val["leaf"] == {"b": I.TOP}
    assert all(toyir.show(out[f]) == toyir.show(procs[f]) for f in procs)


def test_recursion_through_a_changed_argument_is_not_constant():
    procs = parse_all({
        "main": """# params: n
B0:
  r = call down(3, 2)
  ret r
""",
        "down": """# params: d, k
B0:
  c = 0 < d
  br c B1 B2
B1:
  e = d - 1
  k2 = k + 0
  r = call down(e, k2)
  ret r
B2:
  ret k
""",
    })
    val, _ = I.ipcp(procs)
    # k + 0 is not a pass-through jump function, so k becomes BOT.
    assert val["down"] == {"d": I.BOT, "k": I.BOT}

History

Callahan, Cooper, Kennedy and Torczon presented interprocedural constant propagation with jump functions at the SIGPLAN Symposium on Compiler Construction in 1986. They separated the cost of building jump functions from the cheap propagation over the call graph, and they described return jump functions. Grove and Torczon measured the kinds of jump functions on real programs at PLDI 1993. Later compilers, such as LLVM with its ipsccp pass, combine the interprocedural step with sparse conditional constant propagation.

References

  1. David Callahan, Keith D. Cooper, Ken Kennedy and Linda Torczon, Interprocedural constant propagation, Proceedings of the 1986 SIGPLAN Symposium on Compiler Construction (SIGPLAN Notices 21(7)), 152-161, the whole paper (jump functions for the arguments of each call site, return jump functions, and propagation of constants over the call graph)
  2. Dan Grove and Linda Torczon, Interprocedural constant propagation: a study of jump function implementation, Proceedings of the ACM SIGPLAN 1993 Conference on Programming Language Design and Implementation (PLDI 1993), 90-99, the whole paper (literal constant, intraprocedural constant, pass-through and polynomial jump functions, compared on real programs)
  3. Keith D. Cooper and Linda Torczon, Engineering a Compiler, 3rd edition, Morgan Kaufmann, 2022, Section 9.4.2 (Interprocedural Constant Propagation)
  4. LLVM Project, LLVM's Analysis and Transform Passes, LLVM documentation, the entry for -ipsccp (interprocedural sparse conditional constant propagation)

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
  • History with a source
  • a scene preset for the example