Algorithm Search⌘K

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
Properties
deterministicrecursive

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 NN that are only known at run time, and a context, a set of affine constraints on NN. Statement SS is inside dSd_S loops, with counters s⃗=(s1,…,sdS)\vec{s} = (s_1, \dots, s_{d_S}). Its iteration domain DSD_S is a polyhedron, bounded for each value of NN. It writes the array element A[fS(s⃗)]A[f_S(\vec{s})], where fSf_S is affine. A read A[g(t⃗)]A[g(\vec{t})] in statement TT is given.

Execution order. The program runs in its text order. Instance S(s⃗)S(\vec{s}) runs before T(t⃗)T(\vec{t}) if they agree on the first l−1l - 1 of their cSTc_{ST} common loops and sl<tls_l < t_l for some l≤cSTl \le c_{ST}, or if they agree on all common loops and SS comes before TT in the text of the innermost common loop. In the polyhedral model this is the lexicographic order of the (2d+1)(2d + 1)-dimensional schedule vectors (β0,s1,β1,…,sd,βd)(\beta_0, s_1, \beta_1, \dots, s_d, \beta_d), where βk\beta_k is the text position at depth kk.

Output. The source function σ(t⃗,N)\sigma(\vec{t}, N): for each NN in the context and each t⃗∈DT\vec{t} \in D_T, the instance S(s⃗)S(\vec{s}) that runs last among the instances that write A[g(t⃗)]A[g(\vec{t})] before T(t⃗)T(\vec{t}), or ⊥\bot if there is none. It is given as a quast, a tree with nodes "if e≥0e \ge 0" for affine ee, nodes "let q=⌊e/D⌋q = \lfloor e / D \rfloor" that add new integer parameters, and leaves that are ⊥\bot or S(h⃗)S(\vec{h}) with h⃗\vec{h} affine in t⃗\vec{t}, NN 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 s⃗\vec{s}, so the latest writer is the lexicographic maximum of an integer polyhedron with parameters t⃗\vec{t} and NN. Parametric integer programming (PIP) computes this maximum as a quast. A final merge compares the leaves of the quasts by their schedule vectors.

  1. SOURCE(T, t, A[g(t)]) ▷ the read A[g(t)] in the instance T(t)
  2. 1Q <- the quast "no source"
  3. 2for each statement S that writes A[f_S(s)] do
  4. 3for each depth l in 1 .. c_ST, and "same iteration" if S is before T in the text do
  5. 4C <- { s in D_S : f_S(s) = g(t), s_1..s_{l-1} = t_1..t_{l-1}, s_l <= t_l - 1 }
  6. 5K <- PIP-LEXMAX(C) with the parameters t and N
  7. 6Q <- MERGE(Q, K): at each leaf, keep the source that runs later
  8. 7return Q
  9. PIP(rows, context) ▷ each row: x_i = c_i(p) + sum_j a_ij n_j >= 0
  10. 8if the context has no point then return "no solution"
  11. 9while some row has c_i(p) < 0 on the whole context do pivot on it, or return "no solution" if no a_ij > 0
  12. 10if some row has c_i(p) of both signs on the context then
  13. return if c_i >= 0 then PIP(rows, context and c_i >= 0) else PIP(rows, context and c_i <= -1)
  14. 11k <- an unknown x_k whose constant c_k(p) is not integer-valued
  15. 12if there is none then return the leaf (c_1(p), ..., c_n(p))
  16. 13if 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
  17. 14add 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 s1=t1,…,sc=tcs_1 = t_1, \dots, s_c = t_c for all c=cSTc = c_{ST} common loops and no strict inequality.

PIP. The tableau describes every unknown and every constraint as xi=ci(p)+∑jaijnjx_i = c_i(p) + \sum_j a_{ij} n_j, where the nj≥0n_j \ge 0 are the current nonbasic variables and ci(p)c_i(p) is affine in the parameters pp. 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 jj with arj>0a_{rj} > 0, it picks the one whose whole column divided by arja_{rj} is lexicographically least, so that the columns stay lexicographically positive and the basic solution stays the lexicographic minimum. The sign of ci(p)c_i(p) depends on pp, 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 pp, it is not affine, and Feautrier writes it with a new parameter q=⌊e/D⌋q = \lfloor e / D \rfloor. The new parameter is defined by the two context constraints Dq≤e≤Dq+D−1D q \le e \le D q + D - 1.

Maximum instead of minimum. PIP finds a lexicographic minimum over x≥0x \ge 0. The implementation sets xk=M−skx_k = M - s_k for a symbolic parameter MM that is larger than every other value. The sign of a form with an MM term is the sign of its MM coefficient.

Merge. Line L6 walks the two quasts together, adding the tests of both to the context. At a pair of leaves S(h⃗)S(\vec{h}) and S′(h⃗′)S'(\vec{h}'), it compares the schedule vectors θS(h⃗)\theta_S(\vec{h}) and θS′(h⃗′)\theta_{S'}(\vec{h}') 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 S2(t1,t2)S2(t_1, t_2). Both statements write y.

  • S1S1 has one common loop with S2S2. At depth 1, the candidates satisfy s1=t1s_1 = t_1 (same element) and s1≤t1−1s_1 \le t_1 - 1, which is empty. At the "same iteration" depth, S1S1 comes before the jj loop in the text, and the set is {s1:s1=t1}\{s_1 : s_1 = t_1\}. Its maximum is S1(t1)S1(t_1).
  • S2S2 has two common loops with itself. Depth 1 is empty again. At depth 2 the set is {(s1,s2):s1=t1, 0≤s2≤t2−1}\{(s_1, s_2) : s_1 = t_1,\ 0 \le s_2 \le t_2 - 1\}. PIP returns (t1,t2−1)(t_1, t_2 - 1) if t2≥1t_2 \ge 1 and no solution otherwise. "Same iteration" does not apply, because an instance does not run before itself.

The merge compares θS1(t1)=(0,t1,0)\theta_{S1}(t_1) = (0, t_1, 0) with θS2(t1,t2−1)=(0,t1,1,t2−1,0)\theta_{S2}(t_1, t_2 - 1) = (0, t_1, 1, t_2 - 1, 0). They differ first in the third component, so S2S2 is later. The source is

σ(t1,t2)={S2(t1,t2−1)if t2≥1,S1(t1)otherwise.\sigma(t_1, t_2) = \begin{cases} S2(t_1, t_2 - 1) & \text{if } t_2 \ge 1, \\ S1(t_1) & \text{otherwise.} \end{cases}

The implementation prints this tree. A memory-based test says only that the read depends on S1S1 and on many instances of S2S2; 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 S2(t)S2(t) are {s:0≤s≤N, 2s=t}\{s : 0 \le s \le N,\ 2s = t\}. The rational maximum is s=t/2s = t/2, which is not an integer for odd tt. Line L14 adds q=⌊t/2⌋q = \lfloor t / 2 \rfloor, and the result is: if 2q−t≥02q - t \ge 0, that is, tt is even, the source is S1(q)S1(q); otherwise there is no source and the read sees the initial value of A[t]. A test such as tt even cannot be written with affine tests on tt and NN alone, which is why quasts need the new parameters.

Along a diagonal. For A[i+j] = A[i+j] + 1 inside two loops over 0≤i,j≤N0 \le i, j \le N, the source of the read in S(t1,t2)S(t_1, t_2) is S(t1−1,t2+1)S(t_1 - 1, t_2 + 1) if t1≥1t_1 \ge 1 and t2≤N−1t_2 \le N - 1, and the initial value otherwise. The candidate set at depth 2 is empty, because s1=t1s_1 = t_1 and s1+s2=t1+t2s_1 + s_2 = t_1 + t_2 force s2=t2s_2 = t_2.

Correctness

The full proof is in the proof page. It has four steps. First, an instance S(s⃗)S(\vec{s}) writes A[g(t⃗)]A[g(\vec{t})] before T(t⃗)T(\vec{t}) exactly when s⃗\vec{s} 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 s⃗\vec{s}, 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 NN that satisfy the context KK. Statement SS has depth dSd_S, a domain DSD_S that is a polyhedron and is bounded for each NN, and writes A[fS(s⃗)]A[f_S(\vec{s})] with fSf_S affine. The read is A[g(t⃗)]A[g(\vec{t})] in TT, with t⃗∈DT\vec{t} \in D_T. All counters and parameters are integers. For two statements, c=cSTc = c_{ST} is the number of common loops, and βkS\beta^S_k is the text position of SS (or of the loop that holds it) at depth kk. The schedule of S(s⃗)S(\vec{s}) is θS(s⃗)=(β0S,s1,β1S,…,sdS,βdSS)\theta_S(\vec{s}) = (\beta^S_0, s_1, \beta^S_1, \dots, s_{d_S}, \beta^S_{d_S}), 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 NN in KK and every t⃗∈DT\vec{t} \in D_T, the quast QQ returned at line L7, evaluated at (t⃗,N)(\vec{t}, N), gives the instance S(s⃗)S(\vec{s}) with the lexicographically greatest schedule among the instances that write A[g(t⃗)]A[g(\vec{t})] and have a schedule less than θT(t⃗)\theta_T(\vec{t}), or ⊥\bot if there is no such instance.

Step 1: the candidate sets cover the earlier writes, and are disjoint

For a statement SS that writes AA and a depth l∈{1,…,c}l \in \{1, \dots, c\}, let

CS,l(t⃗)={s⃗∈DS:fS(s⃗)=g(t⃗), sk=tk for k<l, sl≤tl−1},C_{S,l}(\vec{t}) = \{\vec{s} \in D_S : f_S(\vec{s}) = g(\vec{t}),\ s_k = t_k \text{ for } k < l,\ s_l \le t_l - 1\},

and if βcS<βcT\beta^S_c < \beta^T_c, let CS,eq(t⃗)={s⃗∈DS:fS(s⃗)=g(t⃗), sk=tk for k≤c}C_{S,\mathrm{eq}}(\vec{t}) = \{\vec{s} \in D_S : f_S(\vec{s}) = g(\vec{t}),\ s_k = t_k \text{ for } k \le c\}. These are the sets of line L4.

Lemma 1. θS(s⃗)<lexθT(t⃗)\theta_S(\vec{s}) <_{\mathrm{lex}} \theta_T(\vec{t}) if and only if s⃗\vec{s} satisfies the depth condition of exactly one of these sets.

Proof. The first 2c2c components of the two schedules are (β0,s1,β1,…,sc)(\beta_0, s_1, \beta_1, \dots, s_c) and (β0,t1,β1,…,tc)(\beta_0, t_1, \beta_1, \dots, t_c), with the same β0,…,βc−1\beta_0, \dots, \beta_{c-1}, because the statements share the loops 1 to cc. Let ll be the first k≤ck \le c with sk≠tks_k \ne t_k, if there is one. Then the schedules differ first at the component of sls_l, and θS(s⃗)<θT(t⃗)\theta_S(\vec{s}) < \theta_T(\vec{t}) exactly when sl<tls_l < t_l, that is, sl≤tl−1s_l \le t_l - 1 for integers. This is the condition of CS,lC_{S,l}. If there is no such ll, the next component is βcS\beta^S_c against βcT\beta^T_c. If S=TS = T, then s⃗=t⃗\vec{s} = \vec{t} on all dS=cd_S = c loops, the instance is T(t⃗)T(\vec{t}) itself, and it is not earlier. Otherwise βcS≠βcT\beta^S_c \ne \beta^T_c, by the remark in the setting, and the order is decided there: S(s⃗)S(\vec{s}) is earlier exactly when βcS<βcT\beta^S_c < \beta^T_c. This is the set CS,eqC_{S,\mathrm{eq}}, which line L3 builds only in that case. The first index ll is unique, so the cases are disjoint. □\square

The access condition fS(s⃗)=g(t⃗)f_S(\vec{s}) = g(\vec{t}) selects the writes of the element that T(t⃗)T(\vec{t}) reads. So the union over all SS and all depths of the candidate sets is exactly the set of earlier writes of A[g(t⃗)]A[g(\vec{t})], and each such write is in exactly one set.

Step 2: inside one candidate set, later means lexicographically greater

Lemma 2. For s⃗,s⃗′∈DS\vec{s}, \vec{s}' \in D_S, θS(s⃗)<lexθS(s⃗′)\theta_S(\vec{s}) <_{\mathrm{lex}} \theta_S(\vec{s}') if and only if s⃗<lexs⃗′\vec{s} <_{\mathrm{lex}} \vec{s}'.

Proof. Both schedules have the same constants βkS\beta^S_k at the same positions, and the counters in between. The first difference is at the first counter where s⃗\vec{s} and s⃗′\vec{s}' differ, with the same sign. □\square

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 xi=ci(p)+∑jaijnjx_i = c_i(p) + \sum_j a_{ij} n_j, where pp are the parameters (here t⃗\vec{t}, NN and the new parameters), the njn_j are the nonbasic variables, and every row must be ≥0\ge 0. The first nn 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 (a1j,a2j,… )(a_{1j}, a_{2j}, \dots) is lexicographically positive.

The unknowns of line L5 are xk=M−skx_k = M - s_k, where MM is a symbolic parameter. For fixed NN and t⃗\vec{t} the candidate set is bounded, so for MM large enough all xkx_k are nonnegative and the lexicographic minimum of x⃗\vec{x} is reached at the lexicographic maximum of s⃗\vec{s}. The sign of an affine form with a nonzero MM coefficient is the sign of that coefficient for MM large enough, so the sign tests are correct for all large MM.

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 Dq≤e≤Dq+D−1D q \le e \le D q + D - 1.

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 rr with cr<0c_r < 0 uses the column jj with arj>0a_{rj} > 0 whose column divided by arja_{rj} is lexicographically least. A pivot is an invertible affine change of the nonbasic variables, so the nn unknown rows always form an invertible n×nn \times n matrix, and every column is nonzero in its first nn entries. Each new column l≠jl \ne j is coll−(arl/arj)colj\mathrm{col}_l - (a_{rl}/a_{rj}) \mathrm{col}_j. If arl≤0a_{rl} \le 0, it is coll\mathrm{col}_l plus a nonnegative multiple of colj\mathrm{col}_j, so it is lex-positive. If arl>0a_{rl} > 0, it is arl(coll/arl−colj/arj)a_{rl}(\mathrm{col}_l / a_{rl} - \mathrm{col}_j / a_{rj}), which is lexicographically nonnegative by the choice of jj and is not zero by the remark above, so it is lex-positive. The new column jj is colj/arj\mathrm{col}_j / a_{rj}, 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 nn 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). □\square

Lemma 4 (cuts). Let row kk be xk=ck(p)+∑jakjnjx_k = c_k(p) + \sum_j a_{kj} n_j, with xkx_k and all njn_j integers. Then every integer point satisfies ∑jfrac(−akj)nj≥frac(ck(p))\sum_j \mathrm{frac}(-a_{kj}) n_j \ge \mathrm{frac}(c_k(p)). The new row has an integer value at every integer point.

Proof. Write xk−∑jakjnj=ckx_k - \sum_j a_{kj} n_j = c_k and split each number into its floor and its fractional part: xk+∑j⌊−akj⌋nj−⌊ck⌋=frac(ck)−∑jfrac(−akj)njx_k + \sum_j \lfloor -a_{kj} \rfloor n_j - \lfloor c_k \rfloor = \mathrm{frac}(c_k) - \sum_j \mathrm{frac}(-a_{kj}) n_j. The left side is an integer. The right side is less than 1, because frac(ck)<1\mathrm{frac}(c_k) < 1 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 ck(p)c_k(p) has parameter terms, the code first replaces every coefficient by its fractional part, which changes ck(p)c_k(p) by an integer for integer pp; call the result f(p)f(p). With DD the common denominator, q=⌊Df(p)/D⌋q = \lfloor D f(p) / D \rfloor is an integer and frac(ck(p))=f(p)−q\mathrm{frac}(c_k(p)) = f(p) - q, which is affine in pp and qq. So the row of line L14 is the same cut. □\square

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 (c1(p),…,cn(p))(c_1(p), \dots, c_n(p)), then for every integer pp 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 cr(p)<0c_r(p) < 0 on the whole context and all arj≤0a_{rj} \le 0; then xr≤cr(p)<0x_r \le c_r(p) < 0 for every n≥0n \ge 0, so no point satisfies the row, and by Lemma 3 (b) the problem has no integer point. (ii) At line L12, every row has ci(p)≥0c_i(p) \ge 0 on the context, because the sign tests of lines L9 and L10 found no negative and no mixed constant. Setting all nj=0n_j = 0 gives x=c(p)x = c(p), which satisfies every row. Any other point of the current rational problem has some nj>0n_j > 0. Its unknowns are c(p)+∑jnjaˉjc(p) + \sum_j n_j \bar{a}_j, where aˉj\bar{a}_j is the part of column jj in the first nn rows. Each aˉj\bar{a}_j is lex-positive, so a nonnegative combination of them that is not all zero is lex-positive, and the point is lexicographically greater than c(p)c(p). So c(p)c(p) 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 c(p)c(p) is the integer lexicographic minimum. □\square

The split at line L10 adds ci≥0c_i \ge 0 to one branch and ci≤−1c_i \le -1 to the other, where cic_i 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 qq that is already defined with the same numerator and denominator and the context forces Dq=eD q = e; then ck(p)c_k(p) equals an integer form on the context, which is a rewriting and changes no value. So the quast of PIP, evaluated at any integer pp 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 MERGE(Q1,Q2)\mathrm{MERGE}(Q_1, Q_2) gives the later of the two instances that Q1Q_1 and Q2Q_2 give at that point, where an instance is later than ⊥\bot.

Proof. Merge walks down Q1Q_1 and then Q2Q_2, adding to the context the test of each node it passes or its negation e≤−1e \le -1. For integer points the two branches of a node cover its context, so every integer point reaches the pair of leaves that Q1Q_1 and Q2Q_2 give there. If one leaf is ⊥\bot, merge returns the other. Otherwise it compares θS(h⃗)\theta_S(\vec{h}) and θS′(h⃗′)\theta_{S'}(\vec{h}') component by component: at component kk it splits the context into the difference ≥1\ge 1, ≤−1\le -1 and =0= 0, which for integers covers all cases, and goes to component k+1k + 1 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. □\square

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 KK of line L5 gives the latest write in its set, or ⊥\bot if the set is empty. By Lemma 6 and induction on the number of sets merged so far, after line L6 the quast QQ gives the latest instance among all sets seen so far. After the last set, it gives the latest of all earlier writes of A[g(t⃗)]A[g(\vec{t})], or ⊥\bot when there is none. This is the source. ■\blacksquare

Complexity

The algorithm runs one PIP for each writing statement SS and each depth, at most s(d+1)s(d + 1) 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 2d+12d + 1 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 NN at once. The tests in the tree are affine, plus the new parameters of the form ⌊e/D⌋\lfloor e / D \rfloor.
  • A function. For each read the source is one instance or ⊥\bot, 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 product i * j in a subscript, or a data-dependent if takes 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.

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

  1. 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
  2. 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.

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
  • at least three sources
  • a scene preset for the example