Algorithm Search⌘K

Algorithmresearch

Polyhedral scanning

Also called Quillere-Rajopadhye-Wilde algorithm, polyhedral code generation.

Generates loop nests that visit the integer points of a union of polyhedra in schedule order, by separating and projecting the polyhedra.

Time
O(s m P^(n+1) L) worst
Space
O(m P^n) extra
Where
L = the cost of one emptiness or implication test; P = the largest number of pieces at one level; m = the largest number of constraints of a polyhedron the generator builds; n = the number of scanning dimensions; s = the number of statements
Properties
deterministicrecursive

Polyhedral scanning turns a set of polyhedra back into loops. A polyhedral compiler describes each statement by the integer points of its iteration domain and by a schedule that gives each point a time vector. After it changes the schedule, it must produce code that runs every point exactly once, in the lexicographic order of the time vectors. For one polyhedron, Ancourt and Irigoin (1991) found the loop bounds by Fourier-Motzkin elimination. For a union of polyhedra, one per statement, Quilleré, Rajopadhye and Wilde (2000) gave a recursive method: at each depth, project the polyhedra, split the projections into disjoint pieces, sort the pieces, and make one loop per piece. The CLooG tool of Bastoul (2004) and the code generator of isl are built on this method. It is the last step of every polyhedral compiler, after a scheduler such as Feautrier's or Pluto.

In plain words

Picture each statement as a set of dots on graph paper, and the schedule as the order in which we must touch the dots: row by row, and left to right inside each row. To write a loop for the rows, we need the lowest and highest row that has a dot. To get them, we flatten the shape onto one axis, like a shadow. When several shapes overlap, some rows have dots of one statement and some rows have dots of both. So we cut the rows into stretches where the same statements are present. Each stretch gets its own loop, and the stretches run from left to right. Inside each loop we do the same for the next axis. The result has no tests inside the loops, and every dot is touched once, in the right order.

The problem

Input. Integer parameters NN in a context KK, and statements S1,…,SsS_1, \dots, S_s. Statement SS has a domain DSD_S, a polyhedron given by affine inequalities in its loop counters i⃗\vec{i} and NN, bounded for each N∈KN \in K, and an affine schedule θS(i⃗)∈Zm\theta_S(\vec{i}) \in \mathbb{Z}^{m}.

Scanning space. Each instance S(i⃗)S(\vec{i}) becomes the point x=(θS(i⃗),i⃗,0,…,0)x = (\theta_S(\vec{i}), \vec{i}, 0, \dots, 0) of Zn\mathbb{Z}^n, with the counters padded to the largest depth. The set of these points is a polyhedron QSQ_S in (x,N)(x, N): the domain, plus the equalities xk=θS,k(i⃗)x_k = \theta_{S,k}(\vec{i}) and the zero padding. The schedule order is the lexicographic order of (x,S)(x, S), where the text position of SS breaks ties.

Output. A loop nest that, for every N∈KN \in K, runs every instance S(i⃗)S(\vec{i}) with i⃗∈DS\vec{i} \in D_S exactly once, in the lexicographic order of (x,S)(x, S), and nothing else.

Loop bounds. A constraint axk+r(x1,…,xk−1,N)≥0a x_k + r(x_1, \dots, x_{k-1}, N) \ge 0 with a>0a > 0 is a lower bound xk≥⌈−r/a⌉x_k \ge \lceil -r / a \rceil, and with a<0a < 0 an upper bound xk≤⌊r/(−a)⌋x_k \le \lfloor r / (-a) \rfloor. A loop runs xkx_k from the maximum of its lower bounds to the minimum of its upper bounds.

The algorithm

The generator is a recursive function of a list of polyhedra (each with the set of statements it stands for), a level kk and a context CC, the constraints that hold at that depth of the code. It starts with the polyhedra QSQ_S, level 1 and the context KK.

  1. SCAN(polyhedra Q_1..Q_s, context C, level k)
  2. 1for each Q_i: Q'_i <- the shadow of Q_i on (x_1..x_k, N), by Fourier-Motzkin elimination of x_n down to x_(k+1); drop the empty ones
  3. 2separate the Q'_i into disjoint pieces R_1..R_r, each labeled with the set of statements whose Q'_i contains it
  4. 3sort the pieces so that, of two pieces that exist for the same outer values, the one with the smaller x_k comes first
  5. 4if no such order exists then make one loop over x_k from the least lower bound to the largest upper bound, and run inside it the part of each piece that contains x_k
  6. 5for each piece R in this order do
  7. 6guards <- the constraints of R without x_k that C does not imply
  8. 7bounds <- the constraints of R with x_k, minus those that the others and C imply
  9. 8if k = n then body <- the statements of the label of R, in text order
  10. 9else body <- SCAN({Q_i intersect R : i in the label of R}, C and R, k + 1)
  11. 10emit "if guards then for x_k = max(lower bounds) to min(upper bounds): body"

Fourier-Motzkin elimination. To remove xjx_j, keep the constraints without xjx_j and add, for each pair of a lower bound axj+r≥0a x_j + r \ge 0 and an upper bound −bxj+q≥0-b x_j + q \ge 0 (with a,b>0a, b > 0), the combination br+aq≥0b r + a q \ge 0. If xjx_j appears in an equality, substitution is enough. The result is the rational shadow of the polyhedron. Each new constraint is divided by the greatest common divisor of its coefficients, and the constant is rounded down, which keeps the same integer points.

Separation. The pieces are built one polyhedron at a time. A new polyhedron QQ splits each old piece RR into R∩QR \cap Q and the pieces of R∖QR \setminus Q, and what is left of QQ after all the old pieces becomes new pieces. The difference of two polyhedra is a union of polyhedra. With the constraints q1,…,qtq_1, \dots, q_t of QQ, it is the disjoint union of

R∩{q1≥0,…,qj−1≥0,qj≤−1},j=1,…,t,R \cap \{q_1 \ge 0, \dots, q_{j-1} \ge 0, q_j \le -1\}, \qquad j = 1, \dots, t,

where qj≤−1q_j \le -1 is the integer complement of qj≥0q_j \ge 0. Empty pieces are dropped. The emptiness tests and the tests "does CC imply g≥0g \ge 0" are linear programs, solved here with an exact simplex method over integer rows.

Sorting. Two pieces always differ by one constraint gg: one has g≥0g \ge 0 and the other g≤−1g \le -1. If gg contains xkx_k, this fixes their order along xkx_k for all outer values. If it does not, the two pieces never exist for the same outer values. So pairs are either ordered or independent, and the test of line L3 is a pair of linear programs: "is there a point of AA and a point of BB with the same outer values and ak≥bka_k \ge b_k?". A topological sort of this relation gives the order. Line L4 is a safety net of this implementation in case the relation has a cycle. It never fires on the tests.

Example

A triangle, interchanged. The nest for i = 0 to N: for j = 0 to i: S(i, j) with the schedule (j,i)(j, i) has t1=jt_1 = j and t2=it_2 = i, so its points satisfy 0≤t1≤t2≤N0 \le t_1 \le t_2 \le N. Eliminating t2t_2 pairs the lower bound t2≥t1t_2 \ge t_1 with the upper bound t2≤Nt_2 \le N, and gives 0≤t1≤N0 \le t_1 \le N. The generator prints

for t1 = 0 to N:
  for t2 = t1 to N:
    i1 = t2
    i2 = t1
    S(i1, i2)

The last two lines are loops with a single iteration, from the equalities i1=t2i_1 = t_2 and i2=t1i_2 = t_1.

Two statements, fused. Let S1S_1 run on 0≤i≤N0 \le i \le N and S2S_2 on 2≤i≤N+22 \le i \le N + 2, with the schedules (i,0)(i, 0) and (i,1)(i, 1), a fusion of two loops. At level 1 the shadows are the two ranges. Separation gives three pieces: S1S_1 alone on 0≤t1≤min⁡(N,1)0 \le t_1 \le \min(N, 1), both on 2≤t1≤N2 \le t_1 \le N, and S2S_2 alone on max⁡(2,N+1)≤t1≤N+2\max(2, N + 1) \le t_1 \le N + 2. Inside the middle piece, level 2 separates t2=0t_2 = 0 from t2=1t_2 = 1. The output is

for t1 = 0 to min(N, 1):
  t2 = 0
  i1 = t1
  S1(i1)
for t1 = 2 to N:
  t2 = 0
  i1 = t1
  S1(i1)
  t2 = 1
  i1 = t1
  S2(i1)
for t1 = max(2, N + 1) to N + 2:
  t2 = 1
  i1 = t1
  S2(i1)

There is no test inside any loop. For N=0N = 0 the middle loop is empty and the last one runs t1=2t_1 = 2, as it should.

A skewed stencil. For for t = 0 to N: for i = 1 to N: S(t, i) with the skewed schedule (t,t+i)(t, t + i), the generator gives for t1 = 0 to N: for t2 = t1 + 1 to t1 + N: with i2=t2−i1i_2 = t_2 - i_1 inside, under the guard N−1≥0N - 1 \ge 0, which the context N≥0N \ge 0 does not imply.

Correctness

The full proof is in the proof page. It rests on four facts about the pieces at one level, for fixed values of the outer dimensions and the parameters.

  • Cover. Every integer point of every QSQ_S has its first kk coordinates in the shadow QS′Q'_S, and so in some piece. Separation keeps every integer point of the union, because a point outside QQ breaks some qj≥0q_j \ge 0 and so has qj≤−1q_j \le -1.
  • Disjointness. Two pieces have no integer point in common, so no point is visited twice.
  • Labels. If a point of QSQ_S lies in the piece RR, then SS is in the label of RR, so the body of RR contains SS.
  • Order. Inside one loop xkx_k grows, and the sorted pieces visit increasing xkx_k for the same outer values. By induction on kk, the whole nest visits the points in lexicographic order.

At the last level, a piece lies inside QSQ_S for each SS of its label, so a statement runs only at points of its domain.

Proof: The scanning code visits each integer point of each statement exactly once, in lexicographic orderfull

Setting. We use the notation of the page. All constraints have integer coefficients and are written g(x,N)≥0g(x, N) \ge 0 with gg affine. For a set RR of constraints, a point of RR means an integer point that satisfies them, and RR is rationally empty if no rational point does. We treat a polyhedron as its set of constraints, so for two of them R∪QR \cup Q is the set of constraints of their intersection. Statement SS has the polyhedron QSQ_S in (x,N)∈Zn×Zp(x, N) \in \mathbb{Z}^n \times \mathbb{Z}^p, made of its domain, the equalities xj=θS,j(i⃗)x_j = \theta_{S,j}(\vec{i}), the zero padding and the context KK. For each N∈KN \in K the points of QSQ_S are exactly the vectors (θS(i⃗),i⃗,0,…,0)(\theta_S(\vec{i}), \vec{i}, 0, \dots, 0) with i⃗∈DS\vec{i} \in D_S, and this map is one to one, because i⃗\vec{i} is part of the vector. So it is enough to prove the claim below for the points of the QSQ_S.

Claim. For every integer N∈KN \in K, the generated code runs the pairs (x,S)(x, S) with xx a point of QSQ_S, each exactly once, and no other pair, in the lexicographic order of (x1,…,xn,S)(x_1, \dots, x_n, S), where SS is compared by its text position.

Step 1: operations that keep the integer points

Lemma 1. Let RR be a set of constraints.

  1. Replacing a⋅x+c≥0a \cdot x + c \ge 0 by (a/d)⋅x+⌊c/d⌋≥0(a / d) \cdot x + \lfloor c / d \rfloor \ge 0, where dd is the gcd of the entries of aa, keeps the points of RR and does not enlarge its rational set.
  2. Removing a constraint that the others imply on all rational points keeps the rational set, so it keeps the points.
  3. Every point of RR satisfies every constraint that Fourier-Motzkin elimination derives from RR, before or after step 1.

Proof. (1) At an integer xx, (a/d)⋅x(a / d) \cdot x is an integer, and it is at least −c/d-c / d, so it is at least ⌈−c/d⌉=−⌊c/d⌋\lceil -c / d \rceil = -\lfloor c / d \rfloor. Conversely ⌊c/d⌋≤c/d\lfloor c / d \rfloor \le c / d, so the new constraint implies the old one at every rational point. (2) is clear. (3) A derived constraint is br+aqb r + a q with a,b>0a, b > 0, where r≥0r \ge 0 and q≥0q \ge 0 are constraints of RR, or as−sjra s - s_j r where r=0r = 0 is an equality of RR. Both are nonnegative wherever the constraints of RR hold. □\square

Let Q′Q' be the shadow of QQ on (x1,…,xk,N)(x_1, \dots, x_k, N) computed at line L1. By Lemma 1, if xx is a point of QQ, then (x1,…,xk)(x_1, \dots, x_k) with the same NN is a point of Q′Q'. Also Q′Q' is contained in the rational projection of QQ, because each derived constraint holds on that projection and step 1 only shrinks it.

Step 2: separation

Let Q1′,…,Qr′Q'_1, \dots, Q'_r be the shadows at one call, each with the statement it stands for. Line L2 returns pieces RR with labels LRL_R.

Lemma 2. The pieces satisfy:

  1. Cover and disjointness. Every point of Q1′∪⋯∪Qr′Q'_1 \cup \dots \cup Q'_r is a point of exactly one piece, and pieces have no other points.
  2. Labels. A point yy of the piece RR is a point of Qi′Q'_i if and only if i∈LRi \in L_R.
  3. Separation. For two different pieces AA and BB, there is a constraint gg such that all rational points of one satisfy g≥0g \ge 0 and all rational points of the other satisfy g≤−1g \le -1.

Proof. First, the difference. For constraint sets PP and Q={q1,…,qt}Q = \{q_1, \dots, q_t\}, the pieces of P∖QP \setminus Q are Pj=P∪{q1≥0,…,qj−1≥0,qj≤−1}P_j = P \cup \{q_1 \ge 0, \dots, q_{j-1} \ge 0, q_j \le -1\}, with the rationally empty ones dropped; the loop also stops early when P∪{q1,…,qj≥0}P \cup \{q_1, \dots, q_j \ge 0\} is rationally empty, and then no later PjP_j has a point. A point of PP that is not a point of QQ breaks some qj≥0q_j \ge 0; let jj be the first. Since qjq_j is an integer there, qj≤−1q_j \le -1, so the point lies in PjP_j and in no other Pj′P_{j'}: for j′<jj' < j it has qj′≥0q_{j'} \ge 0, and for j′>jj' > j it breaks qj≥0q_j \ge 0. Points of QQ lie in no PjP_j. Any PjP_j and Pj′P_{j'} with j<j′j < j' are separated by g=qjg = q_j. Step 1 of Lemma 1, applied by the cleaning, keeps all of this, since it keeps points and only shrinks rational sets.

Now induct on the number of shadows inserted. With one shadow there is one piece. Suppose the claims hold for the pieces of Q1′,…,Qi−1′Q'_1, \dots, Q'_{i-1} and insert Q=Qi′Q = Q'_i. Each old piece RR gives R∪QR \cup Q with label LR∪{i}L_R \cup \{i\} (if not rationally empty) and the pieces of R∖QR \setminus Q with label LRL_R. What is left of QQ, the pieces of (…(Q∖R1)∖R2… )(\dots(Q \setminus R_1) \setminus R_2 \dots), gets the label {i}\{i\}.

(1) A point in some old piece RR, unique by induction, lies in R∪QR \cup Q if it is a point of QQ, and else in exactly one piece of R∖QR \setminus Q. It lies in no piece of what is left of QQ, since those avoid every old piece. A point of QQ in no old piece lies in exactly one piece of what is left of QQ, by the property of the difference applied at each step.

(2) For a point of R∪QR \cup Q or of a piece of R∖QR \setminus Q, the old labels are right by induction, and membership in QQ is right by construction. A point in what is left of QQ lies in no old piece, so by (1) for the old pieces it lies in no Qi′′Q'_{i'} with i′<ii' < i.

(3) Two new pieces that come from different old pieces inherit their separating constraint. R∪QR \cup Q and a piece RjR_j of R∖QR \setminus Q are separated by qjq_j. Two pieces of R∖QR \setminus Q are separated as shown above. A piece of what is left of QQ lies inside a piece of a difference by some old RR, so it satisfies rj≤−1r_j \le -1 for a constraint rjr_j of RR, while every new piece inside RR satisfies rj≥0r_j \ge 0. Two pieces of what is left of QQ were split at some difference step by a constraint of the piece subtracted there. □\square

Step 3: the order of the pieces

For pieces AA and BB at level kk, let WW be the rational set of pairs (a,b)(a, b) with a∈Aa \in A, b∈Bb \in B, the same NN and aj=bja_j = b_j for j<kj < k.

Lemma 3. Either WW is empty, or ak<bka_k < b_k on all of WW, or ak>bka_k > b_k on all of WW. The test of line L3 finds which.

Proof. Take the constraint g=αxk+h(x1,…,xk−1,N)g = \alpha x_k + h(x_1, \dots, x_{k-1}, N) of Lemma 2(3), and say AA satisfies g≥0g \ge 0 and BB satisfies g≤−1g \le -1. On WW, both points have the same hh. If α=0\alpha = 0, then h≥0h \ge 0 and h≤−1h \le -1, so WW is empty. If α>0\alpha > 0, then αak≥−h>−h−1≥αbk\alpha a_k \ge -h > -h - 1 \ge \alpha b_k, so ak>bka_k > b_k. If α<0\alpha < 0, the same steps give ak<bka_k < b_k. Line L3 tests the emptiness of WW, of W∩{ak≥bk}W \cap \{a_k \ge b_k\} and of W∩{bk≥ak}W \cap \{b_k \ge a_k\} with the simplex method, which is exact. □\square

So line L3 builds a relation A→BA \to B ("AA comes first") between every two pieces with W≠∅W \ne \emptyset. If it has no cycle, a topological sort gives an order. In that order, if two pieces AA before BB both have points over the same outer values (x1,…,xk−1,N)(x_1, \dots, x_{k-1}, N), then W≠∅W \ne \emptyset, the relation holds as A→BA \to B, and every point of AA there has a smaller xkx_k than every point of BB there.

Step 4: one loop

Lemma 4. Let RR be a piece at level kk with the guards and bounds of lines L6 and L7, and let (y,N)(y, N), y=(x1,…,xk−1)y = (x_1, \dots, x_{k-1}), be an integer point that satisfies the context CC of the call. The loop of line L10 runs xkx_k over exactly the integers zz such that (y,z)(y, z) is a point of RR, in increasing order.

Proof. The constraints of RR without xkx_k are the guards, except those implied by CC, which hold at (y,N)(y, N). Line L7 removes from the constraints with xkx_k, together with CC, those implied by the others. By Lemma 1(2) the remaining set has the same rational points as all of them together with CC. Since (y,N)(y, N) satisfies all of CC, the kept bounds hold at (y,z)(y, z) exactly when all constraints of RR with xkx_k hold. For an integer zz, az+r≥0a z + r \ge 0 with a>0a > 0 means z≥⌈−r/a⌉z \ge \lceil -r / a \rceil, and with a<0a < 0 it means z≤⌊r/(−a)⌋z \le \lfloor r / (-a) \rfloor. So the integers zz with (y,z)∈R(y, z) \in R are those from the largest lower bound to the smallest upper bound. Both kinds of bounds exist: RR lies in a shadow, which lies in the rational projection of some QSQ_S, and that projection is bounded for each N∈KN \in K, because DSD_S is. □\square

Step 5: the induction

Invariant. A call SCAN(Λ,C,k)\mathrm{SCAN}(\Lambda, C, k) gets a list Λ\Lambda of pairs (Q,S)(Q, S), at most one per statement, such that every QQ contains the constraints of CC. We prove, by induction on n−kn - k, that for every integer point (y,N)(y, N) of CC with y∈Zk−1y \in \mathbb{Z}^{k-1} the code of the call runs exactly the pairs (x,S)(x, S) with (Q,S)∈Λ(Q, S) \in \Lambda, xx a point of QQ and (x1,…,xk−1)=y(x_1, \dots, x_{k-1}) = y, each once, in the lexicographic order of (xk,…,xn,S)(x_k, \dots, x_n, S).

The pairs run. Take such a pair (x,S)(x, S). By Step 1, (y,xk)(y, x_k) is a point of the shadow Q′Q', so by Lemma 2(1) it is a point of exactly one piece RR, and by Lemma 2(2) S∈LRS \in L_R. By Lemma 4, the loop of RR runs z=xkz = x_k exactly once, and the loops of the other pieces never reach (y,xk)(y, x_k), because they run only over their own points.

  • If k=nk = n, the body runs the statements of LRL_R, so (x,S)(x, S) runs once. Conversely, a statement S∈LRS \in L_R runs at x=(y,z)x = (y, z) only when xx is a point of RR, so of Q′Q' by Lemma 2(2). At level nn there is nothing to eliminate, and by Lemma 1 the points of Q′Q' are the points of QQ.
  • If k<nk < n, the body is SCAN(ΛR,C∪R,k+1)\mathrm{SCAN}(\Lambda_R, C \cup R, k + 1) with ΛR={(Q∪R,S):S∈LR}\Lambda_R = \{(Q \cup R, S) : S \in L_R\}. Every new Q∪RQ \cup R contains C∪RC \cup R, and (y,z,N)(y, z, N) satisfies C∪RC \cup R; the pruning of the new context keeps its rational set. By induction the body runs exactly the pairs (x,S)(x, S) with S∈LRS \in L_R, xx a point of QQ and of RR, and prefix (y,z)(y, z). Every point with prefix (y,z)(y, z) is a point of RR, because RR only has constraints in x1,…,xkx_1, \dots, x_k. So these are all the pairs with prefix (y,z)(y, z) and S∈LRS \in L_R. For S∉LRS \notin L_R, no point of QQ has the prefix (y,z)(y, z), because its shadow would contain (y,z)(y, z), and Lemma 2(2) would put SS in LRL_R.

So the call runs every pair once and no other pair.

The order. Inside one loop, z=xkz = x_k grows, and for each zz the body runs its pairs in the order of (xk+1,…,xn,S)(x_{k+1}, \dots, x_n, S) by induction, or in text order at k=nk = n. Between two pieces AA before BB in the sorted order, Step 3 shows that every point of AA over yy has a smaller xkx_k than every point of BB over yy. So the whole sequence is ordered by (xk,…,xn,S)(x_k, \dots, x_n, S).

The fallback. If line L4 runs, the code runs zz in increasing order over a range that contains the ranges of all pieces, and for each zz runs the body of every piece whose range contains zz. By Lemma 4, that range is exactly the set of zz with (y,z)(y, z) a point of the piece, and by Lemma 2(1) at most one piece has this point. So the same argument applies, with the order coming from the single loop over zz.

Step 6: conclusion

The first call is SCAN({(QS,S)},K,1)\mathrm{SCAN}(\{(Q_S, S)\}, K, 1), with KK pruned, which keeps its rational set. Every QSQ_S contains KK, and for k=1k = 1 the prefix yy is empty. The invariant gives the claim for every integer N∈KN \in K. The generator itself stops: the recursion has depth nn, each call makes finitely many pieces, and each linear program ends, because the simplex method uses a ratio test that cannot cycle. ■\blacksquare

Complexity

Fourier-Motzkin elimination of one variable can square the number of constraints, so mm can grow doubly exponentially with nn in the worst case. The implementation removes redundant constraints with linear programs to keep mm small. Separation of ss polyhedra can make a number of pieces PP that is exponential in ss. The generator calls itself at most PP times per piece and level, so it makes O(Pn−1)O(P^{n-1}) calls. Each call separates at most ss shadows against at most PP pieces, with O(Pm)O(P m) tests each, and sorts with O(P2)O(P^2) tests. The total is O(smPn+1)O(s m P^{n+1}) tests of cost LL, and the code holds O(Pn)O(P^n) loops of O(m)O(m) constraints each. In practice, for the loops of real programs, PP and mm stay small, and the size of the code is the main concern.

Properties

  • No tests inside the loops. Each loop has exact bounds. Guards appear only where a piece does not exist for all outer values, and they sit outside the loop they guard.
  • Rational shadows. The shadow from Fourier-Motzkin elimination is the rational one. For a polyhedron with a non-unimodular schedule, such as t=2it = 2i, the loop over tt also visits odd values, where the inner loop over ii is empty. The output is still correct, but it does wasted work.
  • Code size. Separation can duplicate a statement many times, once per piece that contains it.
  • Deterministic. The pieces and their order depend only on the input order of the statements and constraints.

Variants and improvements

  • Strides. CLooG and isl detect equalities such as t=2it = 2i and turn them into loop steps, for t = 0 to 2N step 2, instead of empty iterations.
  • Limits on separation. Bastoul's CLooG can stop separation below a given depth and use guards there, which trades a few tests for much smaller code. isl lets the user choose separation, isolation of full tiles, or unrolling per loop.
  • Exact integer shadows. The projection of the omega test is exact on integers, as a union of polyhedra, and so avoids the empty iterations of rational shadows at the cost of more pieces.
  • Tiled code. A tiled schedule uses ⌊ϕ/τ⌋\lfloor \phi / \tau \rfloor, which is not affine. Code generators add a tile counter TT with τT≤ϕ≤τT+τ−1\tau T \le \phi \le \tau T + \tau - 1 and scan the larger polyhedron.

When to use it

Use polyhedral scanning whenever loops must be produced from a polyhedral description: after an affine scheduler, for loop tiling with parametric bounds, or to rewrite a nest under a unimodular transformation. For one perfect nest and a unimodular change, Fourier-Motzkin bounds alone are enough. For many statements with different domains, separation avoids tests in the inner loops.

Pitfalls

  • Affine programs only. The domains, schedules and context must be affine in the counters and the parameters. Data-dependent bounds or subscripts leave the model.
  • A legal schedule can still give slow code. Scanning makes the code follow the schedule, but separation can blow up the code size, and many small pieces near the borders cost branch and loop overhead.
  • Integer holes. A rational shadow can contain integer values with no integer point above them. Without stride detection, the code runs empty loops there.
  • Context matters. If the context of the parameters is too weak, the generator emits guards and pieces for parameter values that never occur, as in the guard N−1≥0N - 1 \ge 0 of the stencil example.
  • Ties. Points of two statements with the same time vector run in text order. If the schedule is not one to one, the counters themselves decide the order, which must then be legal too.

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.

polyhedral_scanning.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/polyhedral-scanning/. The authors are listed in prov/19214B.jsonl.
"""Polyhedral scanning: loop nests that visit the integer points of a union
of polyhedra in lexicographic order.

Each statement S has a domain D_S and an affine schedule theta_S. Its
points in the scanning space are (theta_S(i), i, 0...), one dimension per
schedule entry and per loop counter, padded with zeros to a common length.
Visiting the union of these sets in lexicographic order runs the program in
schedule order.

At level k the generator projects every polyhedron on the first k + 1
dimensions by Fourier-Motzkin elimination, separates the projections into
disjoint pieces (the Quillere-Rajopadhye-Wilde method), sorts the pieces
along dimension k, and makes one loop per piece whose bounds are the
constraints of the piece on that dimension. Inside each loop it recurses on
the statements of the piece.

A constraint is a list of integers (a_0, ..., a_{v-1}, c) over the dimensions
and then the parameters, and means a . x + c >= 0. An exact simplex method
on integer rows decides emptiness and implication.
"""

from fractions import Fraction
from math import gcd, lcm


# ------------------------------------------------------- exact simplex method

def _reduce(row):
    g = gcd(*row)
    return [x // g for x in row] if g > 1 else row


def _update(row, pr, nz, p, k):
    """p * row - k * pr, touching only the nonzero places nz of pr."""
    out = row[:] if p == 1 else [p * x for x in row]
    for t in nz:
        out[t] -= k * pr[t]
    return out if p == 1 else _reduce(out)


def _pivot(rows, obj, basis, r, j):
    pr, p = rows[r], rows[r][j]
    nz = [t for t, y in enumerate(pr) if y]
    for i in range(len(rows)):
        k = rows[i][j]
        if i != r and k:
            rows[i] = _update(rows[i], pr, nz, p, k)
    k = obj[j]
    if k:
        obj[:] = _update(obj, pr, nz, p, k)
    basis[r] = j


def _run(rows, obj, basis, allowed, lexcols):
    """Maximize; obj[j] > 0 means column j improves. Dantzig's rule with a
    lexicographic ratio test on the start basis columns, which cannot cycle;
    after a fixed number of pivots, Bland's rule as a second guard. Returns
    False if the problem is unbounded."""
    cap = 50 * (len(rows) + len(obj))
    steps = 0
    while True:
        steps += 1
        if steps > cap:
            j = next((j for j in allowed if obj[j] > 0), None)
        else:
            j = max(allowed, key=lambda j: obj[j], default=None)
            if j is not None and obj[j] <= 0:
                j = None
        if j is None:
            return True
        leave = None
        for r, row in enumerate(rows):
            if row[j] <= 0:
                continue
            if leave is None:
                leave = r
                continue
            a, b = row[j], rows[leave][j]
            if steps > cap:
                lhs, rhs = row[-1] * b, rows[leave][-1] * a
                if lhs < rhs or (lhs == rhs and basis[r] < basis[leave]):
                    leave = r
                continue
            for t in [-1] + list(lexcols):
                lhs, rhs = row[t] * b, rows[leave][t] * a
                if lhs != rhs:
                    if lhs < rhs:
                        leave = r
                    break
        if leave is None:
            return False
        _pivot(rows, obj, basis, leave, j)


def lp_max(c, A, b):
    """Maximize c.x subject to A x = b and x >= 0, with integer data, in
    exact arithmetic. Returns the optimal x as Fractions, None if the system
    is infeasible; raises ValueError if the problem is unbounded."""
    m, n = len(A), len(c)
    rows, basis = [], []
    for i in range(m):
        row = list(A[i]) + [b[i]]
        if row[-1] < 0:
            row = [-x for x in row]
        art = [0] * m
        art[i] = 1
        rows.append(_reduce(row[:n] + art + row[n:]))
        basis.append(n + i)
    width = n + m + 1
    den = lcm(*[rows[i][n + i] for i in range(m)]) if m else 1
    obj = [0] * width
    for i in range(m):
        f = den // rows[i][n + i]
        for t in range(width):
            if not (n <= t < n + m):
                obj[t] += f * rows[i][t]
    _run(rows, obj, basis, range(n), range(n, n + m))
    if obj[-1] != 0:
        return None
    for r in range(len(rows) - 1, -1, -1):
        if basis[r] >= n:
            j = next((j for j in range(n) if rows[r][j] != 0), None)
            if j is None:
                del rows[r], basis[r]
            else:
                if rows[r][j] < 0:
                    rows[r] = [-x for x in rows[r]]
                _pivot(rows, [0] * width, basis, r, j)
    obj = list(c) + [0] * m + [0]
    for r in range(len(rows)):
        k = obj[basis[r]]
        if k:
            p = rows[r][basis[r]]
            obj = _reduce([p * x - k * y for x, y in zip(obj, rows[r])])
    if not _run(rows, obj, basis, range(n), range(n, n + m)):
        raise ValueError("unbounded")
    x = [Fraction(0)] * n
    for r, j in enumerate(basis):
        if j < n:
            x[j] = Fraction(rows[r][-1], rows[r][j])
    return x


def _standard(rows, nv, obj):
    """{x free : rows} as A z = b, z >= 0, with x = p - q and one slack per row."""
    m = len(rows)
    A, b = [], []
    for i, r in enumerate(rows):
        line = []
        for j in range(nv):
            line += [r[j], -r[j]]
        slack = [0] * m
        slack[i] = -1
        A.append(line + slack)
        b.append(-r[-1])
    c = []
    for j in range(nv):
        c += [-obj[j], obj[j]]
    return c + [0] * m, A, b


def feasible(rows, nv):
    """Does {x in Q^nv : rows} have a point?"""
    if any(not any(r[:-1]) and r[-1] < 0 for r in rows):
        return False
    rows = [r for r in rows if any(r[:-1])]
    if not rows:
        return True
    c, A, b = _standard(rows, nv, [0] * nv)
    return lp_max(c, A, b) is not None


def implied(rows, g, nv):
    """Does every rational point of the nonempty set {rows} satisfy g >= 0?"""
    if not any(g[:-1]):
        return g[-1] >= 0
    c, A, b = _standard(rows, nv, g)
    try:
        x = lp_max(c, A, b)
    except ValueError:
        return False
    if x is None:
        return True
    return sum(g[j] * (x[2 * j] - x[2 * j + 1]) for j in range(nv)) + g[-1] >= 0


# ------------------------------------------------- constraints and projection

def norm(row):
    """Divide by the gcd of the coefficients and round the constant down.
    The integer points stay the same."""
    g = gcd(*row[:-1])
    if g <= 1:
        return list(row)
    return [x // g for x in row[:-1]] + [row[-1] // g]


def clean(rows):
    """Normalize, drop trivial rows, keep the tightest row per direction."""
    best = {}
    for r in rows:
        r = norm(r)
        if not any(r[:-1]):
            if r[-1] < 0:
                return [r]
            continue
        key = tuple(r[:-1])
        if key not in best or r[-1] < best[key]:
            best[key] = r[-1]
    return [list(k) + [c] for k, c in best.items()]


def negate(g):
    """The integer complement of g >= 0, that is g <= -1."""
    return [-x for x in g[:-1]] + [-g[-1] - 1]


def eliminate(rows, j):
    """Fourier-Motzkin elimination of variable j. With an equality on the
    variable, substitution is enough."""
    for r in rows:
        if r[j] > 0 and [-x for x in r] in rows:
            a = r[j]
            return clean([[a * x - s[j] * y for x, y in zip(s, r)] if s[j] else s
                          for s in rows if s is not r and s != [-x for x in r]])
    pos = [r for r in rows if r[j] > 0]
    neg = [r for r in rows if r[j] < 0]
    out = [r for r in rows if r[j] == 0]
    for p in pos:
        for q in neg:
            a, b = p[j], -q[j]
            out.append([b * x + a * y for x, y in zip(p, q)])
    return clean(out)


def prune(rows, nv):
    """Remove the rows that the others imply."""
    rows = clean(rows)
    if len(rows) == 1 and not any(rows[0][:-1]):
        return rows
    k = 0
    while k < len(rows):
        rest = rows[:k] + rows[k + 1:]
        if rest and implied(rest, rows[k], nv):
            rows = rest
        else:
            k += 1
    return rows


def project(rows, keep, n, nv):
    """The shadow of {rows} on the first `keep` dimensions (and the
    parameters), by eliminating the dimensions n - 1, ..., keep."""
    for j in range(n - 1, keep - 1, -1):
        rows = eliminate(rows, j)
        if len(rows) > 3 * nv:
            rows = prune(rows, nv)
    return rows


# ------------------------------------------------------------- separation

def difference(P, Q, nv):
    """P minus Q as disjoint pieces: P, q_1 >= 0, ..., q_{t-1} >= 0, q_t <= -1."""
    out, acc = [], list(P)
    for q in Q:
        piece = acc + [negate(q)]
        if feasible(piece, nv):
            out.append(clean(piece))
        acc = acc + [q]
        if not feasible(acc, nv):
            break
    return out


def separate(polys, nv):
    """Disjoint pieces that cover the union of the polyhedra, each with the
    set of polyhedra that contain it."""
    pieces = []
    for rows, lab in polys:
        new, rest = [], [rows]
        for prow, plab in pieces:
            both = clean(prow + rows)
            if feasible(both, nv):
                new.append((both, plab | lab))
            new += [(d, plab) for d in difference(prow, rows, nv)]
            rest = [r2 for r in rest for r2 in difference(r, prow, nv)]
        new += [(r, lab) for r in rest]
        pieces = new
    return pieces


def _pair(A, B, k, nv):
    """A and B in one space of nv + 1 variables: B's dimension k moves to
    the new variable nv, the other dimensions and the parameters are shared."""
    a = [r[:-1] + [0, r[-1]] for r in A]
    b = []
    for r in B:
        s = r[:-1] + [r[k], r[-1]]
        s[k] = 0
        b.append(s)
    return a + b


def sort_pieces(pieces, k, nv):
    """An order of the pieces such that two pieces that exist for the same
    outer values come with the smaller x_k first, or None."""
    m = len(pieces)
    after = [set() for _ in range(m)]
    indeg = [0] * m
    for x in range(m):
        for y in range(x + 1, m):
            both = _pair(pieces[x][0], pieces[y][0], k, nv)
            if not feasible(both, nv + 1):
                continue                     # never at the same outer values
            ge = [0] * (nv + 2)
            ge[k], ge[nv] = 1, -1            # x_k(A) - x_k(B) >= 0
            if not feasible(both + [ge], nv + 1):
                after[x].add(y)
                indeg[y] += 1
            elif not feasible(both + [[-v for v in ge]], nv + 1):
                after[y].add(x)
                indeg[x] += 1
            else:
                return None
    out, ready = [], [x for x in range(m) if indeg[x] == 0]
    while ready:
        x = min(ready)
        ready.remove(x)
        out.append(x)
        for y in after[x]:
            indeg[y] -= 1
            if indeg[y] == 0:
                ready.append(y)
    return [pieces[x] for x in out] if len(out) == m else None


# --------------------------------------------------------- code generation

class Scop:
    """Statements with domains and schedules. Each statement is a dict with
    'name', 'iters', 'domain' (affine dicts >= 0 over iters and params) and
    'schedule' (a list of affine dicts). Affine dicts map names to integers;
    the key "" is the constant."""

    def __init__(self, params, context, stmts):
        self.params, self.context, self.stmts = params, context, stmts
        self.m = max(len(s["schedule"]) for s in stmts)
        self.d = max(len(s["iters"]) for s in stmts)
        self.dims = [f"t{k + 1}" for k in range(self.m)] + [f"i{k + 1}" for k in range(self.d)]
        self.names = self.dims + params
        self.n, self.nv = len(self.dims), len(self.names)

    def row(self, aff, rename=None):
        rename = rename or {}
        r = [0] * (self.nv + 1)
        for v, c in aff.items():
            if v == "":
                r[-1] += c
            else:
                r[self.names.index(rename.get(v, v))] += c
        return r

    def context_rows(self):
        return [self.row(c) for c in self.context]

    def polyhedron(self, s):
        """The points (theta(i), i, 0...) of statement s in the scanning space."""
        S = self.stmts[s]
        ren = {x: f"i{k + 1}" for k, x in enumerate(S["iters"])}
        rows = [self.row(c, ren) for c in S["domain"]] + self.context_rows()
        sched = S["schedule"] + [{}] * (self.m - len(S["schedule"]))
        for k, th in enumerate(sched):
            r = self.row(th, ren)
            r[k] -= 1                        # theta_k(i) - t_k = 0
            rows += [r, [-x for x in r]]
        for k in range(len(S["iters"]), self.d):
            r = [0] * (self.nv + 1)
            r[self.m + k] = 1                # i_k = 0 below the statement's depth
            rows += [r, [-x for x in r]]
        return clean(rows)


def scan(scop):
    """The loop nest for the scop: a list of nodes for codegen at level 0."""
    polys = [(scop.polyhedron(s), frozenset([s])) for s in range(len(scop.stmts))]
    ctx = prune(scop.context_rows(), scop.nv) if scop.context else []
    return codegen(polys, 0, ctx, scop.n, scop.nv)


def codegen(polys, k, ctx, n, nv):
    projs = []
    for rows, lab in polys:
        q = prune(project(rows, k + 1, n, nv), nv)  # @line L1
        if feasible(q, nv):
            projs.append((q, lab))
    pieces = separate(projs, nv)  # @line L2
    order = sort_pieces(pieces, k, nv)  # @line L3
    parts = []
    for rows, lab in (order if order is not None else pieces):  # @line L5
        guards = [r for r in rows if r[k] == 0 and not implied(ctx, r, nv)] if ctx else \
            [r for r in rows if r[k] == 0]  # @line L6
        bounds = prune([r for r in rows if r[k] != 0] + ctx, nv)
        bounds = [r for r in bounds if r[k] != 0]  # @line L7
        if k == n - 1:
            body = [{"exec": sorted(lab)}]  # @line L8
        else:
            inner = [(clean(prow + rows), plab) for prow, plab in polys if plab <= lab]
            body = codegen(inner, k + 1, prune(ctx + rows, nv), n, nv)  # @line L9
        parts.append({"k": k, "guards": guards, "bounds": bounds, "body": body})  # @line L10
    if order is None and len(parts) > 1:
        return [{"k": k, "union": parts}]  # @line L4
    return parts


# ------------------------------------------------------------- execution

def _rest(r, k, vals):
    return sum(r[v] * vals[v] for v in range(len(vals)) if v != k and r[v]) + r[-1]


def _range(node, vals):
    """The range of x_k in a loop node, or None if a guard fails."""
    k = node["k"]
    if any(_rest(g, k, vals) < 0 for g in node["guards"]):
        return None
    lo, hi = None, None
    for r in node["bounds"]:
        a, rest = r[k], _rest(r, k, vals)
        if a > 0:
            b = -(rest // a)                 # ceil(-rest / a)
            lo = b if lo is None else max(lo, b)
        else:
            b = rest // (-a)                 # floor(rest / -a)
            hi = b if hi is None else min(hi, b)
    if lo is None or hi is None:
        raise ValueError("unbounded loop")
    return lo, hi


def execute(ast, scop, env, visit):
    """Run the loop nest: visit(s, point) for each statement instance, where
    point is the vector of all scanning dimensions."""
    vals = [0] * scop.n + [env[p] for p in scop.params]

    def run(nodes):
        for node in nodes:
            if "exec" in node:
                for s in node["exec"]:
                    visit(s, tuple(vals[:scop.n]))
                continue
            k = node["k"]
            if "union" in node:
                ranges = [_range(p, vals) for p in node["union"]]
                live = [(p, r) for p, r in zip(node["union"], ranges) if r]
                if not live:
                    continue
                for x in range(min(r[0] for _, r in live), max(r[1] for _, r in live) + 1):
                    vals[k] = x
                    for p, r in live:
                        if r[0] <= x <= r[1]:
                            run(p["body"])
                            vals[k] = x
                continue
            r = _range(node, vals)
            if r is None:
                continue
            for x in range(r[0], r[1] + 1):
                vals[k] = x
                run(node["body"])
                vals[k] = x
            vals[k] = 0

    run(ast)


def instance_of(scop, s, point):
    """The iteration vector of statement s at a scanning point."""
    return point[scop.m:scop.m + len(scop.stmts[s]["iters"])]


# ------------------------------------------------------------- printing

def _expr(coefs, names):
    terms = []
    for v, c in zip(names, coefs[:-1]):
        if c:
            terms.append((c, v))
    out = ""
    for c, v in terms:
        t = v if abs(c) == 1 else f"{abs(c)}*{v}"
        out += (" - " if c < 0 else " + ") + t if out else ("-" if c < 0 else "") + t
    if coefs[-1] or not out:
        c = coefs[-1]
        out += f" {'-' if c < 0 else '+'} {abs(c)}" if out else str(c)
    return out


def _bound(r, k, names):
    a = r[k]
    rest = [x for x in r]
    rest[k] = 0
    if a > 0:
        e = _expr([-x for x in rest], names)
        return e if a == 1 else f"ceil(({e}) / {a})"
    e = _expr(rest, names)
    return e if a == -1 else f"floor(({e}) / {-a})"


def show(ast, scop, depth=0):
    """The loop nest as text."""
    names, pad, lines = scop.names, "  " * depth, []
    for node in ast:
        if "exec" in node:
            for s in node["exec"]:
                S = scop.stmts[s]
                args = ", ".join(scop.dims[scop.m + j] for j in range(len(S["iters"])))
                lines.append(f"{pad}{S['name']}({args})")
            continue
        if "union" in node:
            k = node["k"]
            lines.append(f"{pad}for {names[k]} in the union of:")
            for p in node["union"]:
                lines += show([p], scop, depth + 1)
            continue
        k, inner = node["k"], depth
        if node["guards"]:
            conds = " and ".join(f"{_expr(g, names)} >= 0" for g in node["guards"])
            lines.append(f"{pad}if {conds}:")
            inner += 1
        lo = [_bound(r, k, names) for r in node["bounds"] if r[k] > 0]
        hi = [_bound(r, k, names) for r in node["bounds"] if r[k] < 0]
        ipad = "  " * inner
        if len(lo) == 1 and lo == hi:
            lines.append(f"{ipad}{names[k]} = {lo[0]}")
            inner -= 1
        else:
            lo_s = lo[0] if len(lo) == 1 else f"max({', '.join(lo)})"
            hi_s = hi[0] if len(hi) == 1 else f"min({', '.join(hi)})"
            lines.append(f"{ipad}for {names[k]} = {lo_s} to {hi_s}:")
        lines += show(node["body"], scop, inner + 1)
    return lines


# ------------------------------------------------------------- examples

def triangle(schedule="ij"):
    """for i = 0 to N: for j = 0 to i: S(i, j), scanned in (i, j) or (j, i)."""
    sched = [{"i": 1}, {"j": 1}] if schedule == "ij" else [{"j": 1}, {"i": 1}]
    S = {"name": "S", "iters": ["i", "j"],
         "domain": [{"i": 1}, {"N": 1, "i": -1}, {"j": 1}, {"i": 1, "j": -1}],
         "schedule": sched}
    return Scop(["N"], [{"N": 1}], [S])


def two_ranges():
    """S1 on 0 <= i <= N and S2 on 2 <= i <= N + 2, fused: (i, 0) and (i, 1)."""
    S1 = {"name": "S1", "iters": ["i"], "domain": [{"i": 1}, {"N": 1, "i": -1}],
          "schedule": [{"i": 1}, {}]}
    S2 = {"name": "S2", "iters": ["i"], "domain": [{"i": 1, "": -2}, {"N": 1, "i": -1, "": 2}],
          "schedule": [{"i": 1}, {"": 1}]}
    return Scop(["N"], [{"N": 1}], [S1, S2])


def skewed_stencil():
    """for t = 0 to N: for i = 1 to N: S(t, i), with the schedule (t, t + i)."""
    S = {"name": "S", "iters": ["t", "i"],
         "domain": [{"t": 1}, {"N": 1, "t": -1}, {"i": 1, "": -1}, {"N": 1, "i": -1}],
         "schedule": [{"t": 1}, {"t": 1, "i": 1}]}
    return Scop(["N"], [{"N": 1}], [S])


if __name__ == "__main__":
    for title, scop in [("triangle, (i, j)", triangle("ij")), ("triangle, (j, i)", triangle("ji")),
                        ("two ranges, fused", two_ranges()), ("skewed stencil", skewed_stencil())]:
        print(f"-- {title}")
        print("\n".join(show(scan(scop), scop)))
test_polyhedral_scanning.py 243 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/polyhedral-scanning/. The authors are listed in prov/19214B.jsonl.
"""Tests: for small parameter values, the generated loops must visit every
integer point of every statement domain exactly once, in lexicographic order
of (schedule, iteration vector, statement). Running the statements in that
order on small arrays must give the same memory as the original program
whenever a brute-force check finds the schedule legal."""

import random
import unittest

from polyhedral_scanning import (
    Scop, clean, eliminate, execute, feasible, implied, instance_of, scan, separate,
    show, skewed_stencil, triangle, two_ranges,
)


def value(aff, env):
    return sum(c * (env[v] if v else 1) for v, c in aff.items())


def brute(scop, env, box):
    """All (point, s) with the iteration vector in the box and the domain."""
    out = []
    for s, S in enumerate(scop.stmts):
        d = len(S["iters"])

        def rec(prefix):
            if len(prefix) == d:
                e = dict(env)
                e.update(zip(S["iters"], prefix))
                if all(value(c, e) >= 0 for c in S["domain"]):
                    sched = [value(th, e) for th in S["schedule"]]
                    sched += [0] * (scop.m - len(sched))
                    out.append((tuple(sched) + tuple(prefix) + (0,) * (scop.d - d), s))
                return
            for x in range(-box, box + 1):
                rec(prefix + [x])
        rec([])
    return sorted(out)


def scanned(scop, ast, env):
    seen = []
    execute(ast, scop, env, lambda s, p: seen.append((p, s)))
    return seen


def check_scan(test, scop, ns):
    ast = scan(scop)
    for n in ns:
        env = {"N": n}
        got, want = scanned(scop, ast, env), brute(scop, env, 2 * n + 4)
        # equal to the sorted list of all points: each point once, in order
        test.assertEqual(got, want, f"N={n}\n" + "\n".join(show(ast, scop)))
    return ast


class Pieces(unittest.TestCase):
    def test_simplex_tests(self):
        # x >= 0, y >= 0, x + y <= 2 in two variables
        rows = [[1, 0, 0], [0, 1, 0], [-1, -1, 2]]
        self.assertTrue(feasible(rows, 2))
        self.assertFalse(feasible(rows + [[1, 1, -3]], 2))
        self.assertTrue(implied(rows, [-1, 0, 2], 2))
        self.assertFalse(implied(rows, [-1, 0, 1], 2))

    def test_fourier_motzkin(self):
        # 0 <= j <= i <= N gives 0 <= i <= N after eliminating j
        rows = [[0, 1, 0, 0], [1, -1, 0, 0], [-1, 0, 1, 0]]
        self.assertEqual(sorted(eliminate(rows, 1)), sorted([[1, 0, 0, 0], [-1, 0, 1, 0]]))
        # i = 2 j with 0 <= i <= 3: the shadow is the rational one, odd i included
        rows = [[-1, 2, 0], [1, -2, 0], [1, 0, 0], [-1, 0, 3]]
        self.assertEqual(sorted(eliminate(rows, 1)), sorted([[1, 0, 0], [-1, 0, 3]]))
        # 2 i + 1 >= 0 has the same integer points as i >= 0
        self.assertEqual(clean([[2, 1]]), [[1, 0]])

    def test_separation_is_disjoint_and_covers(self):
        # [0, 5] and [3, 8] on one line
        a, b = [[1, 0], [-1, 5]], [[1, -3], [-1, 8]]
        pieces = separate([(a, frozenset("a")), (b, frozenset("b"))], 1)
        for x in range(-2, 11):
            hit = [lab for rows, lab in pieces if all(r[0] * x + r[1] >= 0 for r in rows)]
            want = frozenset(c for c, (lo, hi) in [("a", (0, 5)), ("b", (3, 8))] if lo <= x <= hi)
            self.assertEqual(hit, [want] if want else [], x)


class Examples(unittest.TestCase):
    def test_triangle(self):
        check_scan(self, triangle("ij"), range(0, 5))
        ast = check_scan(self, triangle("ji"), range(0, 5))
        self.assertEqual(show(ast, triangle("ji"))[:2], ["for t1 = 0 to N:", "  for t2 = t1 to N:"])

    def test_two_ranges_split_in_three_loops(self):
        scop = two_ranges()
        ast = check_scan(self, scop, range(0, 6))
        self.assertEqual(len(ast), 3)
        self.assertEqual(show(ast, scop)[0], "for t1 = 0 to min(N, 1):")

    def test_skewed_stencil(self):
        check_scan(self, skewed_stencil(), range(0, 5))

    def test_guarded_union_fallback(self):
        # force the path used when the pieces cannot be sorted
        import polyhedral_scanning as ps
        saved = ps.sort_pieces
        ps.sort_pieces = lambda pieces, k, nv: None
        try:
            ast = check_scan(self, two_ranges(), range(0, 6))
            self.assertIn("union", ast[0])
            check_scan(self, random_scop(random.Random(7), False), range(0, 4))
        finally:
            ps.sort_pieces = saved

    def test_stride(self):
        # the schedule 2 i leaves holes: odd t1 values have no point
        S = {"name": "S", "iters": ["i"], "domain": [{"i": 1}, {"N": 1, "i": -1}],
             "schedule": [{"i": 2}]}
        check_scan(self, Scop(["N"], [{"N": 1}], [S]), range(0, 5))


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

DOMS_J = [({"j": 1}, {"N": 1, "j": -1}), ({"j": 1}, {"i": 1, "j": -1}),
          ({"j": 1, "i": -1}, {"N": 1, "j": -1})]
DOMS_I = [({"i": 1}, {"N": 1, "i": -1}), ({"i": 1, "": -1}, {"N": 1, "i": -1, "": 1}),
          ({"i": 1, "": -2}, {"N": 1, "i": -1})]
LINEAR = [[{"i": 1}, {"j": 1}], [{"j": 1}, {"i": 1}], [{"i": 1}, {"i": 1, "j": 1}],
          [{"i": 1, "j": 1}, {"i": 1}], [{"i": 1, "j": 1}, {"j": 1}]]


def random_scop(rng, original):
    """One or two outer loops with up to three statements of depth 1 or 2.
    Each statement has its original schedule vector (b0, i, b1, j, b2) and,
    unless `original`, a random schedule of the same shape. The fields
    'write', 'reads' and 'omega' are used by the tests only."""
    stmts, k = [], 0
    for b0 in range(rng.randint(1, 2)):
        lo_i, hi_i = rng.choice(DOMS_I)
        for b1 in range(rng.randint(1, 2)):
            if k == 3:
                break
            if rng.random() < 0.5:
                iters, dom = ["i"], [lo_i, hi_i]
                omega = [{"": b0}, {"i": 1}, {"": b1}, {}, {}]
                lin = [{"i": rng.choice([1, 1, 2])}, {}]
            else:
                iters, dom = ["i", "j"], [lo_i, hi_i] + list(rng.choice(DOMS_J))
                omega = [{"": b0}, {"i": 1}, {"": b1}, {"j": 1}, {}]
                lin = rng.choice(LINEAR)
            sched = omega if original else [{"": b0}, lin[0], {"": b1}, lin[1], {}]

            def sub():
                d = {"i": rng.choice([0, 1, 1, -1])}
                if "j" in iters:
                    d["j"] = rng.choice([0, 1, -1])
                return d, rng.choice([-1, 0, 0, 1])
            reads = [(rng.choice("AB"), sub()) for _ in range(rng.randint(1, 2))]
            stmts.append({"name": f"S{k}", "iters": iters, "domain": dom, "schedule": sched,
                          "omega": omega, "write": (rng.choice("AB"), sub()), "reads": reads})
            k += 1
    return Scop(["N"], [{"N": 1}], stmts)


def cell(acc, env):
    arr, (d, c) = acc
    return arr, value(d, env) + c


def instances(scop, env, box):
    """(omega vector, s, iteration vector) of every instance."""
    out = []
    for point, s in brute(scop, env, box):
        S = scop.stmts[s]
        it = instance_of(scop, s, point)
        e = dict(env)
        e.update(zip(S["iters"], it))
        out.append((tuple(value(o, e) for o in S["omega"]), s, it))
    return sorted(out)


def run(scop, env, order):
    mem = {}
    for s, it in order:
        S = scop.stmts[s]
        e = dict(env)
        e.update(zip(S["iters"], it))
        args = [mem.get(cell(r, e), 1) for r in S["reads"]]
        mem[cell(S["write"], e)] = (sum(args) * 31 + 7 * s + 1) % 1000003
    return mem


def legal(scop, env, inst, pos):
    """Every pair of instances that touch one cell, with a write, keeps its
    order. pos maps (s, it) to the place in the new order."""
    touched = {}
    for _, s, it in inst:
        S = scop.stmts[s]
        e = dict(env)
        e.update(zip(S["iters"], it))
        touched[(s, it)] = ({cell(S["write"], e)}, {cell(r, e) for r in S["reads"]})
    for x in range(len(inst)):
        a = inst[x][1:]
        wa, ra = touched[a]
        for y in range(x + 1, len(inst)):
            b = inst[y][1:]
            wb, rb = touched[b]
            if (wa & (wb | rb) or ra & wb) and pos[b] < pos[a]:
                return False
    return True


class RandomPrograms(unittest.TestCase):
    def test_original_schedule_gives_original_order(self):
        rng = random.Random(2000)
        for _ in range(12):
            scop = random_scop(rng, True)
            ast = check_scan(self, scop, range(0, 4))
            for n in range(0, 4):
                env = {"N": n}
                order = [(s, instance_of(scop, s, p)) for p, s in scanned(scop, ast, env)]
                self.assertEqual(order, [(s, it) for _, s, it in instances(scop, env, 2 * n + 4)])

    def test_random_schedules(self):
        rng = random.Random(1991)
        runs = 0
        for _ in range(16):
            scop = random_scop(rng, False)
            ast = check_scan(self, scop, range(0, 4))
            for n in range(0, 4):
                env = {"N": n}
                inst = instances(scop, env, 2 * n + 4)
                order = [(s, instance_of(scop, s, p)) for p, s in scanned(scop, ast, env)]
                pos = {x: t for t, x in enumerate(order)}
                if legal(scop, env, inst, pos):
                    want = run(scop, env, [(s, it) for _, s, it in inst])
                    self.assertEqual(run(scop, env, order), want)
                    runs += 1
        self.assertGreater(runs, 20)


if __name__ == "__main__":
    unittest.main()

History

Ancourt and Irigoin (1991) gave a general method to scan one polyhedron with DO loops, using Fourier-Motzkin elimination for the bounds. Quilleré, Rajopadhye and Wilde (2000) gave the recursive separation algorithm, which produces code with no redundant tests inside loops. Bastoul (2004) extended it to general schedules and made it practical in CLooG, used by many polyhedral tools, including Pluto. Grosser, Verdoolaege and Cohen (2015) described the AST generator of isl, which handles the same problem with more options for code size.

References

  1. Corinne Ancourt and François Irigoin, Scanning polyhedra with DO loops, PPoPP 1991, 39-50, loop bounds for one polyhedron by Fourier-Motzkin elimination, as maxima and minima of rounded affine expressions
  2. Fabien Quilleré, Sanjay Rajopadhye and Doran Wilde, Generation of efficient nested loops from polyhedra, International Journal of Parallel Programming 28(5), 2000, 469-498, the recursive algorithm for a union of polyhedra, with projection, separation into disjoint pieces and sorting at each level
  3. Cédric Bastoul, Code generation in the polyhedral model is easier than you think, PACT 2004, 7-16, scanning with scattering functions (schedules), the CLooG tool, and the control of code size by limiting separation
  4. Tobias Grosser, Sven Verdoolaege and Albert Cohen, Polyhedral AST generation is more than scanning polyhedra, ACM TOPLAS 37(4), 2015, the AST generator of isl, with options for separation, unrolling and isolation of full tiles

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example