Algorithm Search⌘K

Algorithmcore

Banerjee test

Also called Banerjee inequalities.

Reports independence when the constant of a subscript equation lies outside the real bounds of the equation over the loop bounds.

Time
O(m k) worstO(k) best
Space
O(1) extra
Where
k = the depth of the loop nest; m = the number of subscripts
Properties
deterministiciterative

The Banerjee test is a dependence test that uses the loop bounds. For one subscript pair, it computes the smallest and the largest value that the left side of the dependence equation can take when every loop index runs over the real interval of its loop. If the constant of the equation lies outside that range, no pair of iterations can touch the same element, and the references are independent. The bounds have a closed form for each level and each direction (<<, ==, >> or ∗*), so the test costs a few operations per loop and can refine a direction vector one level at a time. The range is exact over the reals but not over the integers, so the answer "maybe" can be wrong; the answer "independent" never is.

In plain words

The two accesses touch the same element when some expression in the loop indices equals some constant. Each index can only take values inside its loop. So the expression has a smallest and a largest possible value, and both are easy to compute: for each loop, push the index to the end of its range that makes the term smallest, or largest. If the constant is below the smallest value or above the largest, the two accesses can never meet. The test can also ask the same question for pairs where the second access comes in a later, the same or an earlier iteration of each loop, which tells the compiler which loops carry the dependence. It works with fractions, not whole numbers, so it sometimes says "maybe" when the indices could only meet between two whole values.

The problem

A rectangular loop nest of depth kk runs loop ll over Ll≤il≤UlL_l \le i_l \le U_l. Two references to an array of mm dimensions have the subscripts ar0+∑larlila_{r0} + \sum_l a_{rl} i_l (source) and br0+∑lbrljlb_{r0} + \sum_l b_{rl} j_l (sink). A direction vector ψ⃗∈{<,=,>,∗}k\vec{\psi} \in \{<, =, >, *\}^k, in Wolfe's notation (<< at level ll means il<jli_l < j_l, the sink runs in a later iteration of loop ll), restricts the pairs. The question is whether there are integer i⃗\vec{i}, j⃗\vec{j} in the bounds with il ψl jli_l \,\psi_l\, j_l and, for each dimension rr,

∑l=1k(arlil−brljl)=br0−ar0.\sum_{l=1}^{k} \bigl(a_{rl} i_l - b_{rl} j_l\bigr) = b_{r0} - a_{r0}.

The test answers "independent" or "maybe"; it must never answer "independent" when such vectors exist. The search over direction vectors returns the set of plain vectors that the test cannot rule out.

The algorithm

Write t+=max⁡(t,0)t^+ = \max(t, 0) and t−=max⁡(−t,0)t^- = \max(-t, 0), so t=t+−t−t = t^+ - t^-, and N=U−LN = U - L. For a strict direction the integer constraint x<yx < y becomes the real constraint x+1≤yx + 1 \le y.

  1. BANERJEE-TEST(a, b, L, U, psi):
  2. 1for each dimension r do
  3. 2c <- b_r0 - a_r0
  4. 3lo <- 0; hi <- 0
  5. 4for l <- 1 to k do
  6. 5range <- LEVEL-BOUNDS(a_rl, b_rl, L_l, U_l, psi_l)
  7. 6if range is empty then return "independent"
  8. 7lo <- lo + min(range); hi <- hi + max(range)
  9. 8if c < lo or c > hi then return "independent"
  10. 9return "maybe"
  11. LEVEL-BOUNDS(a, b, L, U, d): bounds of a*x - b*y over the region of d
  12. 10if d = "*" then return [a+ L - a- U - b+ U + b- L, a+ U - a- L - b+ L + b- U]
  13. 11if d = "=" then e <- a - b; return [e+ L - e- U, e+ U - e- L]
  14. 12if d = "<" then (empty if N < 1); v0 <- (a - b) L - b
  15. return [v0 - (a- + b)+ (N - 1), v0 + (a+ - b)+ (N - 1)]
  16. 13if d = ">" then (empty if N < 1); v0 <- (a - b) L + a
  17. return [v0 - (b+ - a)+ (N - 1), v0 + (a + b-)+ (N - 1)]

The region of a level is a rectangle for ∗*, a diagonal segment for ==, and a triangle for << and >>. The formulas are the extremes of ax−bya x - b y over its corners: (L,L+1)(L, L+1), (L,U)(L, U) and (U−1,U)(U-1, U) for <<, and (L+1,L)(L+1, L), (U,L)(U, L) and (U,U−1)(U, U-1) for >>.

Search over direction vectors. Start with (∗,…,∗)(*, \dots, *). If the test says "maybe", replace the first ∗* by each of <<, ==, >> and test the three vectors; go on until no ∗* is left. A vector that tests "independent" is cut with all its refinements. The leaves are the direction vectors that the test cannot rule out.

Example

The loop

for i = 1 to 4:
  for j = 1 to 4:
    X[i + 2*j] = X[i + 2*j - 1] + 1

has a=(1,2)a = (1, 2), a0=0a_0 = 0 for the write and b=(1,2)b = (1, 2), b0=−1b_0 = -1 for the read, so c=−1c = -1. The left side is (i−i′)+2(j−j′)(i - i') + 2(j - j'), where (i′,j′)(i', j') is the iteration of the read. The search over directions gives these ranges:

ψ⃗\vec{\psi} range of the left side −1-1 inside?
(∗,∗)(*, *) [−9,9][-9, 9] yes, refine
(<,∗)(<, *) [−9,5][-9, 5] yes, refine
(<,<)(<, <) [−9,−3][-9, -3] no
(<,=)(<, =) [−3,−1][-3, -1] yes
(<,>)(<, >) [−1,5][-1, 5] yes
(=,∗)(=, *) [−6,6][-6, 6] yes, refine
(=,<)(=, <), (=,=)(=, =), (=,>)(=, >) [−6,−2][-6, -2], [0,0][0, 0], [2,6][2, 6] no
(>,∗)(>, *) [−5,9][-5, 9] yes, refine
(>,<)(>, <) [−5,1][-5, 1] yes
(>,=)(>, =), (>,>)(>, >) [1,3][1, 3], [3,9][3, 9] no

The result is {(<,=),(<,>),(>,<)}\{(<, =), (<, >), (>, <)\}, and enumeration of all 256256 pairs of iterations gives the same set, so here the test is exact. The vectors (<,=)(<, =) and (<,>)(<, >) are flow dependences from the write to the read, for example (1,1)→(2,1)(1, 1) \to (2, 1) and (1,2)→(4,1)(1, 2) \to (4, 1). The vector (>,<)(>, <) has the read first: it is an anti dependence from the read to the write, with direction (<,>)(<, >) after reversal, for example the read in (1,2)(1, 2) and the write in (2,1)(2, 1), both on X[4]X[4]. No vector starts with ==, so the inner loop carries nothing and is parallel. The direction (<,>)(<, >) makes loop interchange illegal.

Independent by the bounds only. For A[i] = A[i + 10] with 1≤i≤51 \le i \le 5, the GCD test says "maybe" (the gcd is 11), but i−ji - j lies in [−4,4][-4, 4] and c=10c = 10 does not. The Banerjee test says "independent".

Maybe without a dependence. For A[2*i] = A[3*i + 2] with 1≤i≤31 \le i \le 3, the range for ∗* is [−7,3][-7, 3], which holds c=2c = 2. Refined, << gives [−7,−4][-7, -4], == gives [−3,−1][-3, -1] and >> gives [0,3][0, 3], so the test keeps (>)(>). The point (i,j)=(2.5,1)(i, j) = (2.5, 1) solves the equation in the real triangle, but no integer point does: the loop writes A[2],A[4],A[6]A[2], A[4], A[6] and reads A[5],A[8],A[11]A[5], A[8], A[11].

Correctness

The full proof is in proofs/correctness.md. Its steps:

  1. The regions are convex hulls of their corners. Each region of a level (rectangle, segment, triangle) is the set of convex combinations of the corners listed above; the proof writes the weights out.
  2. The closed forms are the extremes over the corners. A linear function on a convex hull takes its minimum and maximum at corners, and the formulas of lines L10 to L13 evaluate them, using the positive and negative parts to choose the right corner.
  3. The sum of the extremes is the extreme of the sum. The left side is a sum of one term per level, and the region of a direction vector is a product of the level regions, so each term can be pushed to its extreme on its own. So lolo and hihi are the minimum and the maximum of the left side over the whole region.
  4. Exactness over the reals. The region is convex, so the segment from the minimizing point to the maximizing point stays in it, and the left side takes every value in [lo,hi][lo, hi] along it. So the test answers "maybe" for one subscript exactly when a real solution exists in the region.
  5. Soundness. An integer dependence with direction ψ⃗\vec{\psi} is a real point of the region (an integer x<yx < y gives x+1≤yx + 1 \le y) that solves each equation, so the test answers "maybe".
  6. The search loses nothing. The region of a refined vector is inside the region of the coarser one, so a cut vector would also fail every refinement.
Proof: The Banerjee bounds are the exact real range of a subscript equation, so the test is soundfull

Setting

The loop nest has depth kk, and loop ll runs over the integers Ll,…,UlL_l, \dots, U_l, with Nl=Ul−LlN_l = U_l - L_l. One subscript pair gives the equation

h(x⃗,y⃗)=∑l=1k(alxl−blyl)=c,c=b0−a0,h(\vec{x}, \vec{y}) = \sum_{l=1}^{k} (a_l x_l - b_l y_l) = c, \qquad c = b_0 - a_0,

where x⃗\vec{x} stands for the source iteration and y⃗\vec{y} for the sink iteration. For t∈Rt \in \mathbb{R} write t+=max⁡(t,0)t^+ = \max(t, 0) and t−=max⁡(−t,0)t^- = \max(-t, 0), so t=t+−t−t = t^+ - t^- and t+,t−≥0t^+, t^- \ge 0.

For a direction d∈{∗,=,<,>}d \in \{*, =, <, >\}, the region of level ll is the set of real pairs

Rl(d)={(x,y)∈R2:Ll≤x≤Ul, Ll≤y≤Ul, ρd(x,y)},R_l(d) = \{(x, y) \in \mathbb{R}^2 : L_l \le x \le U_l,\ L_l \le y \le U_l,\ \rho_d(x, y)\},

where ρ∗\rho_* is no condition, ρ=\rho_= is x=yx = y, ρ<\rho_< is x+1≤yx + 1 \le y and ρ>\rho_> is y+1≤xy + 1 \le x. For integers, x<yx < y is the same as x+1≤yx + 1 \le y, so every integer pair with x d yx \,d\, y in the bounds lies in Rl(d)R_l(d). The region of a direction vector ψ⃗\vec{\psi} is the product R(ψ⃗)=R1(ψ1)×⋯×Rk(ψk)R(\vec{\psi}) = R_1(\psi_1) \times \dots \times R_k(\psi_k).

The test computes, for each level, the pair (lol,hil)(lo_l, hi_l) of line L5 (the function level_bounds, lines L10 to L13), adds them in line L7, and answers "independent" in line L8 if c<loc < lo or c>hic > hi, or in line L6 if some region is empty.

Lemma 1 (each region is the convex hull of its vertices)

Let Vl(d)V_l(d) be the vertex list of the code:

dd Vl(d)V_l(d)
∗* (L,L),(L,U),(U,L),(U,U)(L, L), (L, U), (U, L), (U, U)
== (L,L),(U,U)(L, L), (U, U)
<<, if N≥1N \ge 1 (L,L+1),(L,U),(U−1,U)(L, L+1), (L, U), (U-1, U)
>>, if N≥1N \ge 1 (L+1,L),(U,L),(U,U−1)(L+1, L), (U, L), (U, U-1)

(dropping the index ll). Then Rl(d)R_l(d) is the set of convex combinations of Vl(d)V_l(d). For d∈{<,>}d \in \{<, >\} and N<1N < 1 the region is empty.

Proof. Each vertex lies in the region, and the region is convex (it is cut out by linear inequalities), so every convex combination of vertices lies in it. For the other inclusion, take (x,y)(x, y) in the region.

  • d=∗d = *. Put s=(x−L)/Ns = (x - L)/N and t=(y−L)/Nt = (y - L)/N if N>0N > 0 (if N=0N = 0 the region is the one point (L,L)(L, L)). Then s,t∈[0,1]s, t \in [0, 1] and (x,y)=(1−s)(1−t)(L,L)+(1−s)t(L,U)+s(1−t)(U,L)+st(U,U)(x, y) = (1-s)(1-t)(L, L) + (1-s)t(L, U) + s(1-t)(U, L) + st(U, U). The four weights are nonnegative and sum to 11.
  • d==d = {=}. Then x=yx = y and (x,x)=(1−s)(L,L)+s(U,U)(x, x) = (1 - s)(L, L) + s(U, U) with s=(x−L)/Ns = (x - L)/N, or the one point (L,L)(L, L) if N=0N = 0.
  • d=<d = {<}. The three numbers p=x−Lp = x - L, q=U−yq = U - y and r=y−x−1r = y - x - 1 are nonnegative in the region, and p+q+r=N−1p + q + r = N - 1. If N<1N < 1, they cannot all be nonnegative, so the region is empty. If N=1N = 1, all three are 00, and the region is the one point (L,L+1)=(L,U)(L, L + 1) = (L, U). If N≥2N \ge 2, the vertices have (p,q,r)(p, q, r) equal to (0,N−1,0)(0, N-1, 0), (0,0,N−1)(0, 0, N-1) and (N−1,0,0)(N-1, 0, 0), in the order of the table. The point qN−1(L,L+1)+rN−1(L,U)+pN−1(U−1,U)\frac{q}{N-1}(L, L+1) + \frac{r}{N-1}(L, U) + \frac{p}{N-1}(U-1, U) has the same pp, qq, rr as (x,y)(x, y), because pp, qq, rr are affine functions and the weights sum to 11. Two points with the same pp and qq are equal, so this is (x,y)(x, y).
  • d=>d = {>}. Swap the roles of xx and yy in the previous case. □\square

Lemma 2 (a linear function on a convex hull)

Let VV be a finite set of points and φ\varphi a linear function (plus a constant). On the set of convex combinations of VV, the minimum of φ\varphi is min⁡v∈Vφ(v)\min_{v \in V} \varphi(v) and the maximum is max⁡v∈Vφ(v)\max_{v \in V} \varphi(v).

Proof. For p=∑vλvvp = \sum_v \lambda_v v with λv≥0\lambda_v \ge 0 and ∑vλv=1\sum_v \lambda_v = 1, φ(p)=∑vλvφ(v)\varphi(p) = \sum_v \lambda_v \varphi(v), a weighted mean of the values at the vertices. A weighted mean lies between the smallest and the largest of the values. Both are reached, at the vertices themselves. □\square

Lemma 3 (the closed forms)

For each level and each direction with a nonempty region, the pair (lol,hil)(lo_l, hi_l) returned by level_bounds equals the minimum and the maximum of φ(x,y)=ax−by\varphi(x, y) = a x - b y over Rl(d)R_l(d).

Proof. By Lemmas 1 and 2 it is enough to compute the extremes of φ\varphi over Vl(d)V_l(d).

  • d=∗d = *. The term axa x over x∈{L,U}x \in \{L, U\} has the minimum aLaL if a≥0a \ge 0 and aUaU if a<0a < 0, which is a+L−a−Ua^+ L - a^- U in both cases, and the maximum a+U−a−La^+ U - a^- L. The term −by-b y over y∈{L,U}y \in \{L, U\} has the minimum −(b+U−b−L)-(b^+ U - b^- L) and the maximum −(b+L−b−U)-(b^+ L - b^- U). The four vertices are all combinations of xx and yy in {L,U}\{L, U\}, so the two terms reach their extremes on their own. The sums are the bounds of line L10.
  • d==d = {=}. On (L,L)(L, L) and (U,U)(U, U), φ=(a−b)x\varphi = (a - b) x, with extremes (a−b)+L−(a−b)−U(a-b)^+ L - (a-b)^- U and (a−b)+U−(a−b)−L(a-b)^+ U - (a-b)^- L, as in line L11.
  • d=<d = {<}. Let v0=φ(L,L+1)=(a−b)L−bv_0 = \varphi(L, L+1) = (a - b) L - b. Direct computation gives φ(L,U)=v0−b(N−1)\varphi(L, U) = v_0 - b(N - 1) and φ(U−1,U)=v0+(a−b)(N−1)\varphi(U-1, U) = v_0 + (a - b)(N - 1). As N−1≥0N - 1 \ge 0, the minimum is v0−(N−1)max⁡(0,b,b−a)=v0−(N−1)(a−+b)+v_0 - (N-1)\max(0, b, b - a) = v_0 - (N-1)(a^- + b)^+, and the maximum is v0+(N−1)max⁡(0,−b,a−b)=v0+(N−1)(a+−b)+v_0 + (N-1)\max(0, -b, a - b) = v_0 + (N-1)(a^+ - b)^+. Here max⁡(b,b−a)=b+a−\max(b, b - a) = b + a^- and max⁡(−b,a−b)=a+−b\max(-b, a - b) = a^+ - b. These are the bounds of line L12.
  • d=>d = {>}. Let v0=φ(L+1,L)=(a−b)L+av_0 = \varphi(L+1, L) = (a - b) L + a. Then φ(U,L)=v0+a(N−1)\varphi(U, L) = v_0 + a(N-1) and φ(U,U−1)=v0+(a−b)(N−1)\varphi(U, U-1) = v_0 + (a - b)(N - 1). The minimum is v0−(N−1)max⁡(0,−a,b−a)=v0−(N−1)(b+−a)+v_0 - (N-1)\max(0, -a, b - a) = v_0 - (N-1)(b^+ - a)^+ and the maximum is v0+(N−1)max⁡(0,a,a−b)=v0+(N−1)(a+b−)+v_0 + (N-1)\max(0, a, a - b) = v_0 + (N-1)(a + b^-)^+, as in line L13. □\square

Theorem 1 (the Banerjee bounds)

Let ψ⃗\vec{\psi} be a direction vector whose regions are all nonempty, and let lo=∑llollo = \sum_l lo_l and hi=∑lhilhi = \sum_l hi_l as computed in line L7. Then

lo=min⁡R(ψ⃗)h,hi=max⁡R(ψ⃗)h,lo = \min_{R(\vec{\psi})} h, \qquad hi = \max_{R(\vec{\psi})} h,

and every value between lolo and hihi is taken by hh on R(ψ⃗)R(\vec{\psi}).

Proof. The function is a sum h=∑lφl(xl,yl)h = \sum_l \varphi_l(x_l, y_l) in which the term φl\varphi_l depends only on the pair of level ll, and the region is a product of the sets Rl(ψl)R_l(\psi_l). So a point of R(ψ⃗)R(\vec{\psi}) is any choice of one pair from each Rl(ψl)R_l(\psi_l), and each term can be made as small as possible on its own: min⁡h=∑lmin⁡φl=∑llol\min h = \sum_l \min \varphi_l = \sum_l lo_l by Lemma 3, and the same for the maximum. Both are reached: let pmin⁡p^{\min} be the point that takes, at each level, the vertex where φl\varphi_l is smallest, and pmax⁡p^{\max} the same with the largest.

For a value cc with lo≤c≤hilo \le c \le hi, put t=(c−lo)/(hi−lo)t = (c - lo)/(hi - lo) if hi>lohi > lo and t=0t = 0 otherwise, and p=pmin⁡+t(pmax⁡−pmin⁡)p = p^{\min} + t(p^{\max} - p^{\min}). Each level pair of pp is a convex combination of two points of the convex set Rl(ψl)R_l(\psi_l), so p∈R(ψ⃗)p \in R(\vec{\psi}). As hh is linear, h(p)=lo+t(hi−lo)=ch(p) = lo + t(hi - lo) = c. □\square

The function real_witness builds exactly this point pp, with rational coordinates, and the tests check that it lies in the region and solves the equation.

Theorem 2 (exact over the reals, for one subscript)

For one subscript pair and a direction vector ψ⃗\vec{\psi}, the test answers "maybe" if and only if the equation h=ch = c has a real solution in R(ψ⃗)R(\vec{\psi}).

Proof. If some region is empty, R(ψ⃗)R(\vec{\psi}) is empty, there is no solution, and line L6 answers "independent". Otherwise, by Theorem 1, the set of values of hh on R(ψ⃗)R(\vec{\psi}) is exactly the interval [lo,hi][lo, hi]. So a solution exists if and only if lo≤c≤hilo \le c \le hi, which is the negation of the condition of line L8. □\square

Theorem 3 (soundness)

If there are integer vectors i⃗\vec{i} and j⃗\vec{j} in the loop bounds with il ψl jli_l \,\psi_l\, j_l for all ll and with all mm subscript pairs equal, the test answers "maybe". So "independent" proves that there is no dependence with direction vector ψ⃗\vec{\psi}.

Proof. The point (i⃗,j⃗)(\vec{i}, \vec{j}) lies in R(ψ⃗)R(\vec{\psi}) (integer il<jli_l < j_l gives il+1≤jli_l + 1 \le j_l), and it solves the equation of each subscript. By Theorem 2 each subscript gives "maybe" in line L8, and no region is empty, so line L6 never fires. Line L9 answers "maybe". □\square

Theorem 4 (the direction search loses nothing)

The function direction_vectors returns a set that contains the direction vector of every integer solution in the bounds, and equals the set of plain vectors ψ⃗∈{<,=,>}k\vec{\psi} \in \{<, =, >\}^k for which the test says "maybe".

Proof. Each plain ψ⃗\vec{\psi} is reached from (∗,…,∗)(*, \dots, *) by replacing the first ∗* with a symbol, one level at a time, and the search follows this path unless the test says "independent" at a vector ψ⃗′\vec{\psi}' on it. Every vector on the path keeps the symbols of ψ⃗\vec{\psi} where it has symbols and has ∗* elsewhere, so R(ψ⃗)⊆R(ψ⃗′)R(\vec{\psi}) \subseteq R(\vec{\psi}'), because Rl(d)⊆Rl(∗)R_l(d) \subseteq R_l(*). A smaller set gives a smaller range of hh, so if cc is outside the range for ψ⃗′\vec{\psi}', it is outside for ψ⃗\vec{\psi}, and the test also says "independent" for ψ⃗\vec{\psi}. So the cut removes only vectors that the test rules out, and the leaves are exactly the plain vectors with "maybe". By Theorem 3, the direction vector of an integer solution gives "maybe", so it is in the set. □\square

An example where the test says "maybe" and there is no integer solution

Take A[2*i] = A[3*i + 2] + 1 for i=1,…,3i = 1, \dots, 3. The equation is 2x−3y=22x - 3y = 2 on 1≤x,y≤31 \le x, y \le 3, with a=2a = 2, b=3b = 3, L=1L = 1, U=3U = 3 and N=2N = 2.

  • For ∗*: lo=2⋅1−3⋅3=−7lo = 2 \cdot 1 - 3 \cdot 3 = -7 and hi=2⋅3−3⋅1=3hi = 2 \cdot 3 - 3 \cdot 1 = 3. The value 22 is inside, so the test says "maybe". The GCD test also says "maybe", since gcd⁡(2,3)=1\gcd(2, 3) = 1.
  • Refined: for <<, v0=−1−3=−4v_0 = -1 - 3 = -4, so the range is [−4−3,−4+0]=[−7,−4][-4 - 3, -4 + 0] = [-7, -4]; for ==, a−b=−1a - b = -1 and the range is [−3,−1][-3, -1]; for >>, v0=−1+2=1v_0 = -1 + 2 = 1, and the range is [1−1,1+2]=[0,3][1 - 1, 1 + 2] = [0, 3]. Only >> stays "maybe". A real witness is (x,y)=(2.5,1)(x, y) = (2.5, 1): it has y+1≤xy + 1 \le x, and 2⋅2.5−3⋅1=22 \cdot 2.5 - 3 \cdot 1 = 2.
  • There is no integer solution in the bounds: 2x=3y+22x = 3y + 2 forces yy to be even, so y=2y = 2 and x=4>3x = 4 > 3. The written elements are A[2],A[4],A[6]A[2], A[4], A[6] and the read elements are A[5],A[8],A[11]A[5], A[8], A[11].

So Theorem 2 is the best the test can do: it is exact over the reals, and the gap between real and integer solutions is where it says "maybe" with no dependence.

Cost

level_bounds takes O(1)O(1) arithmetic operations, so one subscript and one direction vector cost O(k)O(k), and the test of mm subscripts costs O(mk)O(mk). The direction search visits at most 1+3+⋯+3k<323k1 + 3 + \dots + 3^k < \tfrac{3}{2} 3^k vectors, so it costs O(3kmk)O(3^k m k) in the worst case.

Complexity

One call of LEVEL-BOUNDS costs O(1)O(1) operations, so a direction vector costs O(k)O(k) per subscript and O(mk)O(mk) for the reference. The search tests at most 1+3+⋯+3k1 + 3 + \dots + 3^k vectors, so O(3kmk)O(3^k m k) time in the worst case, with a recursion stack of depth kk. In practice most branches are cut near the root, and nests are shallow. The test needs O(1)O(1) extra space for one direction vector.

Properties

  • Conservative in one direction only. "Independent" is a proof; "maybe" is not a proof of dependence.
  • Exact over the reals. For one subscript and a rectangular region, "maybe" holds exactly when a real solution exists (Theorem 2 of the proof).
  • Not exact over the integers. It ignores divisibility, which the GCD test checks; the two are often run together on the same equation.
  • One subscript at a time. Like the GCD test, it does not join the equations of a multidimensional reference.
  • Direction aware. It is the classic test for computing direction vectors, because each direction has its own closed form.

Variants and improvements

  • Trapezoidal bounds. Banerjee's book extends the bounds to loops whose bounds are affine in outer indices, such as triangular loops. The closed forms then include the coefficients of the bounds.
  • Combined GCD and Banerjee test. Run the GCD test first on the equation for each direction vector; it is cheap and catches divisibility that the real bounds miss.
  • Exact tests for simple subscripts. For subscripts with one index, the exact SIV tests of the practical tests replace the Banerjee test, and the Banerjee test is kept for the remaining MIV subscripts.
  • Real elimination of the whole system. Fourier-Motzkin elimination decides real feasibility of all subscripts and bounds together, which catches coupled subscripts; the omega test makes it exact over the integers.
  • Symbolic bounds. When a bound is a parameter nn, the extremes are affine functions of nn, and the test asks whether cc can lie between them for some nn.

When to use it

Use it for subscripts with several loop indices in a nest with known bounds, after the exact tests for single-index subscripts, and use the hierarchical search when the transformations need direction vectors (interchange, parallelization, vectorization). For exact answers, or for coupled subscripts that matter, use the omega test or a polyhedral library.

Pitfalls

  • Using x<yx < y over the reals. The strict real triangle x<yx < y has the same closure as x≤yx \le y and gives wider bounds. The test must use x+1≤yx + 1 \le y, which is valid for integers and gives the closed forms above.
  • Forgetting empty regions. For a loop with one iteration (U=LU = L), the directions << and >> have no pairs; the test must answer "independent" for them, not compute bounds from a formula with N−1=−1N - 1 = -1.
  • Reading "maybe" as "dependent". The example A[2*i] = A[3*i + 2] shows a "maybe" without a dependence.
  • Mixing up the notation. On this page << means that the sink index is larger. In the plus-zero-minus notation of the dragon book the same direction is written ++.
  • A direction vector with >> first. A leaf such as (>,<)(>, <) is not a dependence from the source to the sink. It is a dependence from the sink to the source, and its direction is the reversed vector.

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.

banerjee_bounds.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/banerjee-test/. The authors are listed in prov/PS0MQH.jsonl.
"""The Banerjee test with direction vectors, for rectangular loop nests.

A loop nest has depth k, and loop l runs over the integers L_l..U_l, given as
bounds = [(L_1, U_1), ..., (L_k, U_k)]. A subscript is a tuple
(c0, c1, ..., ck) for c0 + c1*i1 + ... + ck*ik. The source reference uses
the indices i and the sink reference the indices j; a reference to an array
of m dimensions is a list of m subscripts.

The direction psi_l relates i_l and j_l: "<" is i_l < j_l, "=" is i_l = j_l,
">" is i_l > j_l and "*" is no constraint (Wolfe's notation).

banerjee_test returns "independent" when, for some subscript, the equation
sum(a_l i_l) - sum(b_l j_l) = b0 - a0 has no real solution in the region of
the bounds and the directions, and "maybe" otherwise.
"""

from fractions import Fraction


def pos(x: int) -> int:
    """The positive part x+ = max(x, 0)."""
    return x if x > 0 else 0


def neg(x: int) -> int:
    """The negative part x- = max(-x, 0); x = x+ - x-."""
    return -x if x < 0 else 0


def level_bounds(a: int, b: int, lo: int, hi: int, d: str):
    """Min and max of a*x - b*y over the real region of one level, or None.

    The region is lo <= x, y <= hi with x = y for "=", x + 1 <= y for "<",
    y + 1 <= x for ">" and no relation for "*". It is empty for "<" and ">"
    when hi - lo < 1.
    """
    n = hi - lo
    if d == "*":
        return (pos(a) * lo - neg(a) * hi - pos(b) * hi + neg(b) * lo,  # @line L10
                pos(a) * hi - neg(a) * lo - pos(b) * lo + neg(b) * hi)
    if d == "=":
        c = a - b
        return (pos(c) * lo - neg(c) * hi, pos(c) * hi - neg(c) * lo)  # @line L11
    if n < 1:
        return None
    if d == "<":
        v0 = (a - b) * lo - b
        return (v0 - pos(neg(a) + b) * (n - 1), v0 + pos(pos(a) - b) * (n - 1))  # @line L12
    v0 = (a - b) * lo + a
    return (v0 - pos(pos(b) - a) * (n - 1), v0 + pos(a + neg(b)) * (n - 1))  # @line L13


def subscript_bounds(src, snk, bounds, psi=None):
    """Min and max of the left side of the dependence equation, or None."""
    lo_sum, hi_sum = 0, 0  # @line L3
    for l, (lo, hi) in enumerate(bounds):  # @line L4
        d = "*" if psi is None else psi[l]
        r = level_bounds(src[l + 1], snk[l + 1], lo, hi, d)  # @line L5
        if r is None:
            return None  # @line L6
        lo_sum += r[0]  # @line L7
        hi_sum += r[1]
    return lo_sum, hi_sum


def banerjee_test(src, snk, bounds, psi=None) -> str:
    """The Banerjee test for two references and an optional direction vector."""
    for f, g in zip(src, snk):  # @line L1
        c = g[0] - f[0]  # @line L2
        r = subscript_bounds(f, g, bounds, psi)
        if r is None or c < r[0] or c > r[1]:  # @line L8
            return "independent"
    return "maybe"  # @line L9


def direction_vectors(src, snk, bounds) -> set:
    """All plain direction vectors that the Banerjee test does not rule out.

    The search refines one "*" at a time, from the outermost level, and cuts
    a branch as soon as the test says "independent".
    """
    k = len(bounds)
    out = set()

    def refine(psi: tuple) -> None:
        if banerjee_test(src, snk, bounds, psi) == "independent":
            return
        if "*" not in psi:
            out.add(psi)
            return
        l = psi.index("*")
        for d in "<=>":
            refine(psi[:l] + (d,) + psi[l + 1:])

    refine(("*",) * k)
    return out


def level_vertices(lo: int, hi: int, d: str) -> list:
    """The vertices of the real region of one level, as (x, y) pairs."""
    if d == "*":
        return [(lo, lo), (lo, hi), (hi, lo), (hi, hi)]
    if d == "=":
        return [(lo, lo), (hi, hi)]
    if hi - lo < 1:
        return []
    if d == "<":
        return [(lo, lo + 1), (lo, hi), (hi - 1, hi)]
    return [(lo + 1, lo), (hi, lo), (hi, hi - 1)]


def real_witness(src, snk, bounds, psi=None):
    """A real solution (x, y) of one subscript equation in the region, or None.

    It joins the vertex that gives the minimum with the vertex that gives the
    maximum at each level; the segment between the two points stays in the
    region, and the left side runs over [lo, hi] along it.
    """
    k = len(bounds)
    c = snk[0] - src[0]
    pmin, pmax = [], []
    for l, (lo, hi) in enumerate(bounds):
        d = "*" if psi is None else psi[l]
        vs = level_vertices(lo, hi, d)
        if not vs:
            return None
        val = lambda p: src[l + 1] * p[0] - snk[l + 1] * p[1]  # noqa: E731
        pmin.append(min(vs, key=val))
        pmax.append(max(vs, key=val))
    left = lambda ps: sum(src[l + 1] * ps[l][0] - snk[l + 1] * ps[l][1] for l in range(k))  # noqa: E731
    lo_v, hi_v = left(pmin), left(pmax)
    if c < lo_v or c > hi_v:
        return None
    t = Fraction(0) if hi_v == lo_v else Fraction(c - lo_v, hi_v - lo_v)
    x = [pmin[l][0] + t * (pmax[l][0] - pmin[l][0]) for l in range(k)]
    y = [pmin[l][1] + t * (pmax[l][1] - pmin[l][1]) for l in range(k)]
    return x, y


if __name__ == "__main__":
    # for i = 1 to 5: A[i] = A[i + 10]: the range of i - j is [-4, 4].
    print(banerjee_test([(0, 1)], [(10, 1)], [(1, 5)]))  # independent
    # for i = 1 to 3: A[2*i] = A[3*i + 2]: maybe, only with ">".
    print(banerjee_test([(0, 2)], [(2, 3)], [(1, 3)]))  # maybe
    print(sorted(direction_vectors([(0, 2)], [(2, 3)], [(1, 3)])))  # [('>',)]
banerjee_test.py 22 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/banerjee-test/. The authors are listed in prov/PS0MQH.jsonl.
"""Entry point named after the slug. The code is in banerjee_bounds.py,
because the tools treat a file whose name ends in _test as a test file."""

from banerjee_bounds import (
    banerjee_test,
    direction_vectors,
    level_bounds,
    level_vertices,
    real_witness,
    subscript_bounds,
)

__all__ = [
    "banerjee_test",
    "direction_vectors",
    "level_bounds",
    "level_vertices",
    "real_witness",
    "subscript_bounds",
]
test_banerjee_test.py 205 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/banerjee-test/. The authors are listed in prov/PS0MQH.jsonl.

import random
from fractions import Fraction
from itertools import product

from banerjee_test import (
    banerjee_test,
    direction_vectors,
    level_bounds,
    level_vertices,
    real_witness,
    subscript_bounds,
)

DIRS = "<=>*"


def holds(rel, a, b) -> bool:
    return rel == "*" or (rel == "<" and a < b) or (rel == "=" and a == b) or (rel == ">" and a > b)


def sign(a, b) -> str:
    return "<" if a < b else ("=" if a == b else ">")


def value(sub, x):
    return sub[0] + sum(c * v for c, v in zip(sub[1:], x))


def box(bounds):
    return list(product(*[range(lo, hi + 1) for lo, hi in bounds]))


def brute_pairs(src, snk, bounds, psi=None):
    """All integer pairs (i, j) in the box with equal subscripts and directions psi."""
    pts = box(bounds)
    out = []
    for i in pts:
        for j in pts:
            if psi is not None and not all(holds(r, a, b) for r, a, b in zip(psi, i, j)):
                continue
            if all(value(f, i) == value(g, j) for f, g in zip(src, snk)):
                out.append((i, j))
    return out


def random_bounds(rng, k):
    top = {1: 8, 2: 6, 3: 4}[k]
    out = []
    for _ in range(k):
        lo = rng.randint(0, 2)
        out.append((lo, rng.randint(lo, top)))
    return out


def random_case(rng):
    k = rng.randint(1, 3)
    bounds = random_bounds(rng, k)
    m = rng.randint(1, 2)
    src, snk = [], []
    for _ in range(m):
        f = [rng.randint(-6, 6)] + [rng.randint(-4, 4) for _ in range(k)]
        g = [rng.randint(-6, 6)] + [rng.randint(-4, 4) for _ in range(k)]
        if rng.random() < 0.5:
            i = [rng.randint(lo, hi) for lo, hi in bounds]
            j = [rng.randint(lo, hi) for lo, hi in bounds]
            g[0] += value(f, i) - value(g, j)
        src.append(tuple(f))
        snk.append(tuple(g))
    psi = None if rng.random() < 0.3 else tuple(rng.choice(DIRS) for _ in range(k))
    return src, snk, bounds, psi


def in_region(x, y, bounds, psi):
    for l, (lo, hi) in enumerate(bounds):
        d = "*" if psi is None else psi[l]
        if not (lo <= x[l] <= hi and lo <= y[l] <= hi):
            return False
        if d == "<" and not x[l] + 1 <= y[l]:
            return False
        if d == ">" and not y[l] + 1 <= x[l]:
            return False
        if d == "=" and x[l] != y[l]:
            return False
    return True


def test_level_bounds_are_the_extremes_over_integer_points():
    # The vertices of each region are integer points, so the closed forms
    # must equal the min and max of a*x - b*y over the integer points.
    for a in range(-5, 6):
        for b in range(-5, 6):
            for lo in range(0, 3):
                for hi in range(lo, 8):
                    for d in DIRS:
                        pts = [(x, y) for x in range(lo, hi + 1) for y in range(lo, hi + 1) if holds(d, x, y)]
                        r = level_bounds(a, b, lo, hi, d)
                        if not pts:
                            assert r is None
                            assert level_vertices(lo, hi, d) == []
                            continue
                        vals = [a * x - b * y for x, y in pts]
                        assert r == (min(vals), max(vals)), (a, b, lo, hi, d)
                        vs = level_vertices(lo, hi, d)
                        assert all(p in pts for p in vs)
                        assert min(a * x - b * y for x, y in vs) == r[0]
                        assert max(a * x - b * y for x, y in vs) == r[1]


def test_subscript_bounds_over_the_whole_box():
    rng = random.Random(11)
    for _ in range(400):
        k = rng.randint(1, 3)
        bounds = random_bounds(rng, k)
        f = tuple(rng.randint(-5, 5) for _ in range(k + 1))
        g = tuple(rng.randint(-5, 5) for _ in range(k + 1))
        psi = tuple(rng.choice(DIRS) for _ in range(k))
        r = subscript_bounds(f, g, bounds, psi)
        vals = [
            sum(f[l + 1] * i[l] - g[l + 1] * j[l] for l in range(k))
            for i in box(bounds)
            for j in box(bounds)
            if all(holds(d, a, b) for d, a, b in zip(psi, i, j))
        ]
        if not vals:
            assert r is None
        else:
            assert r == (min(vals), max(vals))


def test_never_independent_when_dependent():
    rng = random.Random(12)
    dependent = 0
    for _ in range(1500):
        src, snk, bounds, psi = random_case(rng)
        sols = brute_pairs(src, snk, bounds, psi)
        answer = banerjee_test(src, snk, bounds, psi)
        if sols:
            dependent += 1
            assert answer == "maybe", (src, snk, bounds, psi, sols[0])
    assert dependent > 300


def test_exact_over_the_reals_for_one_subscript():
    # "maybe" comes with a real witness in the region; "independent" means
    # that c is outside [lo, hi], the exact range of the left side.
    rng = random.Random(13)
    maybes = 0
    for _ in range(3000):
        k = rng.randint(1, 3)
        bounds = random_bounds(rng, k)
        f = tuple(rng.randint(-7, 7) for _ in range(k + 1))
        g = tuple(rng.randint(-7, 7) for _ in range(k + 1))
        psi = tuple(rng.choice(DIRS) for _ in range(k))
        answer = banerjee_test([f], [g], bounds, psi)
        w = real_witness(f, g, bounds, psi)
        assert (w is not None) == (answer == "maybe")
        if w is None:
            continue
        maybes += 1
        x, y = w
        assert all(isinstance(v, (int, Fraction)) for v in x + y)
        assert in_region(x, y, bounds, psi)
        assert value(f, x) == value(g, y)
    assert maybes > 500


def test_direction_vectors_contain_every_true_direction():
    rng = random.Random(14)
    for _ in range(600):
        src, snk, bounds, _ = random_case(rng)
        k = len(bounds)
        found = direction_vectors(src, snk, bounds)
        true = {tuple(sign(a, b) for a, b in zip(i, j)) for i, j in brute_pairs(src, snk, bounds)}
        assert true <= found
        # The pruned search loses nothing against testing every plain vector.
        every = {p for p in product("<=>", repeat=k) if banerjee_test(src, snk, bounds, p) == "maybe"}
        assert found == every


def test_page_examples():
    # A[i] = A[i + 10] for i = 1..5: gcd 1, but i - j lies in [-4, 4].
    assert banerjee_test([(0, 1)], [(10, 1)], [(1, 5)]) == "independent"
    # A[2*i] = A[3*i + 2] for i = 1..3: real range [-7, 3] holds 2.
    assert subscript_bounds((0, 2), (2, 3), [(1, 3)]) == (-7, 3)
    assert banerjee_test([(0, 2)], [(2, 3)], [(1, 3)]) == "maybe"
    assert level_bounds(2, 3, 1, 3, "<") == (-7, -4)
    assert level_bounds(2, 3, 1, 3, "=") == (-3, -1)
    assert level_bounds(2, 3, 1, 3, ">") == (0, 3)
    assert direction_vectors([(0, 2)], [(2, 3)], [(1, 3)]) == {(">",)}
    assert brute_pairs([(0, 2)], [(2, 3)], [(1, 3)]) == []
    x, y = real_witness((0, 2), (2, 3), [(1, 3)], (">",))
    assert 2 * x[0] == 3 * y[0] + 2 and y[0] + 1 <= x[0]
    # X[i + 2*j] = X[i + 2*j - 1] in a 1..4 by 1..4 nest (page example).
    src, snk, bounds = [(0, 1, 2)], [(-1, 1, 2)], [(1, 4), (1, 4)]
    assert subscript_bounds(src[0], snk[0], bounds, ("=", "*")) == (-6, 6)
    assert subscript_bounds(src[0], snk[0], bounds, ("=", "<")) == (-6, -2)
    assert subscript_bounds(src[0], snk[0], bounds, ("=", "=")) == (0, 0)
    assert subscript_bounds(src[0], snk[0], bounds, ("=", ">")) == (2, 6)
    assert subscript_bounds(src[0], snk[0], bounds, ("<", ">")) == (-1, 5)
    found = direction_vectors(src, snk, bounds)
    true = {tuple(sign(a, b) for a, b in zip(i, j)) for i, j in brute_pairs(src, snk, bounds)}
    assert found == true == {("<", "="), ("<", ">"), (">", "<")}

History

Utpal Banerjee developed the bounds test at the University of Illinois in the second half of the 1970s, in David Kuck's group, for the Parafrase parallelizing compiler. The form with direction vectors, where each level has its own bounds for <<, == and >>, was worked out in the 1980s and is the form in Wolfe's book and in Allen and Kennedy's book, which also give the hierarchical search. Banerjee's 1988 book collects the tests with their proofs, including the bounds for trapezoidal loops.

References

  1. Utpal Banerjee, Dependence Analysis for Supercomputing, Kluwer Academic Publishers, 1988, the bounds of a linear function over a rectangle with direction constraints, and the test built on them
  2. Randy Allen and Ken Kennedy, Optimizing Compilers for Modern Architectures, a Dependence-Based Approach, Morgan Kaufmann, 2002 (copyright 2001), Chapter 3 (the Banerjee inequality with direction vectors, the positive and negative parts, and the hierarchical search for direction vectors)
  3. Michael Wolfe, High Performance Compilers for Parallel Computing, Addison-Wesley, 1996, the chapter on dependence testing (the Banerjee bounds for each direction, and the search over the direction vector hierarchy)
  4. Gina Goff, Ken Kennedy and Chau-Wen Tseng, Practical dependence testing, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI), 1991, the Banerjee test as the general test for MIV subscripts, used after the exact single-index tests

Where this leads

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.best
  • 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