Algorithm Search⌘K

Algorithmcore

GCD test

Also called greatest common divisor dependence test.

Reports independence when the gcd of the coefficients of a linear subscript equation does not divide its constant term.

Time
O(m k log C) worstO(k) best
Space
O(1) extra
Where
C = the largest absolute value of a coefficient; k = the depth of the loop nest; m = the number of subscripts
Properties
deterministiciterative

The GCD test is the oldest and cheapest dependence test. Two references to an array, such as A[2*i] and A[2*i + 1], touch the same element only if a linear equation in the loop indices has an integer solution. By Bezout's identity, such an equation has an integer solution exactly when the gcd of its coefficients divides its constant term. The GCD test checks this one condition for each subscript. If it fails for some subscript, the references are independent. If it holds, the test says "maybe": it ignores the loop bounds, so a solution may exist only outside the iteration space.

In plain words

Write the condition "both references touch the same element" as an equation. The unknowns are the loop indices of the two accesses, and they must be whole numbers. Every combination of the unknowns gives a multiple of the greatest common divisor of their coefficients, and no other values. So if the constant of the equation is not such a multiple, the equation has no whole-number solution at all, and the two references never meet. If the constant is a multiple, there is a solution somewhere, but maybe not inside the loops. The test then cannot rule the dependence out and says "maybe". It is cheap, it never answers wrongly in the safe direction, and it catches the classic case of even against odd positions.

The problem

A loop nest of depth kk has two references to an array of mm dimensions. Dimension rr of the source has the subscript ar0+∑larlila_{r0} + \sum_l a_{rl} i_l, and the sink has br0+∑lbrljlb_{r0} + \sum_l b_{rl} j_l, with integer coefficients. A direction vector ψ⃗∈{<,=,>,∗}k\vec{\psi} \in \{<, =, >, *\}^k may restrict the pairs (this page uses Wolfe's notation: << at level ll means il<jli_l < j_l, see direction vector). The question is whether there are integer vectors i⃗\vec{i}, j⃗\vec{j} in the loop bounds with

∑l=1karlil−∑l=1kbrljl=br0−ar0(r=1,…,m)\sum_{l=1}^{k} a_{rl} i_l - \sum_{l=1}^{k} b_{rl} j_l = b_{r0} - a_{r0} \quad (r = 1, \dots, m)

and il ψl jli_l \,\psi_l\, j_l for each ll. The GCD test answers "independent" or "maybe". It must never answer "independent" when such vectors exist.

The algorithm

Let EE be the set of levels with ψl\psi_l equal to "=". At such a level the two indices are one variable, with coefficient al−bla_l - b_l.

  1. GCD-TEST-SUBSCRIPT(a, b, psi):
  2. 1c <- b_0 - a_0
  3. 2g <- 0
  4. 3for l <- 1 to k do
  5. 4if psi_l = "=" then g <- gcd(g, a_l - b_l)
  6. 5else g <- gcd(g, a_l, b_l)
  7. 6if g = 0 then return ("maybe" if c = 0 else "independent")
  8. 7if c mod g != 0 then return "independent"
  9. 8return "maybe"
  10. GCD-TEST(src, snk, psi):
  11. 9for each dimension r do
  12. 10if GCD-TEST-SUBSCRIPT(src_r, snk_r, psi) = "independent" then return "independent"
  13. 11return "maybe"

Line L6 handles a subscript pair that uses no index at all (a ZIV pair): the two subscripts are equal for all iterations or for none. The entries <<, >> and ∗* are treated alike, because the gcd cannot use them (see Correctness).

A witness is easy to get when the answer is "maybe": the extended Euclidean algorithm, run over the coefficients one at a time, gives integers with ∑vαvxv=G\sum_v \alpha_v x_v = G, and multiplying by c/Gc / G solves the equation. The implementation returns it from solve_linear.

Example

for i = 1 to 10:
  for j = 1 to 10:
    A[3*i + 2*j] = A[i + 4*j + 1] + 1

The equation between the write in (i,j)(i, j) and the read in (i′,j′)(i', j') is 3i+2j−i′−4j′=13i + 2j - i' - 4j' = 1.

With ψ⃗=(∗,∗)\vec{\psi} = (*, *). The gcd of 3,2,1,43, 2, 1, 4 is 11, which divides 11. The answer is "maybe". The witness from the extended Euclidean algorithm is (i,j,i′,j′)=(0,0,−1,0)(i, j, i', j') = (0, 0, -1, 0), outside the bounds, but there are also solutions inside, such as (1,2,2,1)(1, 2, 2, 1): S(1,2)S(1, 2) writes A[7]A[7] and S(2,1)S(2, 1) reads A[7]A[7].

With ψ⃗=(=,∗)\vec{\psi} = (=, *). Now i=i′i = i', and the trace is:

line action gg
L1 c=1−0c = 1 - 0
L2 00
L4, l=1l = 1 ψ1\psi_1 is "=": add a1−b1=3−1=2a_1 - b_1 = 3 - 1 = 2 22
L5, l=2l = 2 add a2=2a_2 = 2 and b2=4b_2 = 4 22
L7 1 mod 2=11 \bmod 2 = 1 independent

So no dependence has "=" at the outer level: every dependence of this loop is carried by the ii loop, and the jj loop can run in parallel for each ii. Enumeration of the box confirms it: the 236 solutions have the direction vectors (<,∗)(<, *) and (>,∗)(>, *) only, never (=,∗)(=, *).

A case the test cannot decide. For A[2*i] = A[3*i + 2] with 1≤i≤31 \le i \le 3, the gcd of 22 and 33 is 11, and the answer is "maybe". But 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], so there is no dependence. The Banerjee test also fails here; the exact SIV test of the practical tests succeeds.

Correctness

The full proof is in proofs/correctness.md. It has two parts.

Exactness without bounds. By Bezout's identity for nn variables, the values of ∑vαvxv\sum_v \alpha_v x_v over integer vectors x⃗\vec{x} are exactly the multiples of G=gcd⁡(α1,…,αn)G = \gcd(\alpha_1, \dots, \alpha_n). After the substitution il=jli_l = j_l for l∈El \in E, the equation of one subscript has the coefficients al−bla_l - b_l for l∈El \in E and al,−bla_l, -b_l for the other levels, and lines L2 to L5 compute their gcd. So the test answers "maybe" for a subscript exactly when its equation, with the "=" entries and nothing else, has an integer solution.

Soundness. A real dependence in the bounds with direction ψ⃗\vec{\psi} solves this relaxed equation for every subscript. So every subscript gives "maybe", and so does the whole test. The answer "independent" is a proof of independence.

Why << and >> do not help. Writing jl=il+δlj_l = i_l + \delta_l with δl≥1\delta_l \ge 1 gives the coefficients al−bla_l - b_l and blb_l, and gcd⁡(al−bl,bl)=gcd⁡(al,bl)\gcd(a_l - b_l, b_l) = \gcd(a_l, b_l). The gcd is the same, and the inequality δl≥1\delta_l \ge 1 is lost.

Proof: The GCD test is exact for one equation without bounds, and sound with boundsfull

We use the setting of the page. A subscript pair is f(i⃗)=a0+∑l=1kalilf(\vec{i}) = a_0 + \sum_{l=1}^{k} a_l i_l for the source and g(j⃗)=b0+∑l=1kbljlg(\vec{j}) = b_0 + \sum_{l=1}^{k} b_l j_l for the sink, with integer coefficients. The direction vector ψ⃗∈{<,=,>,∗}k\vec{\psi} \in \{<, =, >, *\}^k is optional; E={l:ψl==}E = \{l : \psi_l = {=}\} is the set of its "=" entries. The equation f(i⃗)=g(j⃗)f(\vec{i}) = g(\vec{j}) is

∑l=1kalil−∑l=1kbljl=c,c=b0−a0.(1)\sum_{l=1}^{k} a_l i_l - \sum_{l=1}^{k} b_l j_l = c, \qquad c = b_0 - a_0. \tag{1}

We take gcd⁡(0,0)=0\gcd(0, 0) = 0 and gcd⁡(x,0)=∣x∣\gcd(x, 0) = |x|, and the gcd of a list is the gcd of its entries taken one at a time. This gives the same value in any order, and gcd⁡(x,−y)=gcd⁡(x,y)\gcd(x, -y) = \gcd(x, y).

Lemma 1 (Bezout for nn variables)

Let α1,…,αn\alpha_1, \dots, \alpha_n be integers and G=gcd⁡(α1,…,αn)G = \gcd(\alpha_1, \dots, \alpha_n). Then the set I={∑vαvxv:x⃗∈Zn}I = \{\sum_v \alpha_v x_v : \vec{x} \in \mathbb{Z}^n\} is equal to GZ={Gt:t∈Z}G\mathbb{Z} = \{G t : t \in \mathbb{Z}\}. So the equation ∑vαvxv=c\sum_v \alpha_v x_v = c has an integer solution if and only if GG divides cc, where "00 divides cc" means c=0c = 0.

Proof. If all αv\alpha_v are 00, then I={0}I = \{0\} and G=0G = 0, so I=GZI = G\mathbb{Z}. Otherwise II has a positive element (take xv=±1x_v = \pm 1 for one nonzero αv\alpha_v and 00 elsewhere). Let dd be the smallest positive element of II. The set II is closed under sums and under multiplication by integers.

  • Every element of II is a multiple of dd. Take y∈Iy \in I and divide: y=qd+ry = q d + r with 0≤r<d0 \le r < d. Then r=y−qd∈Ir = y - q d \in I, and r<dr < d, so rr is not positive. So r=0r = 0.
  • d=Gd = G. Each αv\alpha_v is in II (take the unit vector), so dd divides each αv\alpha_v, and therefore dd divides GG. Also GG divides each αv\alpha_v, so GG divides each element ∑vαvxv\sum_v \alpha_v x_v of II, and in particular dd. Both are positive, so d=Gd = G.

So I⊆GZI \subseteq G\mathbb{Z} by the first point, and GZ⊆IG\mathbb{Z} \subseteq I because G=d∈IG = d \in I and II is closed under integer multiples. □\square

Lemma 2 (the witness)

ext_gcd(a, b) returns (g,x,y)(g, x, y) with ax+by=g=gcd⁡(a,b)a x + b y = g = \gcd(a, b), and solve_linear(coefs, c) returns an integer vector x⃗\vec{x} with ∑vαvxv=c\sum_v \alpha_v x_v = c when GG divides cc, and None otherwise.

Proof. In ext_gcd, let a∗a^* and b∗b^* be the inputs. The loop keeps a∗x0+b∗y0=aa^* x_0 + b^* y_0 = a and a∗x1+b∗y1=ba^* x_1 + b^* y_1 = b: at the start (x0,y0,x1,y1)=(1,0,0,1)(x_0, y_0, x_1, y_1) = (1, 0, 0, 1), and one step replaces (a,b)(a, b) with (b,a−qb)(b, a - q b) and the coefficient pairs in the same way. It also keeps gcd⁡(a,b)\gcd(a, b), since a common divisor of aa and bb divides a−qba - qb, and back. Python's divmod gives ∣a−qb∣<∣b∣|a - q b| < |b|, so ∣b∣|b| falls at each step and the loop ends with b=0b = 0. Then gcd⁡(a∗,b∗)=gcd⁡(a,0)=∣a∣\gcd(a^*, b^*) = \gcd(a, 0) = |a|, and the sign flip makes g≥0g \ge 0.

In solve_linear, after the step for index vv the vector satisfies ∑u≤vαuxu=g\sum_{u \le v} \alpha_u x_u = g with g=gcd⁡(α1,…,αv)g = \gcd(\alpha_1, \dots, \alpha_v) (the other entries are 00). Before the first step this holds with g=0g = 0 and x⃗=0⃗\vec{x} = \vec{0}. A step computes sg+tαv=h=gcd⁡(g,αv)s g + t \alpha_v = h = \gcd(g, \alpha_v), multiplies the old vector by ss, and sets xv=tx_v = t; the new sum is sg+tαv=hs g + t \alpha_v = h. At the end, g=Gg = G. If G=0G = 0, all coefficients are 00, and the zero vector solves the equation exactly when c=0c = 0. If G≠0G \ne 0 and GG divides cc, multiplying by c/Gc / G gives a solution. If GG does not divide cc, Lemma 1 says that there is none, and the function returns None. □\square

Theorem 1 (exactness of one subscript without bounds)

Let GG be the value of gg after lines L2 to L5 of gcd_test_subscript. Then the test answers "maybe" if and only if equation (1) has an integer solution (i⃗,j⃗)(\vec{i}, \vec{j}) with il=jli_l = j_l for all l∈El \in E, with no bounds and no other constraint.

Proof. Put il=jl=tli_l = j_l = t_l for l∈El \in E. Equation (1) with these equalities is the equation

∑l∈E(al−bl) tl+∑l∉E(alil+(−bl)jl)=c\sum_{l \in E} (a_l - b_l)\, t_l + \sum_{l \notin E} \bigl(a_l i_l + (-b_l) j_l\bigr) = c

in the free integer variables tlt_l (l∈El \in E), and il,jli_l, j_l (l∉El \notin E). Its solutions are exactly the solutions of (1) with the equalities. Lines L2 to L5 compute G=gcd⁡({al−bl:l∈E}∪{al,bl:l∉E})G = \gcd\bigl(\{a_l - b_l : l \in E\} \cup \{a_l, b_l : l \notin E\}\bigr): line L4 adds al−bla_l - b_l, line L5 adds ala_l and blb_l, and gcd⁡(⋅,bl)=gcd⁡(⋅,−bl)\gcd(\cdot, b_l) = \gcd(\cdot, -b_l). This is the gcd of the coefficients of the equation above. By Lemma 1 the equation has a solution if and only if GG divides cc. Lines L6 to L8 return "maybe" in exactly this case: for G=0G = 0 when c=0c = 0, and for G≠0G \ne 0 when c mod G=0c \bmod G = 0. □\square

Theorem 2 (soundness)

If two references have a dependence, that is, integer vectors i⃗\vec{i} and j⃗\vec{j} in the loop bounds that make all mm subscript pairs equal and satisfy il ψl jli_l \,\psi_l\, j_l for each ll, then gcd_test returns "maybe". Equivalently, the answer "independent" proves that there is no dependence with the direction vector ψ⃗\vec{\psi}.

Proof. Take such i⃗\vec{i} and j⃗\vec{j}, and one subscript pair. The pair satisfies equation (1) of that subscript, and il=jli_l = j_l for l∈El \in E because ψl\psi_l is "=". It is therefore a solution of the relaxed system of Theorem 1, which drops the bounds and the entries <<, >>, ∗*. By Theorem 1 the test of that subscript answers "maybe". This holds for every subscript, so the loop of lines L9 and L10 never returns, and line L11 returns "maybe". □\square

Why "<" and ">" are not used

The test could try to use ψl=<\psi_l = {<} by writing jl=il+δlj_l = i_l + \delta_l with δl≥1\delta_l \ge 1. The terms of level ll become (al−bl)il−blδl(a_l - b_l) i_l - b_l \delta_l, and gcd⁡(al−bl,bl)=gcd⁡(al,bl)\gcd(a_l - b_l, b_l) = \gcd(a_l, b_l), since a common divisor of two of ala_l, blb_l, al−bla_l - b_l divides the third. So the gcd does not change, and the constraint δl≥1\delta_l \ge 1 is an inequality, which Lemma 1 cannot see. The same holds for >>. This is why the code treats <<, >> and ∗* alike.

What the test does not decide

Theorem 1 is the only exactness the test has. With bounds, with the entries << and >>, or with several subscripts, "maybe" can be wrong:

  • A[2i]A[2i] against A[3j+2]A[3j + 2] with 1≤i,j≤31 \le i, j \le 3: gcd⁡(2,3)=1\gcd(2, 3) = 1 divides 22, but the solutions (1+3t,2t)(1 + 3t, 2t) all leave the box.
  • A[i]A[i] against A[j]A[j] with ψ=(<)\psi = (<): gcd⁡(1,1)=1\gcd(1, 1) = 1 divides 00, but i=ji = j is forced.
  • A[i][i]A[i][i] against A[j][j+1]A[j][j + 1]: each subscript alone has solutions, the two together have none.

In each case the answer "maybe" is still allowed by Theorem 2, which is the only promise the test makes with bounds.

Cost

Each call of gcd on numbers of absolute value at most CC takes O(log⁡C)O(\log C) division steps, and the running gcd never exceeds the largest coefficient. A subscript makes at most 2k2k calls, so the test of mm subscripts takes O(mklog⁡C)O(m k \log C) arithmetic operations and O(1)O(1) extra space. solve_linear takes O(n2+nlog⁡C)O(n^2 + n \log C) operations for nn variables, because it scales the vector once per variable.

Complexity

Each gcd of numbers at most CC in absolute value takes O(log⁡C)O(\log C) division steps, and a subscript needs at most 2k2k of them. The whole test takes O(mklog⁡C)O(m k \log C) time and O(1)O(1) extra space. A test that stops at the first independent subscript can end after O(k)O(k) steps when the gcds are small. A full search over direction vectors multiplies the cost by the number of vectors tested, at most 3k3^k and usually far fewer.

Properties

  • Conservative in one direction only. "Independent" is always right. "Maybe" can be wrong in the sense that no dependence exists.
  • Exact for one equation without bounds. For a single subscript and no bounds it decides the question.
  • Blind to bounds and to <<, >>. Only the "=" entries of a direction vector change the result.
  • One subscript at a time. It does not combine the subscripts of a multidimensional reference, so it misses independence that only the system shows.
  • Weak in practice. The gcd is often 11, for instance whenever some coefficient is ±1\pm 1, and then the test always says "maybe".

Variants and improvements

  • Generalized GCD test. Solve the whole system of mm equations at once over the integers, with the Hermite normal form or the Smith normal form. This decides integer solvability of the system without bounds, so it catches coupled subscripts such as A[i][i]A[i][i] against A[j][j+1]A[j][j + 1]. Banerjee's book gives this version.
  • Bounds after the gcd. The general solution of one equation, from the witness and the kernel, is a lattice of points; intersecting it with the bounds is the exact SIV test for two variables. See practical dependence tests.
  • Combined with Banerjee. Compilers run the GCD test and the Banerjee test on the same equation; each catches cases the other misses.
  • Exact integer tests. The omega test solves the full integer program, including bounds and directions.

When to use it

Use it as the first test on a subscript pair with several indices, before more costly tests: it costs a few gcds and catches stride patterns such as even against odd elements. Do not rely on it alone. With loop bounds known, a solution outside the bounds is common, and the test cannot see it. For single-index subscripts, the exact SIV tests are just as cheap and stronger.

Pitfalls

  • Answering "dependent" for "maybe". The test proves only independence. A "maybe" means that the compiler must assume a dependence, not that one exists.
  • Dropping a nonzero constant in a ZIV pair. If all coefficients are 00, the gcd is 00; the subscripts are equal only when the constants are equal. Treating gcd⁡=0\gcd = 0 as "divides everything" gives a wrong "maybe", which is safe, but treating it as "divides nothing" gives a wrong "independent" for A[5]A[5] against A[5]A[5], which is not safe.
  • Using the gcd of the "<" substitution as stronger. Substituting jl=il+δlj_l = i_l + \delta_l does not change the gcd; only "=" does.
  • Testing each subscript and concluding about the system. Each subscript of A[i][i]A[i][i] against A[j][j+1]A[j][j+1] passes, but the system has no solution. The test is still sound, just weak.
  • Symbolic terms. A subscript such as A[n*i] with unknown nn has no integer coefficient; the test must treat the term as unknown and answer "maybe", or test with nn as an extra variable.

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.

gcd_dependence.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gcd-test/. The authors are listed in prov/M4BM5N.jsonl.
"""The GCD dependence test.

A loop nest has depth k. A subscript is a tuple (c0, c1, ..., ck) for the
affine function c0 + c1*i1 + ... + ck*ik of the iteration vector. The source
reference uses the indices i, the sink reference uses the indices j, and a
reference to an array of m dimensions is a list of m subscripts.

gcd_test(src, snk, psi) returns "independent" when no integer vectors i, j
(with any values, the loop bounds are ignored) make all subscripts equal and
match the direction vector psi, and "maybe" otherwise. Only the "=" entries
of psi change the test; "<", ">" and "*" give the same answer as no entry.
"""

from math import gcd


def ext_gcd(a: int, b: int) -> tuple[int, int, int]:
    """Return (g, x, y) with a*x + b*y = g = gcd(a, b) and g >= 0."""
    x0, y0, x1, y1 = 1, 0, 0, 1
    while b != 0:
        q, r = divmod(a, b)
        a, b = b, r
        x0, x1 = x1, x0 - q * x1
        y0, y1 = y1, y0 - q * y1
    if a < 0:
        return -a, -x0, -y0
    return a, x0, y0


def equation(src: tuple[int, ...], snk: tuple[int, ...], psi=None) -> tuple[list[int], int]:
    """The dependence equation of one subscript pair, as (coefficients, c).

    The equation is sum(coef * var) = c over the variables i1, j1, ..., ik, jk,
    except that a level with psi "=" has one variable i_l = j_l.
    """
    k = len(src) - 1
    coefs: list[int] = []
    for l in range(1, k + 1):
        if psi is not None and psi[l - 1] == "=":
            coefs.append(src[l] - snk[l])
        else:
            coefs.append(src[l])
            coefs.append(-snk[l])
    return coefs, snk[0] - src[0]


def solve_linear(coefs: list[int], c: int):
    """Return an integer vector x with sum(coefs[v] * x[v]) == c, or None.

    The vector comes from the extended Euclidean algorithm. It exists exactly
    when gcd(coefs) divides c (with gcd of all zeros equal to 0).
    """
    n = len(coefs)
    g, x = 0, [0] * n  # invariant: sum(coefs[v] * x[v]) == g
    for v in range(n):
        h, s, t = ext_gcd(g, coefs[v])
        x = [s * xv for xv in x]
        x[v] = t
        g = h
    if g == 0:
        return [0] * n if c == 0 else None
    if c % g != 0:
        return None
    q = c // g
    return [q * xv for xv in x]


def gcd_test_subscript(src: tuple[int, ...], snk: tuple[int, ...], psi=None) -> str:
    """The GCD test for one subscript pair."""
    k = len(src) - 1
    c = snk[0] - src[0]  # @line L1
    g = 0  # @line L2
    for l in range(1, k + 1):  # @line L3
        if psi is not None and psi[l - 1] == "=":
            g = gcd(g, src[l] - snk[l])  # @line L4
        else:
            g = gcd(gcd(g, src[l]), snk[l])  # @line L5
    if g == 0:
        return "maybe" if c == 0 else "independent"  # @line L6
    if c % g != 0:
        return "independent"  # @line L7
    return "maybe"  # @line L8


def gcd_test(src: list[tuple[int, ...]], snk: list[tuple[int, ...]], psi=None) -> str:
    """The GCD test for two references, one subscript at a time."""
    for f, g in zip(src, snk):  # @line L9
        if gcd_test_subscript(f, g, psi) == "independent":  # @line L10
            return "independent"
    return "maybe"  # @line L11


if __name__ == "__main__":
    # for i = 1 to n: A[2*i] = A[2*i + 1]
    print(gcd_test([(0, 2)], [(1, 2)]))  # independent
    # for i, j: A[3*i + 2*j] = A[i + 4*j + 1]
    print(gcd_test([(0, 3, 2)], [(1, 1, 4)]))  # maybe
    # with psi = (=, *): gcd(3 - 1, 2, 4) = 2 does not divide 1
    print(gcd_test([(0, 3, 2)], [(1, 1, 4)], ("=", "*")))  # independent
gcd_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gcd-test/. The authors are listed in prov/M4BM5N.jsonl.
"""Entry point named after the slug. The code is in gcd_dependence.py,
because the tools treat a file whose name ends in _test as a test file."""

from gcd_dependence import equation, ext_gcd, gcd_test, gcd_test_subscript, solve_linear

__all__ = ["equation", "ext_gcd", "gcd_test", "gcd_test_subscript", "solve_linear"]
test_gcd_test.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gcd-test/. The authors are listed in prov/M4BM5N.jsonl.

import random
from itertools import product
from math import gcd

from gcd_test import equation, ext_gcd, gcd_test, gcd_test_subscript, solve_linear

DIRS = "<=>*"


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


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


def brute_solutions(src, snk, bounds, psi=None):
    """All pairs (i, j) in the box with equal subscripts and the directions psi."""
    box = list(product(*[range(lo, hi + 1) for lo, hi in bounds]))
    out = []
    for i in box:
        for j in box:
            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_case(rng: random.Random):
    k = rng.randint(1, 3)
    top = {1: 8, 2: 6, 3: 4}[k]
    bounds = []
    for _ in range(k):
        lo = rng.randint(0, 2)
        bounds.append((lo, rng.randint(lo, top)))
    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:
            # Make the subscript pair meet at one random pair of iterations.
            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 test_ext_gcd():
    rng = random.Random(1)
    for _ in range(2000):
        a, b = rng.randint(-60, 60), rng.randint(-60, 60)
        g, x, y = ext_gcd(a, b)
        assert g == gcd(a, b)
        assert a * x + b * y == g


def test_solve_linear_is_exact():
    rng = random.Random(2)
    for _ in range(3000):
        n = rng.randint(1, 6)
        coefs = [rng.choice([0, 0, rng.randint(-9, 9)]) for _ in range(n)]
        c = rng.randint(-30, 30)
        g = 0
        for a in coefs:
            g = gcd(g, a)
        x = solve_linear(coefs, c)
        solvable = (c == 0) if g == 0 else (c % g == 0)
        if solvable:
            assert x is not None
            assert sum(a * v for a, v in zip(coefs, x)) == c
        else:
            assert x is None


def test_never_independent_when_dependent():
    rng = random.Random(3)
    dependent_cases = 0
    for _ in range(1500):
        src, snk, bounds, psi = random_case(rng)
        sols = brute_solutions(src, snk, bounds, psi)
        answer = gcd_test(src, snk, psi)
        assert answer in ("independent", "maybe")
        if sols:
            dependent_cases += 1
            assert answer == "maybe", (src, snk, bounds, psi, sols[0])
    assert dependent_cases > 300


def test_exact_for_one_subscript_without_bounds():
    # For one subscript, "maybe" means an integer solution exists when the
    # bounds and the "<" and ">" entries are dropped; the witness proves it.
    rng = random.Random(4)
    for _ in range(3000):
        k = rng.randint(1, 4)
        f = tuple([rng.randint(-9, 9)] + [rng.randint(-5, 5) for _ in range(k)])
        g = tuple([rng.randint(-9, 9)] + [rng.randint(-5, 5) for _ in range(k)])
        psi = tuple(rng.choice(DIRS) for _ in range(k))
        coefs, c = equation(f, g, psi)
        x = solve_linear(coefs, c)
        answer = gcd_test_subscript(f, g, psi)
        assert (x is not None) == (answer == "maybe")
        if x is None:
            continue
        i, j, pos = [], [], 0
        for l in range(k):
            if psi[l] == "=":
                i.append(x[pos])
                j.append(x[pos])
                pos += 1
            else:
                i.append(x[pos])
                j.append(x[pos + 1])
                pos += 2
        # The variables of the equation are i_l and j_l with coefficients
        # f_l and -g_l, so the witness gives equal subscripts.
        assert value(f, i) == value(g, j)


def test_directions_lt_gt_do_not_change_the_answer():
    rng = random.Random(5)
    for _ in range(2000):
        k = rng.randint(1, 3)
        f = tuple(rng.randint(-6, 6) for _ in range(k + 1))
        g = tuple(rng.randint(-6, 6) for _ in range(k + 1))
        base = tuple(rng.choice("=*") for _ in range(k))
        other = tuple("=" if r == "=" else rng.choice("<>*") for r in base)
        assert gcd_test_subscript(f, g, base) == gcd_test_subscript(f, g, other)


def test_page_examples():
    # A[2*i] = A[2*i + 1]: even against odd.
    assert gcd_test([(0, 2)], [(1, 2)]) == "independent"
    # A[2*i] = A[3*i + 2] for i = 1..3: maybe, but no dependence in the bounds.
    assert gcd_test([(0, 2)], [(2, 3)]) == "maybe"
    assert brute_solutions([(0, 2)], [(2, 3)], [(1, 3)]) == []
    # A[i + 2*j] and A[4*i + 6*j + 3]: gcd(1, 2, 4, 6) = 1.
    assert gcd_test([(0, 1, 2)], [(3, 4, 6)]) == "maybe"
    # A[2*i + 4*j] and A[4*i + 6*j + 3]: gcd 2 does not divide 3.
    assert gcd_test([(0, 2, 4)], [(3, 4, 6)]) == "independent"
    # A[4*i] and A[2*i + 2] with psi = (=): (4 - 2) i = 2 has the solution i = 1.
    assert gcd_test([(0, 4)], [(2, 2)], ("=",)) == "maybe"
    # A[3*i] and A[i + 1] with psi = (=): 2 i = 1 has no solution, but with
    # psi = (*) the equation 3 i - j = 1 does.
    assert gcd_test([(0, 3)], [(1, 1)], ("=",)) == "independent"
    assert gcd_test([(0, 3)], [(1, 1)], ("*",)) == "maybe"
    # Coupled subscripts A[i][i] and A[j][j + 1]: each passes, no solution.
    src, snk = [(0, 1), (0, 1)], [(0, 1), (1, 1)]
    assert gcd_test(src, snk) == "maybe"
    assert brute_solutions(src, snk, [(1, 8)]) == []
    # A constant subscript pair: 5 against 5 and 5 against 7.
    assert gcd_test([(5, 0)], [(5, 0)]) == "maybe"
    assert gcd_test([(5, 0)], [(7, 0)]) == "independent"

History

The GCD test came out of the work on dependence analysis for parallelizing Fortran compilers at the University of Illinois in the 1970s, in the group of David Kuck. Utpal Banerjee's 1988 book states it with the bounds test that carries his name, and extends it to systems of equations with unimodular matrices. Allen and Kennedy and the dragon book present it as the basic test for subscripts with several indices.

References

  1. Randy Allen and Ken Kennedy, Optimizing Compilers for Modern Architectures, a Dependence-Based Approach, Morgan Kaufmann, 2002 (copyright 2001), Chapter 3 (the GCD test for MIV subscripts, with direction vectors)
  2. Utpal Banerjee, Dependence Analysis for Supercomputing, Kluwer Academic Publishers, 1988, the gcd test for one linear Diophantine equation and its generalization to systems
  3. Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 11.6 (the GCD test for linear Diophantine equations in array data-dependence analysis)
  4. Michael Wolfe, High Performance Compilers for Parallel Computing, Addison-Wesley, 1996, the chapter on dependence testing (the GCD test, with and without direction vectors)

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