Techniqueadvanced
Chains of recurrences
Also called scalar evolution.
Represents the values of an induction variable over iterations as a chain of add or multiply recurrences, closed under arithmetic.
In plain words
A loop variable often follows a simple rule: start at some value, then add a fixed amount each time, or add an amount that itself grows by a fixed amount, or multiply by a fixed factor. A chain of recurrences writes this rule as a short list: the start value, then the first step, then the step of the step, and so on, with a plus or a times between them. The list is enough to compute every value with a few additions per iteration, and it has a closed formula in the iteration number. Sums and products of such lists are again such lists, by simple rules, so a compiler can describe every expression of a loop that is built from counters. LLVM calls its version of this analysis scalar evolution.
When it applies
Use a chain of recurrences (CR) when a value is a function of the iteration number of a loop and is built from:
- the loop counter and loop-invariant values,
- additions, subtractions and multiplications by loop-invariant values or by other chains of the same loop,
- loop-carried updates of the form
v = v + eorv = c * v, whereeis itself a chain or invariant andcis invariant.
The chains then describe exactly the polynomial sequences (pure sums), the geometric sequences and their generalizations (pure products), and mixtures of them. Two uses are common. A compiler uses the chain to recognize and classify induction variables, to get closed forms for dependence testing and trip counts, and to replace multiplications by additions (strength reduction). A numerical program uses the chain to evaluate a function on a regular grid with a few additions per point instead of a full polynomial evaluation at each point, which was the original aim of Bachmann, Wang and Zima.
It does not apply to values that change under a condition, values read from memory, or sequences with no closed form of these shapes. A compiler marks those as unknown.
The template
Notation. A chain of recurrences is
where the do not depend on . The number is the length. The tail is again a chain, and is the constant . The value at is defined from the tail:
So and . A chain with only is a pure sum, one with only is a pure product. In a compiler a chain belongs to one loop , written (LLVM prints {start,+,step}<loop>), and a coefficient may be a chain of an outer loop, which is invariant in .
Evaluation. Keep one register per coefficient and update the registers from left to right:
EVAL-CR(φ[0..k], op[1..k], N)- 1
r ← copy of φ[0..k] - 2
for n ← 0 to N − 1 - 3
output r[0] - 4
for j ← 0 to k − 1 - 5
r[j] ← r[j] op[j+1] r[j+1]
Before iteration of the outer loop, for every . Line L5 reads before it is changed, because the updates go from left to right, so it sets to . The loop outputs with operations per value.
Closed forms. For a pure sum and a pure product,
Proof. Induction on . For both sides are , because . For , the tail has length , so by the induction hypothesis . Then
The last step is the identity for . It follows from Pascal's rule : summing over telescopes to , since for . The product form has the same proof with sums of exponents in place of sums, when all .
So a pure sum of length is a polynomial of degree at most in , and the coefficients are the forward differences of the sequence (finite differences, Newton's forward formula of Newton interpolation). Conversely, every polynomial of degree is the pure sum .
Rules. Let be invariant, and pure sums of the same loop. Each rule follows from the closed form or from :
| expression | chain |
|---|---|
| add the coefficients term by term, after padding the shorter chain with zeros | |
| , flattened | |
The product rule comes from , so the step of is , which is shorter in total length, so the recursion stops. For two chains of length 1: , and is the same polynomial.
Building the chains of a loop (compiler use).
- The normalized counter of loop is . A loop-invariant value is the chain of length 0.
- Visit the SSA names of the loop so that operands come before uses, and handle each cycle through a header φ as one unit (the strongly connected components of induction variable analysis).
- For a header φ
v = φ(init, v + e)where has the chain , set , flattened: if then . Forv = φ(init, c * v), set . - For other operations, apply the rules. A name defined after the update in the same iteration, such as
i2 = i1 + 1, gets the shifted chain . - Where no rule applies, mark the name as unknown, and every expression that uses it too.
- Use the chain: read the closed form, evaluate it at the last iteration for a trip count or an exit value, or emit the registers of EVAL-CR as new induction variables.
Classic examples
Evaluating a polynomial on a grid. Let . With , the rules give , so , , and
EVAL-CR starts with the registers and outputs , with two additions per value and no multiplication. These are , and are , and . In the same way ; the closed form gives .
The loop of the induction variable page. In the example loop of induction variable analysis:
| SSA name | definition | chain | closed form |
|---|---|---|---|
i1 |
φ(0, i1 + 1) |
||
t |
4 * i1 + 8 |
||
j1 |
φ(5, j1 + i1) |
||
k1 |
φ(1, 2 * k1) |
||
x1 |
φ(1, 2 * x1 + 1) |
The values of j1 are . The last row is a mixed chain: its step is , so , which gives .
Two nested loops. For for i in 0..M: for j in 0..N: A[i*N + j], the subscript is . The start value of the inner chain is a chain of the outer loop, and both are pure sums with invariant coefficients, so the subscript is affine in and the practical dependence tests apply. With the inner loop starts at and steps by 1.
Strength reduction. The chain of t says that t can be its own register, set to 8 before the loop and increased by 4 at the end of each iteration, as in operator strength reduction. For two registers do the job, and no multiplication is needed for a polynomial of any degree.
Variations
- Mixed chains. Chains with both and , such as above, describe sums of polynomials times geometric terms. Their closed forms are found by the definition, one level at a time, and do not have the single binomial formula.
- Multivariate chains. A chain whose coefficients are chains of outer loops, as in the nested example, describes a function of all loop counters of a nest. Later work on chains uses the same idea to evaluate functions of two variables on a grid, for example to plot surfaces.
- Symbolic coefficients. A coefficient can be an invariant name such as . The rules stay the same, with symbolic arithmetic in the coefficients, as in a computer algebra system.
- Monotonic ranges. If in a pure sum, then , so the sequence is nondecreasing, and its range over is . Bounds of this kind let a dependence test handle some nonlinear subscripts.
- Scalar evolution in LLVM. LLVM's ScalarEvolution builds add recurrences
{start,+,step}<loop>, with more operands for higher degree, together with flags that say whether the arithmetic can wrap. It uses them for trip counts, exit values, and the subscripts of its dependence analysis. The alias "scalar evolution" on this page is that name; it is the compiler analysis built on chains, not a different mathematical object. - Periodic and wrap-around values. Plain chains do not describe a value that flips between two states or has one special first value. Later work extends the notation for these cases, or peels the first iteration so that the rest is a chain.
Pitfalls
- Machine integers. EVAL-CR uses only additions and multiplications, so on -bit integers it computes exactly. The closed form does not: has a division by , which must happen before the reduction. On 8 bits, , but . For signed types in C, an overflow is undefined behavior, which lets a compiler assume no wrap; for unsigned types the wrap is defined and the chain only holds modulo . Check for integer overflow before a closed form is used for a trip count or a dependence test.
- Iteration numbering. The chain gives the value at the start of iteration for a header φ. A name defined after the update, such as
i2 = i1 + 1, has the chain , not . Mixing the two numberings shifts every subscript by one step. - Chains are not unique as written. and are the same function, and so are and . Remove trailing zeros (in sums) and trailing ones (in products) before comparing two chains.
- The step must be invariant or a chain of the same loop.
v = v + xwith anxthat is loaded from memory in each iteration is not a chain. Building a chain from it gives a wrong closed form, not just a weak one. - Products grow the chain. The product of chains of lengths and has length , and has length . Repeated products give long chains with large coefficients; compilers stop at a fixed length and mark the rest as unknown.
- Floating point. With floating-point coefficients, EVAL-CR adds a rounding error at each step and the errors build up over many iterations. For long runs, compute some values again from the closed form, or use exact or wider arithmetic for the registers.
- A product chain with a zero coefficient. In every value after the first is 0. The closed form is still correct with the rule , but code that takes logarithms of the coefficients fails.
Exercises
- Find the pure sum chain of in two ways: from the forward differences of , and from the product rule applied to and .
- Prove the rule from the closed form of a pure sum.
- Prove the closed form of a pure product chain by induction on its length, and say where the proof needs nonzero coefficients.
- A loop runs
s = φ(0, s + t)andt = φ(1, t + 2). Give the chains oftands, their closed forms, and the values for . - On 8-bit unsigned integers, run EVAL-CR for for 30 steps and compare each value with and with . At which does the second formula first differ?
- Show that a pure sum chain with is nondecreasing, and give a chain with that is still nondecreasing for all .
References
- Olaf Bachmann, Paul S. Wang and Eugene V. Zima, Chains of recurrences, a method to expedite the evaluation of closed-form functions, ISSAC 1994, pages 242 to 249, the definition of a chain of recurrences, the algebraic rules, and the evaluation of a function on a regular grid
- Robert A. van Engelen, Efficient symbolic analysis for optimizing compilers, CC 2001, LNCS 2027, pages 118 to 132, the use of chains of recurrences to recognize induction variables in a compiler, and the comparison with symbolic differencing
- Eugene V. Zima, On computational properties of chains of recurrences, ISSAC 2001, the closed forms of pure sum and pure product chains and the cost of evaluation
- Michael P. Gerlek, Eric Stoltz and Michael Wolfe, Beyond induction variables: detecting and classifying sequences using a demand-driven SSA form, ACM Transactions on Programming Languages and Systems 17(1), 1995, the classes of sequences (linear, polynomial, geometric) that the chains represent
- Ronald L. Graham, Donald E. Knuth and Oren Patashnik, Concrete Mathematics, second edition, Addison-Wesley, 1994, Section 5.1 (Pascal's rule and the summation of binomial coefficients on the upper index) and Section 2.6 (finite differences)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W0 stub |
|
Tag 2XRK3A Edit this page History Report an error Markdown