Algorithmadvanced
Array dataflow analysis
Also called Feautrier array dataflow, value-based dependence analysis.
Finds for each read of an array element the exact iteration that last wrote it, by parametric integer programming.
- Time
- O(s d (P + L)) worst
- Space
- O(L) extra
- Where
- L = the size of the largest quast that is built; P = the cost of one call of parametric integer programming (exponential in the worst case); d = the depth of the deepest loop nest; s = the number of statements that write the array
- Model
- Word RAM
- Properties
- deterministicrecursive
- Evidence
- Proof sketchCode in 1 languages
Array dataflow analysis takes a read of an array element in a loop program and finds, for every iteration that does the read, the exact iteration that last wrote that element before it. Paul Feautrier gave the method in 1991 for static control programs, where every loop bound and every array subscript is an affine function of the loop counters and of some integer size parameters. For each possible writer, the set of candidate iterations is a polyhedron that depends on the reading iteration, and its lexicographic maximum is found by parametric integer programming. The answer is a quast, a tree of affine tests whose leaves are affine formulas, and it holds for all values of the parameters at once.
In plain words
A program reads an array cell. Which earlier step put the value there? Ordinary dependence tests only say "some earlier step of that statement may have written this cell". This analysis says exactly which one. It looks at each statement that writes the array and asks: of the steps of this statement that wrote this cell before the read, which one was the latest? The steps form a shape bounded by straight lines, so this is an optimization over the whole numbers inside the shape. The answer is not one number but a small decision tree, because it depends on where the read happens and on the size of the arrays. At the end, the trees for all the writers are combined, and the latest writer wins. If no writer exists, the read sees the initial value.
The problem
Input. A static control program: statements in nested loops, with affine loop bounds and affine subscripts in the loop counters and in integer parameters that are only known at run time, and a context, a set of affine constraints on . Statement is inside loops, with counters . Its iteration domain is a polyhedron, bounded for each value of . It writes the array element , where is affine. A read in statement is given.
Execution order. The program runs in its text order. Instance runs before if they agree on the first of their common loops and for some , or if they agree on all common loops and comes before in the text of the innermost common loop. In the polyhedral model this is the lexicographic order of the -dimensional schedule vectors , where is the text position at depth .
Output. The source function : for each in the context and each , the instance that runs last among the instances that write before , or if there is none. It is given as a quast, a tree with nodes "if " for affine , nodes "let " that add new integer parameters, and leaves that are or with affine in , and the new parameters.
The algorithm
The algorithm splits the earlier writes into candidate sets. Each set comes from one writing statement and one depth: the depth is the loop that carries the order, or "same iteration" if the two instances share all common loops. Inside one candidate set, a later instance has a lexicographically greater vector , so the latest writer is the lexicographic maximum of an integer polyhedron with parameters and . Parametric integer programming (PIP) computes this maximum as a quast. A final merge compares the leaves of the quasts by their schedule vectors.
SOURCE(T, t, A[g(t)]) ▷ the read A[g(t)] in the instance T(t)- 1
Q <- the quast "no source" - 2
for each statement S that writes A[f_S(s)] do - 3
for each depth l in 1 .. c_ST, and "same iteration" if S is before T in the text do - 4
C <- { s in D_S : f_S(s) = g(t), s_1..s_{l-1} = t_1..t_{l-1}, s_l <= t_l - 1 } - 5
K <- PIP-LEXMAX(C) with the parameters t and N - 6
Q <- MERGE(Q, K): at each leaf, keep the source that runs later - 7
return Q PIP(rows, context) ▷ each row: x_i = c_i(p) + sum_j a_ij n_j >= 0- 8
if the context has no point then return "no solution" - 9
while some row has c_i(p) < 0 on the whole context do pivot on it, or return "no solution" if no a_ij > 0 - 10
if some row has c_i(p) of both signs on the context then return if c_i >= 0 then PIP(rows, context and c_i >= 0) else PIP(rows, context and c_i <= -1)- 11
k <- an unknown x_k whose constant c_k(p) is not integer-valued - 12
if there is none then return the leaf (c_1(p), ..., c_n(p)) - 13
if the fractional part f of c_k is a constant then add the cut row -f + sum_j frac(-a_kj) n_j >= 0 and go to L9 - 14
add the parameter q = floor(D f(p) / D) and the cut row q - f(p) + sum_j frac(-a_kj) n_j >= 0, and go to L9
For the "same iteration" depth, line L4 uses for all common loops and no strict inequality.
PIP. The tableau describes every unknown and every constraint as , where the are the current nonbasic variables and is affine in the parameters . At the start, the nonbasic variables are the unknowns. The constant column is the current solution. Line L9 is the dual simplex method with a lexicographic pivot rule. Among the columns with , it picks the one whose whole column divided by is lexicographically least, so that the columns stay lexicographically positive and the basic solution stays the lexicographic minimum. The sign of depends on , so the test is a feasibility test of the context plus one constraint, and when both signs occur, line L10 splits the context into two parts. Lines L13 and L14 are Gomory cuts. When the fractional part depends on , it is not affine, and Feautrier writes it with a new parameter . The new parameter is defined by the two context constraints .
Maximum instead of minimum. PIP finds a lexicographic minimum over . The implementation sets for a symbolic parameter that is larger than every other value. The sign of a form with an term is the sign of its coefficient.
Merge. Line L6 walks the two quasts together, adding the tests of both to the context. At a pair of leaves and , it compares the schedule vectors and one component at a time. Each comparison is a three-way split on the sign of an affine difference, and the first nonzero difference decides. Branches whose context has no point are dropped.
Example
Take a lower triangular matrix-vector product:
for i = 0 to N - 1:
S1: y[i] = 0
for j = 0 to i:
S2: y[i] = y[i] + L[i][j] * x[j]
Consider the read of y[i] in . Both statements write y.
- has one common loop with . At depth 1, the candidates satisfy (same element) and , which is empty. At the "same iteration" depth, comes before the loop in the text, and the set is . Its maximum is .
- has two common loops with itself. Depth 1 is empty again. At depth 2 the set is . PIP returns if and no solution otherwise. "Same iteration" does not apply, because an instance does not run before itself.
The merge compares with . They differ first in the third component, so is later. The source is
The implementation prints this tree. A memory-based test says only that the read depends on and on many instances of ; the source keeps one instance.
A new parameter. In
for i = 0 to N: S1: A[2i] = ...
for j = 0 to 2N: S2: B[j] = A[j]
the candidates for the read in are . The rational maximum is , which is not an integer for odd . Line L14 adds , and the result is: if , that is, is even, the source is ; otherwise there is no source and the read sees the initial value of A[t]. A test such as even cannot be written with affine tests on and alone, which is why quasts need the new parameters.
Along a diagonal. For A[i+j] = A[i+j] + 1 inside two loops over , the source of the read in is if and , and the initial value otherwise. The candidate set at depth 2 is empty, because and force .
Correctness
The full proof is in the proof page. It has four steps. First, an instance writes before exactly when is in one of the candidate sets of line L4, and these sets are disjoint. Second, inside one candidate set, the order of execution is the lexicographic order of , because all its points belong to one statement. Third, PIP returns the integer lexicographic minimum for every parameter value of the context: the lexicographic dual simplex keeps the basic solution equal to the minimum of the rational relaxation, splits partition the context, and every Gomory cut is satisfied by all integer points and cuts off a fractional basic solution. Fourth, the merge keeps, for each parameter value, the later of two instances, because it compares the full schedule vectors. So the result is the latest of all earlier writes of the element, which is the definition of the source. The method is exact: it makes no approximation, as long as bounds and subscripts are affine.
Proof: Array dataflow analysis returns the exact last writer for static control programsfull
Setting. We use the notation of the page. The program is a static control program with integer parameters that satisfy the context . Statement has depth , a domain that is a polyhedron and is bounded for each , and writes with affine. The read is in , with . All counters and parameters are integers. For two statements, is the number of common loops, and is the text position of (or of the loop that holds it) at depth . The schedule of is , and the program runs the instances in the lexicographic order of their schedules. Two different statements in a common loop have different text positions at the first depth where they are not in the same loop, so two different instances never have the same schedule.
Claim. For every in and every , the quast returned at line L7, evaluated at , gives the instance with the lexicographically greatest schedule among the instances that write and have a schedule less than , or if there is no such instance.
Step 1: the candidate sets cover the earlier writes, and are disjoint
For a statement that writes and a depth , let
and if , let . These are the sets of line L4.
Lemma 1. if and only if satisfies the depth condition of exactly one of these sets.
Proof. The first components of the two schedules are and , with the same , because the statements share the loops 1 to . Let be the first with , if there is one. Then the schedules differ first at the component of , and exactly when , that is, for integers. This is the condition of . If there is no such , the next component is against . If , then on all loops, the instance is itself, and it is not earlier. Otherwise , by the remark in the setting, and the order is decided there: is earlier exactly when . This is the set , which line L3 builds only in that case. The first index is unique, so the cases are disjoint.
The access condition selects the writes of the element that reads. So the union over all and all depths of the candidate sets is exactly the set of earlier writes of , and each such write is in exactly one set.
Step 2: inside one candidate set, later means lexicographically greater
Lemma 2. For , if and only if .
Proof. Both schedules have the same constants at the same positions, and the counters in between. The first difference is at the first counter where and differ, with the same sign.
So the latest instance in a candidate set is its lexicographic maximum.
Step 3: PIP returns the integer lexicographic optimum for every parameter value
PIP works on a tableau whose rows are , where are the parameters (here , and the new parameters), the are the nonbasic variables, and every row must be . The first rows are the unknowns. At the start the nonbasic variables are the unknowns themselves, so these rows form the identity matrix. We call this tableau lex-positive when every column is lexicographically positive.
The unknowns of line L5 are , where is a symbolic parameter. For fixed and the candidate set is bounded, so for large enough all are nonnegative and the lexicographic minimum of is reached at the lexicographic maximum of . The sign of an affine form with a nonzero coefficient is the sign of that coefficient for large enough, so the sign tests are correct for all large .
Lemma 3 (invariant). At every step, (a) the tableau is lex-positive, (b) every integer point of the current problem is also a point of the original problem and conversely, every integer point of the original problem with parameters in the current context satisfies all the rows, and (c) the context is a subset of the original context, and the new parameters satisfy their definitions .
Proof. At the start the tableau is the identity in the unknown rows, so it is lex-positive, and (b) and (c) hold. A pivot at line L9 on row with uses the column with whose column divided by is lexicographically least. A pivot is an invertible affine change of the nonbasic variables, so the unknown rows always form an invertible matrix, and every column is nonzero in its first entries. Each new column is . If , it is plus a nonnegative multiple of , so it is lex-positive. If , it is , which is lexicographically nonnegative by the choice of and is not zero by the remark above, so it is lex-positive. The new column is , which is lex-positive. A pivot only rewrites the same equations with another set of nonbasic variables, so (b) holds. A split at line L10 adds a constraint to the context and changes no row. A cut at line L13 or L14 adds a row at the bottom, and Lemma 4 shows that every integer point satisfies it. The sign of a column is decided in its first entries, so a new row at the bottom keeps (a). The new parameter of line L14 comes with its two defining constraints, which gives (c).
Lemma 4 (cuts). Let row be , with and all integers. Then every integer point satisfies . The new row has an integer value at every integer point.
Proof. Write and split each number into its floor and its fractional part: . The left side is an integer. The right side is less than 1, because and the sum is nonnegative. So it is at most 0, which is the cut. The slack of the cut is the negative of the left side, an integer. When has parameter terms, the code first replaces every coefficient by its fractional part, which changes by an integer for integer ; call the result . With the common denominator, is an integer and , which is affine in and . So the row of line L14 is the same cut.
The nonbasic variables are always unknowns or slacks of rows with integer values: the unknowns, the slacks of the constraints, which have integer coefficients, and the slacks of earlier cuts, which are integers by Lemma 4. So Lemma 4 applies at every step.
Lemma 5. Each leaf of the quast that PIP returns is correct on its context: (i) if it is "no solution", no integer point of the problem has parameters in the context; (ii) if it is , then for every integer in the context this point is the integer lexicographic minimum.
Proof. (i) Line L8 returns "no solution" only if the context has no rational point, so it has no integer point. Line L9 returns it for a row with on the whole context and all ; then for every , so no point satisfies the row, and by Lemma 3 (b) the problem has no integer point. (ii) At line L12, every row has on the context, because the sign tests of lines L9 and L10 found no negative and no mixed constant. Setting all gives , which satisfies every row. Any other point of the current rational problem has some . Its unknowns are , where is the part of column in the first rows. Each is lex-positive, so a nonnegative combination of them that is not all zero is lex-positive, and the point is lexicographically greater than . So is the rational lexicographic minimum of the current problem. All its coordinates are integers, because line L11 found no row with a non-integral constant. The current problem contains every integer point of the original problem, by Lemma 3 (b), so is the integer lexicographic minimum.
The split at line L10 adds to one branch and to the other, where is scaled to integer coefficients, so for integer parameters the two branches cover the context. The implementation also proves a row integral when it finds a new parameter that is already defined with the same numerator and denominator and the context forces ; then equals an integer form on the context, which is a rewriting and changes no value. So the quast of PIP, evaluated at any integer in the context, follows one path to a correct leaf.
Termination. The lemmas above show partial correctness: whenever PIP returns, its answer is right. Termination rests on Gomory's argument for the lexicographic dual simplex with cuts, which Feautrier's method follows: the lexicographic minimum grows strictly with each cut and stays in a bounded set. The implementation adds a depth limit that raises an error, so it never returns a wrong answer silently.
Step 4: the merge keeps the later source
Lemma 6. For every integer point of the context, the quast gives the later of the two instances that and give at that point, where an instance is later than .
Proof. Merge walks down and then , adding to the context the test of each node it passes or its negation . For integer points the two branches of a node cover its context, so every integer point reaches the pair of leaves that and give there. If one leaf is , merge returns the other. Otherwise it compares and component by component: at component it splits the context into the difference , and , which for integers covers all cases, and goes to component only in the third case. The first nonzero difference decides the lexicographic order, which is the execution order. If one vector is a prefix of the other, the leaves are the same instance (two different instances have different schedules, and both are then the same statement and point), and either is correct. A branch whose context has no rational point has no integer point, so dropping it loses nothing.
The function simplify, used after each merge, only drops branches without rational points and replaces a node by one of its subtrees when it proves, with rational tests on integer-valued differences, that both give the same instance at every point of the node's context. It changes no value at an integer point.
Conclusion
By Lemma 1, the earlier writes of the element are partitioned into the candidate sets. By Lemmas 2 and 5, the quast of line L5 gives the latest write in its set, or if the set is empty. By Lemma 6 and induction on the number of sets merged so far, after line L6 the quast gives the latest instance among all sets seen so far. After the last set, it gives the latest of all earlier writes of , or when there is none. This is the source.
Complexity
The algorithm runs one PIP for each writing statement and each depth, at most calls for one read. PIP solves integer programs, so it is NP-hard in general, and the quast it returns can have exponentially many leaves. PIP terminates by the same argument as Gomory's method with a lexicographic rule, but the number of cuts has no polynomial bound. The merge visits each pair of leaves and does at most three-way splits, each with a few rational feasibility tests. In practice the candidate sets have few constraints and the quasts are small, and the cost is close to that of a few exact dependence tests per read.
The implementation on this page uses an exact rational simplex for the context tests and computes the brute-force sources on small loop bounds only for testing.
Properties
- Exact. For static control programs the result is the exact source at every iteration and every value of the parameters.
- Value based. It reports the flow of values, not the reuse of memory cells. A write that is overwritten before the read gives no edge, unlike a memory-based data dependence.
- Parametric. The result holds for all sizes at once. The tests in the tree are affine, plus the new parameters of the form .
- A function. For each read the source is one instance or , never a set. This makes the result a direct input for array expansion into single assignment form and for array privatization.
Variants and improvements
- Fuzzy array dataflow analysis. Barthou, Collard and Feautrier extend the method to programs with conditionals and non-affine subscripts. The source then becomes a set of possible instances, described with new free parameters.
- Presburger formulation. Pugh and Wonnacott compute the same value-based dependences as formulas of Presburger arithmetic and solve them with the omega test.
- Last write trees. Maydan, Amarasinghe and Lam compute the same trees with faster tests that are exact for the common cases, and use them for array privatization.
- Scalars. A scalar is an array of dimension zero, so the same algorithm gives exact reaching definitions inside loops at the level of instances.
- Scheduling input. Feautrier's scheduling and the affine scheduling problem use the source functions as the dependence edges of the program. A schedule has to respect only the flow from source to read, after array expansion has removed the other dependences.
When to use it
Use it when the compiler needs to know where a value comes from, not only whether two accesses touch the same cell: to expand arrays into single assignment form and remove false dependences, to privatize arrays, to find parallelism that the memory-based dependences hide, or to build the dataflow graph for polyhedral scheduling. If only the legality of one transformation is needed, the cheaper dependence tests are enough.
Pitfalls
- Affine only. The candidate sets are polyhedra only when bounds and subscripts are affine in the counters and the parameters. An index array
A[P[i]], a producti * jin a subscript, or a data-dependentiftakes the program out of the model. The plain method then does not apply; the fuzzy variant gives sets of possible sources. - Bounded domains. The maximum exists only if the candidate set is bounded for each parameter value. A loop with no upper bound, or a context that allows negative sizes where the code expects positive ones, makes the problem ill posed.
- Integers, not rationals. The rational maximum of a candidate set can be a point that is not an iteration, as in the even-index example. The Gomory cuts and the new parameters are needed, and leaving them out gives a wrong source.
- Context feasibility. The tests that drop a branch must be sound for integers. A rational test may keep a branch that has no integer point, which only makes the tree larger, but a test that drops a branch with an integer point gives a wrong answer.
- Aliasing. The method assumes that two different array names never share memory. Programs where arrays overlap need a different model.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/feautrier-array-dataflow/. The authors are listed in prov/61C0MP.jsonl.
"""Feautrier's array dataflow analysis for static control programs.
For a read of an array cell by an instance T(t), the source is the last
instance S(s), in the original order, that wrote that cell before T(t).
The analysis finds it as a quast (a quasi-affine selection tree) in the
coordinates of t and the structure parameters:
* for each write reference and each depth of common loops, the set of
candidate sources is a polyhedron in s with parameters (t, N);
* its lexicographic maximum is found by parametric integer programming
(PIP), a parametric dual simplex with Gomory cuts, which may add new
parameters q = floor(e / D);
* the candidates are combined by keeping, for each value of the
parameters, the one that runs last.
Affine forms are dicts from variable names to Fractions; the key "" holds
the constant. A constraint is a form e with the meaning e >= 0. Everything is
exact rational arithmetic.
A quast is one of
("leaf", None) no source: the initial value is read
("leaf", (S, [forms])) the instance S(forms)
("if", e, then, else) e >= 0 ? then : else (e integer-valued)
("div", q, e, D, sub) let q = floor(e / D), then sub
"""
from fractions import Fraction
from itertools import count, product
from math import floor, gcd, lcm
BIG = "M" # a parameter larger than any other value (big-M, kept symbolic)
# ---------------------------------------------------------------- affine forms
def form(d=None, const=0):
out = {k: Fraction(v) for k, v in (d or {}).items() if v}
if const:
out[""] = out.get("", Fraction(0)) + Fraction(const)
return out
def add(a, b, k=1):
out = dict(a)
for v, c in b.items():
out[v] = out.get(v, Fraction(0)) + k * c
if out[v] == 0:
del out[v]
return out
def scale(a, k):
return {v: c * k for v, c in a.items() if c * k != 0}
def evaluate(a, env):
return sum((c * (env[v] if v else 1) for v, c in a.items()), Fraction(0))
def denom(a):
return lcm(*[c.denominator for c in a.values()]) if a else 1
def frac(x):
return x - floor(x)
def rename(a, names):
return {names.get(v, v): c for v, c in a.items()}
def show_form(a):
terms = []
for v in sorted(k for k in a if k):
c = a[v]
s = v if c == 1 else f"-{v}" if c == -1 else f"{c}*{v}"
terms.append(s)
if a.get("", 0) or not terms:
terms.append(str(a.get("", 0)))
return " + ".join(terms).replace("+ -", "- ")
# ------------------------------------------------------------ rational simplex
def _reduce(row):
g = gcd(*row)
return [x // g for x in row] if g > 1 else row
def lp_feasible(cons):
"""Is {x : e(x) >= 0 for e in cons} nonempty over the rationals? The
forms must have integer coefficients. Phase 1 of the simplex method with
Bland's rule, on integer rows (each row is kept up to a positive factor).
The variables are free, so each one is split as x = x+ - x-."""
names = sorted({v for e in cons for v in e if v})
if all(e.get("", 0) >= 0 for e in cons):
return True # x = 0 works
nv, m = len(names), len(cons)
bad = [r for r, e in enumerate(cons) if e.get("", 0) < 0]
# columns: x+ (nv), x- (nv), slack (m), artificial (len(bad)), rhs
width = 2 * nv + m + len(bad) + 1
rows, basis = [], []
for r, e in enumerate(cons):
row = [0] * width
c = int(e.get("", 0))
for j, v in enumerate(names):
a = int(e.get(v, 0))
row[j], row[nv + j] = a, -a
if c >= 0: # s = a.x + c, basic
row = [-x for x in row]
row[2 * nv + r], row[-1] = 1, c
basis.append(2 * nv + r)
else: # a.x - s + art = -c
k = 2 * nv + m + bad.index(r)
row[2 * nv + r], row[k], row[-1] = -1, 1, -c
basis.append(k)
rows.append(row)
art0 = 2 * nv + m
obj = [0] * width # reduced costs of sum(art)
for r in bad:
obj = [x - y for x, y in zip(obj, rows[r])]
for j in range(art0, width - 1):
obj[j] = 0
while True:
enter = next((j for j in range(width - 1) if obj[j] < 0), None)
if enter is None:
break
leave = None
for r in range(m):
a = rows[r][enter]
if a > 0:
if leave is None:
leave = r
continue
lhs = rows[r][-1] * rows[leave][enter]
rhs = rows[leave][-1] * a
if lhs < rhs or (lhs == rhs and basis[r] < basis[leave]):
leave = r
if leave is None:
break
pr = rows[leave]
p = pr[enter]
for r in range(m):
k = rows[r][enter]
if r != leave and k:
rows[r] = _reduce([p * x - k * y for x, y in zip(rows[r], pr)])
k = obj[enter]
obj = _reduce([p * x - k * y for x, y in zip(obj, pr)])
basis[leave] = enter
return obj[-1] == 0
_cache = {}
def tighten(e):
"""Scale e >= 0 to integer coefficients with gcd 1 and round the constant
down. Every variable here is an integer, so no integer point is lost.
Returns a sorted tuple of (variable, int) pairs."""
d = 1
for c in e.values():
if c.denominator != 1:
d = lcm(d, c.denominator)
ints = {v: c.numerator * (d // c.denominator) for v, c in e.items()}
g = gcd(*[c for v, c in ints.items() if v])
if g > 1:
ints = {v: (c // g) for v, c in ints.items()} # floor for the constant
return tuple(sorted((v, c) for v, c in ints.items() if c))
def feasible(cons):
"""Rational feasibility of the tightened system. False means that there
is no integer point; True may hold with no integer point."""
key = frozenset(tighten(e) for e in cons)
if key not in _cache:
_cache[key] = lp_feasible([dict(k) for k in key])
return _cache[key]
# --------------------------------------------------------------------- PIP
_names = count()
def sign(c, ctx):
"""'pos' if c >= 0 on the context, 'neg' if c < 0, else 'mixed'.
The big parameter M decides the sign when it appears."""
m = c.get(BIG, 0)
if m:
return "pos" if m > 0 else "neg"
d = denom(c)
if not feasible(ctx + [add(scale(c, -d), form(const=-1))]):
return "pos"
if not feasible(ctx + [c]):
return "neg"
return "mixed"
def pivot(rows, r, n):
"""Lexicographic dual simplex pivot on row r. Returns False if row r has
no positive entry (no solution)."""
cand = [j for j, a in enumerate(rows[r][1]) if a > 0]
if not cand:
return False
key = lambda j: [row[1][j] / rows[r][1][j] for row in rows]
j = min(cand, key=key)
arj = rows[r][1][j]
cr, ar = rows[r][0], rows[r][1]
for i, (ci, ai) in enumerate(rows):
aij = ai[j]
if aij == 0:
continue
f = aij / arj
newc = add(ci, cr, -f)
newa = [a - f * b for a, b in zip(ai, ar)]
newa[j] = f
rows[i] = (newc, newa)
return True
def pip(rows, n, ctx, depth=0, divs=()):
"""Lexicographic minimum of the n unknowns (rows 0..n-1), all >= 0 and
integer, subject to every row >= 0, as a quast in the parameters.
`divs` lists the parameters (q, numerator, d) with q = floor(num / d)
already defined on this path."""
if not feasible(ctx): # @line L8
return ("leaf", None)
if depth > 80:
raise RuntimeError("PIP: too deep")
rows = [(dict(c), list(a)) for c, a in rows]
while True:
mixed = None
for r, (c, a) in enumerate(rows):
s = sign(c, ctx)
if s == "neg":
break
if s == "mixed" and mixed is None:
mixed = r
else:
r = None
if r is not None: # @line L9
if not pivot(rows, r, n):
return ("leaf", None)
continue
if mixed is not None: # @line L10
c = rows[mixed][0]
e = scale(c, denom(c))
yes = pip(rows, n, ctx + [e], depth + 1, divs)
no = pip(rows, n, ctx + [add(scale(e, -1), form(const=-1))], depth + 1, divs)
return ("if", e, yes, no)
k = next((k for k in range(n) # @line L11
if any(v.denominator != 1 for v in rows[k][0].values())), None)
if k is None:
return ("leaf", [rows[k][0] for k in range(n)]) # @line L12
c = rows[k][0]
assert c.get(BIG, Fraction(0)).denominator == 1
fc = {v: frac(x) for v, x in c.items() if v != BIG and frac(x)}
# x = c + sum a_j n_j with x and all n_j integer gives the cut
# sum frac(-a_j) n_j >= frac(c)
cut_a = [frac(-x) for x in rows[k][1]]
if not any(fc.get(v) for v in fc if v):
# a constant fraction: the classic Gomory cut
rows.append((form(const=-fc[""]), cut_a)) # @line L13
return pip(rows, n, ctx, depth + 1, divs)
d = denom(fc)
num = scale(fc, d) # integer-valued numerator
old = next((q for q, nm, dd in divs if dd == d and nm == num), None)
if old is not None:
if not feasible(ctx + [add(num, form({old: -d}, -1))]):
# the context forces num = d * q, so the fraction is zero
rows[k] = (add(add(c, fc, -1), form({old: 1})), rows[k][1])
return pip(rows, n, ctx, depth + 1, divs)
rows.append((add(form({old: 1}), fc, -1), cut_a))
return pip(rows, n, ctx, depth + 1, divs)
q = f"q{next(_names)}"
ctx2 = ctx + [add(num, form({q: -d})), add(form({q: d}, d - 1), num, -1)]
rows.append((add(form({q: 1}), fc, -1), cut_a)) # @line L14
return ("div", q, num, d, pip(rows, n, ctx2, depth + 1, divs + ((q, num, d),)))
def lexmax(svars, cons, ctx):
"""Parametric lexmax of the integer points s with cons(s, params) >= 0.
Uses x_k = M - s_k >= 0 and the lexicographic minimum of x."""
n = len(svars)
rows = []
for k in range(n):
a = [Fraction(0)] * n
a[k] = Fraction(1)
rows.append((form(), a))
for e in cons:
a = [-e.get(v, Fraction(0)) for v in svars]
c = {v: x for v, x in e.items() if v not in svars}
msum = sum((e.get(v, Fraction(0)) for v in svars), Fraction(0))
if msum:
c[BIG] = c.get(BIG, Fraction(0)) + msum
rows.append((c, a))
return map_leaves(pip(rows, n, ctx), lambda xs: [add(form({BIG: 1}), x, -1) for x in xs])
def map_leaves(t, f):
if t[0] == "leaf":
if t[1] is None:
return t
out = f(t[1])
for e in out:
assert BIG not in e, "lexmax is unbounded"
return ("leaf", out)
if t[0] == "if":
return ("if", t[1], map_leaves(t[2], f), map_leaves(t[3], f))
return ("div", t[1], t[2], t[3], map_leaves(t[4], f))
# ------------------------------------------------------------ static programs
class Stmt:
"""A statement inside loops with iterators `iters`. `betas` has length
len(iters) + 1 and gives the textual position at each depth, so the
original schedule is (betas[0], i1, betas[1], i2, ..., betas[d])."""
def __init__(self, name, iters, betas, domain, write, reads):
self.name, self.iters, self.betas = name, iters, betas
self.domain = domain # list of forms >= 0 over iters and params
self.write = write # (array, [forms])
self.reads = reads # list of (array, [forms])
def theta(self, point):
out = [self.betas[0]]
for x, b in zip(point, self.betas[1:]):
out += [x, b]
return out
class Program:
def __init__(self, params, context, stmts):
self.params = params # names of the structure parameters
self.context = context # forms >= 0 over the parameters
self.stmts = stmts
self.by_name = {s.name: s for s in stmts}
def common_loops(S, T):
c = 0
while c < min(len(S.iters), len(T.iters)) and S.betas[c] == T.betas[c]:
c += 1
return c
def theta_forms(S, sforms):
out = [form(const=S.betas[0])]
for x, b in zip(sforms, S.betas[1:]):
out += [x, form(const=b)]
return out
def split3(e, ctx, pos, neg, zero):
"""Build a quast on the sign of the form e: pos(ctx), neg(ctx), zero(ctx)."""
d = denom(e)
e = scale(e, d)
gt = add(e, form(const=-1)) # e >= 1
lt = add(scale(e, -1), form(const=-1)) # e <= -1
eq = [e, scale(e, -1)]
branches = []
if feasible(ctx + [gt]):
branches.append((gt, pos(ctx + [gt])))
if feasible(ctx + [lt]):
branches.append((lt, neg(ctx + [lt])))
if feasible(ctx + eq):
branches.append((None, zero(ctx + eq)))
if not branches:
return ("leaf", None)
tree = branches[-1][1]
for cond, sub in reversed(branches[:-1]):
tree = ("if", cond, sub, tree)
return tree
def later(prog, a, b, ctx):
"""Quast that picks, of the leaves a and b, the one that runs later."""
if a is None:
return ("leaf", b)
if b is None:
return ("leaf", a)
ta = theta_forms(prog.by_name[a[0]], a[1])
tb = theta_forms(prog.by_name[b[0]], b[1])
def cmp(k, ctx):
if k >= min(len(ta), len(tb)):
return ("leaf", a)
return split3(add(tb[k], ta[k], -1), ctx,
lambda c: ("leaf", b), lambda c: ("leaf", a), lambda c: cmp(k + 1, c))
return cmp(0, ctx)
def merge(prog, q1, q2, ctx):
"""For each parameter value, the later of the sources given by q1 and q2."""
if not feasible(ctx):
return ("leaf", None)
if q1[0] == "if":
e = q1[1]
no = add(scale(e, -1), form(const=-1))
return ("if", e, merge(prog, q1[2], q2, ctx + [e]), merge(prog, q1[3], q2, ctx + [no]))
if q1[0] == "div":
_, q, num, d, sub = q1
ctx2 = ctx + [add(num, form({q: -d})), add(form({q: d}, d - 1), num, -1)]
return ("div", q, num, d, merge(prog, sub, q2, ctx2))
if q2[0] == "if":
e = q2[1]
no = add(scale(e, -1), form(const=-1))
return ("if", e, merge(prog, q1, q2[2], ctx + [e]), merge(prog, q1, q2[3], ctx + [no]))
if q2[0] == "div":
_, q, num, d, sub = q2
ctx2 = ctx + [add(num, form({q: -d})), add(form({q: d}, d - 1), num, -1)]
return ("div", q, num, d, merge(prog, q1, sub, ctx2))
return later(prog, q1[1], q2[1], ctx)
def source(prog, T, ref):
"""The quast of the source of read reference `ref` of statement T, in
the variables t0, t1, ... (the instance of T) and the parameters."""
arr, subs = ref
tn = {v: f"t{k}" for k, v in enumerate(T.iters)}
tsubs = [rename(e, tn) for e in subs]
ctx = [rename(e, tn) for e in T.domain] + list(prog.context)
quast = ("leaf", None) # @line L1
for S in prog.stmts: # @line L2
if S.write[0] != arr:
continue
sn = {v: f"s{k}" for k, v in enumerate(S.iters)}
svars = [f"s{k}" for k in range(len(S.iters))]
base = [rename(e, sn) for e in S.domain]
for a, b in zip(S.write[1], tsubs):
eq = add(rename(a, sn), b, -1)
base += [eq, scale(eq, -1)]
c = common_loops(S, T)
levels = list(range(1, c + 1))
if S.betas[c] < T.betas[c]:
levels.append(None) # loop independent
for l in levels: # @line L3
cons = list(base)
for k in range((c if l is None else l - 1)):
e = form({svars[k]: 1, f"t{k}": -1})
cons += [e, scale(e, -1)]
if l is not None:
cons.append(form({f"t{l - 1}": 1, svars[l - 1]: -1}, -1)) # @line L4
cand = lexmax(svars, cons, ctx) # @line L5
quast = simplify(merge(prog, quast, tag(cand, S.name), ctx), ctx) # @line L6
return quast # @line L7
def tag(t, name):
if t[0] == "leaf":
return t if t[1] is None else ("leaf", (name, t[1]))
if t[0] == "if":
return ("if", t[1], tag(t[2], name), tag(t[3], name))
return ("div", t[1], t[2], t[3], tag(t[4], name))
def eval_quast(t, env):
"""The source at a concrete point: None or (statement, tuple of ints)."""
env = dict(env)
while True:
if t[0] == "leaf":
if t[1] is None:
return None
name, xs = t[1]
vals = [evaluate(e, env) for e in xs]
assert all(v.denominator == 1 for v in vals)
return name, tuple(int(v) for v in vals)
if t[0] == "if":
t = t[2] if evaluate(t[1], env) >= 0 else t[3]
else:
_, q, num, d, sub = t
env[q] = floor(evaluate(num, env) / d)
t = sub
def same_leaf(a, b, ctx):
"""Do two leaves name the same instance for every point of the context?"""
if a is None or b is None:
return a is b
if a[0] != b[0]:
return False
for x, y in zip(a[1], b[1]):
d = add(x, y, -1)
if feasible(ctx + [add(d, form(const=-1))]) or \
feasible(ctx + [add(scale(d, -1), form(const=-1))]):
return False
return True
def agree(a, b, ctx):
"""Do the quasts a and b give the same instance at every point of ctx?
The test is sound but may answer False when the answer is True."""
if not feasible(ctx):
return True
for x, y in ((a, b), (b, a)):
if x[0] == "if":
e = x[1]
no = add(scale(e, -1), form(const=-1))
return agree(x[2], y, ctx + [e]) and agree(x[3], y, ctx + [no])
if x[0] == "div":
_, q, num, d, sub = x
ctx2 = ctx + [add(num, form({q: -d})), add(form({q: d}, d - 1), num, -1)]
return agree(sub, y, ctx2)
return same_leaf(a[1], b[1], ctx)
def simplify(t, ctx=()):
"""Drop branches that the context makes empty, and conditions whose two
branches give the same instance on the context."""
ctx = list(ctx)
if t[0] == "if":
e = t[1]
no = add(scale(e, -1), form(const=-1))
if not feasible(ctx + [e]):
return simplify(t[3], ctx)
if not feasible(ctx + [no]):
return simplify(t[2], ctx)
a, b = simplify(t[2], ctx + [e]), simplify(t[3], ctx + [no])
if a == b or agree(a, b, ctx + [e]):
return b
if agree(a, b, ctx + [no]):
return a
return ("if", e, a, b)
if t[0] == "div":
_, q, num, d, sub = t
ctx2 = ctx + [add(num, form({q: -d})), add(form({q: d}, d - 1), num, -1)]
sub = simplify(sub, ctx2)
return sub if q not in repr(sub) else ("div", q, num, d, sub)
return t
def show(t, indent=0):
pad = " " * indent
if t[0] == "leaf":
if t[1] is None:
return [pad + "no source (initial value)"]
name, xs = t[1]
return [pad + f"{name}[{', '.join(show_form(e) for e in xs)}]"]
if t[0] == "if":
return ([pad + f"if {show_form(t[1])} >= 0:"] + show(t[2], indent + 1)
+ [pad + "else:"] + show(t[3], indent + 1))
return [pad + f"let {t[1]} = floor(({show_form(t[2])}) / {t[3]})"] + show(t[4], indent)
# --------------------------------------------------------------- brute force
def instances(prog, env, box):
out = []
for S in prog.stmts:
for p in product(range(-box, box + 1), repeat=len(S.iters)):
e = dict(env)
e.update(zip(S.iters, p))
if all(evaluate(c, e) >= 0 for c in S.domain):
out.append((S.theta(p), S, p))
out.sort(key=lambda x: x[0])
return out
def brute_sources(prog, env, box):
"""Map (T, read index, t) to the last writer of the cell before T(t)."""
last, out = {}, {}
for _, S, p in instances(prog, env, box):
e = dict(env)
e.update(zip(S.iters, p))
for r, (arr, subs) in enumerate(S.reads):
cell = (arr,) + tuple(evaluate(x, e) for x in subs)
out[(S.name, r, p)] = last.get(cell)
arr, subs = S.write
last[(arr,) + tuple(evaluate(x, e) for x in subs)] = (S.name, p)
return out
# ------------------------------------------------------------------ examples
def F(**kw):
c = kw.pop("c", 0)
return form(kw, c)
def matvec():
"""for i = 0 to N-1: S1: y[i] = 0; for j = 0 to i: S2: y[i] = y[i] + L[i][j] * x[j]"""
s1 = Stmt("S1", ["i"], [0, 0], [F(i=1), F(N=1, i=-1, c=-1)], ("y", [F(i=1)]), [])
s2 = Stmt("S2", ["i", "j"], [0, 1, 0], [F(i=1), F(N=1, i=-1, c=-1), F(j=1), F(i=1, j=-1)],
("y", [F(i=1)]), [("y", [F(i=1)]), ("L", [F(i=1), F(j=1)]), ("x", [F(j=1)])])
return Program(["N"], [F(N=1, c=-1)], [s1, s2])
def even_writes():
"""for i = 0 to N: S1: A[2i] = ...; for j = 0 to 2N: S2: B[j] = A[j]"""
s1 = Stmt("S1", ["i"], [0, 0], [F(i=1), F(N=1, i=-1)], ("A", [F(i=2)]), [])
s2 = Stmt("S2", ["j"], [1, 0], [F(j=1), F(N=2, j=-1)], ("B", [F(j=1)]), [("A", [F(j=1)])])
return Program(["N"], [F(N=1)], [s1, s2])
def diagonal():
"""for i = 0 to N: for j = 0 to N: S: A[i+j] = A[i+j] + 1"""
s = Stmt("S", ["i", "j"], [0, 0, 0], [F(i=1), F(N=1, i=-1), F(j=1), F(N=1, j=-1)],
("A", [F(i=1, j=1)]), [("A", [F(i=1, j=1)])])
return Program(["N"], [F(N=1)], [s])
if __name__ == "__main__":
for name, prog, T, r in [("matvec", matvec(), "S2", 0), ("even", even_writes(), "S2", 0),
("diagonal", diagonal(), "S", 0)]:
print(name)
print("\n".join(show(source(prog, prog.by_name[T], prog.by_name[T].reads[r]), 1)))
test_feautrier_array_dataflow.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/feautrier-array-dataflow/. The authors are listed in prov/61C0MP.jsonl.
"""Tests: the symbolic source of every read must match a brute-force search
for the last writer, at every instance, for several values of N."""
import random
import unittest
from feautrier_array_dataflow import (
F, Program, Stmt, brute_sources, diagonal, eval_quast, even_writes, lexmax,
matvec, source, form,
)
def check(test, prog, ns, box=None):
"""Compare the quast of every read with the brute-force last writer."""
quasts = {}
for T in prog.stmts:
for r, ref in enumerate(T.reads):
quasts[(T.name, r)] = source(prog, T, ref)
count = 0
for n in ns:
env = {"N": n}
brute = brute_sources(prog, env, box if box is not None else 2 * n + 2)
for (name, r, point), want in brute.items():
e = dict(env)
e.update({f"t{k}": x for k, x in enumerate(point)})
got = eval_quast(quasts[(name, r)], e)
test.assertEqual(got, want, f"{name} read {r} at {point}, N={n}")
count += 1
return quasts, count
class Examples(unittest.TestCase):
def test_matvec(self):
quasts, count = check(self, matvec(), range(1, 6))
self.assertGreater(count, 50)
# the source of y[i] in S2(i, j) never depends on N
self.assertNotIn("'N'", repr(quasts[("S2", 0)]))
def test_even_writes_needs_a_new_parameter(self):
quasts, _ = check(self, even_writes(), range(0, 6))
self.assertIn("div", repr(quasts[("S2", 0)]))
def test_diagonal(self):
check(self, diagonal(), range(0, 5))
def test_lexmax_matches_enumeration(self):
# lexmax of (s0, s1) with 0 <= s0, s1 <= N, 3*s0 + 2*s1 <= t
cons = [F(s0=1), F(s1=1), F(N=1, s0=-1), F(N=1, s1=-1), F(t=1, s0=-3, s1=-2)]
quast = lexmax(["s0", "s1"], cons, [F(N=1), F(t=1)])
for n in range(0, 5):
for t in range(0, 20):
pts = [(a, b) for a in range(n + 1) for b in range(n + 1) if 3 * a + 2 * b <= t]
got = eval_quast(_tag(quast), {"N": n, "t": t})
self.assertEqual(got, ("x", max(pts)))
def _tag(t):
if t[0] == "leaf":
return t if t[1] is None else ("leaf", ("x", t[1]))
if t[0] == "if":
return ("if", t[1], _tag(t[2]), _tag(t[3]))
return ("div", t[1], t[2], t[3], _tag(t[4]))
def random_program(rng):
"""One or two outer i loops; each holds statements at depth 1 or inner
j loops. All statements touch one array A with affine subscripts."""
stmts, k = [], 0
for b0 in range(rng.randint(1, 2)):
for b1 in range(rng.randint(1, 2)):
dom_i = [F(i=1), F(N=1, i=-1)]
if rng.random() < 0.5:
iters, betas, dom = ["i"], [b0, b1], dom_i
else:
lo, hi = rng.choice([(F(j=1), F(N=1, j=-1)), (F(j=1), F(i=1, j=-1)),
(F(j=1, i=-1), F(N=1, j=-1))])
iters, betas, dom = ["i", "j"], [b0, b1, 0], dom_i + [lo, hi]
def sub():
d = {"i": rng.choice([0, 1, 1, 2, -1])}
if "j" in iters:
d["j"] = rng.choice([0, 1, 1, 2, -1])
if rng.random() < 0.2:
d["N"] = 1
return form(d, rng.choice([-1, 0, 0, 1]))
reads = [("A", [sub()]) for _ in range(rng.randint(1, 2))]
stmts.append(Stmt(f"S{k}", iters, betas, dom, ("A", [sub()]), reads))
k += 1
return Program(["N"], [F(N=1)], stmts)
class RandomPrograms(unittest.TestCase):
def test_random(self):
rng = random.Random(1988)
total = 0
for _ in range(14):
prog = random_program(rng)
_, count = check(self, prog, range(0, 4))
total += count
self.assertGreater(total, 500)
if __name__ == "__main__":
unittest.main()
History
Paul Feautrier published parametric integer programming in 1988 and the array dataflow analysis built on it in 1991, as part of his work on automatic parallelization. The 1991 paper defines the source function and gives the result as a quast. Around 1993, Maydan, Amarasinghe and Lam, and Pugh and Wonnacott gave other ways to compute the same exact information. Feautrier used the source functions as the dependence input of his scheduling algorithm in 1992, and the analysis became a standard part of the polyhedral model. Polyhedral libraries such as isl still compute exact dataflow with parametric integer programming.
References
- Paul Feautrier, Dataflow analysis of array and scalar references, International Journal of Parallel Programming 20(1), 1991, 23-53, the definition of the source function, the candidate sets by depth, the use of PIP for each candidate set and the combination of the partial results into one quast
- Paul Feautrier, Parametric integer programming, RAIRO Recherche Opérationnelle 22(3), 1988, 243-268, the parametric dual simplex method, the quast (quasi-affine selection tree) form of the solution, and the Gomory cuts with new parameters for the integer case
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 61C0MP Edit this page History Report an error Markdown