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.
- Solves
- Dependence testing
- 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
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
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 has two references to an array of dimensions. Dimension of the source has the subscript , and the sink has , with integer coefficients. A direction vector may restrict the pairs (this page uses Wolfe's notation: at level means , see direction vector). The question is whether there are integer vectors , in the loop bounds with
and for each . The GCD test answers "independent" or "maybe". It must never answer "independent" when such vectors exist.
The algorithm
Let be the set of levels with equal to "=". At such a level the two indices are one variable, with coefficient .
GCD-TEST-SUBSCRIPT(a, b, psi):- 1
c <- b_0 - a_0 - 2
g <- 0 - 3
for l <- 1 to k do - 4
if psi_l = "=" then g <- gcd(g, a_l - b_l) - 5
else g <- gcd(g, a_l, b_l) - 6
if g = 0 then return ("maybe" if c = 0 else "independent") - 7
if c mod g != 0 then return "independent" - 8
return "maybe" GCD-TEST(src, snk, psi):- 9
for each dimension r do - 10
if GCD-TEST-SUBSCRIPT(src_r, snk_r, psi) = "independent" then return "independent" - 11
return "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 , and multiplying by 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 and the read in is .
With . The gcd of is , which divides . The answer is "maybe". The witness from the extended Euclidean algorithm is , outside the bounds, but there are also solutions inside, such as : writes and reads .
With . Now , and the trace is:
| line | action | |
|---|---|---|
| L1 | ||
| L2 | ||
| L4, | is "=": add | |
| L5, | add and | |
| L7 | independent |
So no dependence has "=" at the outer level: every dependence of this loop is carried by the loop, and the loop can run in parallel for each . 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 , the gcd of and is , and the answer is "maybe". But the loop writes and reads , 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 variables, the values of over integer vectors are exactly the multiples of . After the substitution for , the equation of one subscript has the coefficients for and 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 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 with gives the coefficients and , and . The gcd is the same, and the inequality 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 for the source and for the sink, with integer coefficients. The direction vector is optional; is the set of its "=" entries. The equation is
We take and , 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 .
Lemma 1 (Bezout for variables)
Let be integers and . Then the set is equal to . So the equation has an integer solution if and only if divides , where " divides " means .
Proof. If all are , then and , so . Otherwise has a positive element (take for one nonzero and elsewhere). Let be the smallest positive element of . The set is closed under sums and under multiplication by integers.
- Every element of is a multiple of . Take and divide: with . Then , and , so is not positive. So .
- . Each is in (take the unit vector), so divides each , and therefore divides . Also divides each , so divides each element of , and in particular . Both are positive, so .
So by the first point, and because and is closed under integer multiples.
Lemma 2 (the witness)
ext_gcd(a, b) returns with , and solve_linear(coefs, c) returns an integer vector with when divides , and None otherwise.
Proof. In ext_gcd, let and be the inputs. The loop keeps and : at the start , and one step replaces with and the coefficient pairs in the same way. It also keeps , since a common divisor of and divides , and back. Python's divmod gives , so falls at each step and the loop ends with . Then , and the sign flip makes .
In solve_linear, after the step for index the vector satisfies with (the other entries are ). Before the first step this holds with and . A step computes , multiplies the old vector by , and sets ; the new sum is . At the end, . If , all coefficients are , and the zero vector solves the equation exactly when . If and divides , multiplying by gives a solution. If does not divide , Lemma 1 says that there is none, and the function returns None.
Theorem 1 (exactness of one subscript without bounds)
Let be the value of after lines L2 to L5 of gcd_test_subscript. Then the test answers "maybe" if and only if equation (1) has an integer solution with for all , with no bounds and no other constraint.
Proof. Put for . Equation (1) with these equalities is the equation
in the free integer variables (), and (). Its solutions are exactly the solutions of (1) with the equalities. Lines L2 to L5 compute : line L4 adds , line L5 adds and , and . This is the gcd of the coefficients of the equation above. By Lemma 1 the equation has a solution if and only if divides . Lines L6 to L8 return "maybe" in exactly this case: for when , and for when .
Theorem 2 (soundness)
If two references have a dependence, that is, integer vectors and in the loop bounds that make all subscript pairs equal and satisfy for each , then gcd_test returns "maybe". Equivalently, the answer "independent" proves that there is no dependence with the direction vector .
Proof. Take such and , and one subscript pair. The pair satisfies equation (1) of that subscript, and for because 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".
Why "<" and ">" are not used
The test could try to use by writing with . The terms of level become , and , since a common divisor of two of , , divides the third. So the gcd does not change, and the constraint 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:
- against with : divides , but the solutions all leave the box.
- against with : divides , but is forced.
- against : 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 takes division steps, and the running gcd never exceeds the largest coefficient. A subscript makes at most calls, so the test of subscripts takes arithmetic operations and extra space. solve_linear takes operations for variables, because it scales the vector once per variable.
Complexity
Each gcd of numbers at most in absolute value takes division steps, and a subscript needs at most of them. The whole test takes time and extra space. A test that stops at the first independent subscript can end after steps when the gcds are small. A full search over direction vectors multiplies the cost by the number of vectors tested, at most 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 , for instance whenever some coefficient is , and then the test always says "maybe".
Variants and improvements
- Generalized GCD test. Solve the whole system of 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 against . 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 , the gcd is ; the subscripts are equal only when the constants are equal. Treating as "divides everything" gives a wrong "maybe", which is safe, but treating it as "divides nothing" gives a wrong "independent" for against , which is not safe.
- Using the gcd of the "<" substitution as stronger. Substituting does not change the gcd; only "=" does.
- Testing each subscript and concluding about the system. Each subscript of against 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 has no integer coefficient; the test must treat the term as unknown and answer "maybe", or test with 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.
# 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
- 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)
- Utpal Banerjee, Dependence Analysis for Supercomputing, Kluwer Academic Publishers, 1988, the gcd test for one linear Diophantine equation and its generalization to systems
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag M4BM5N Edit this page History Report an error Markdown