[llvm-branch-commits] [mlir] [mlir][Presburger] Add IntegerRelation::gist (context-based simplification) (PR #235957)
Jeremy Kun via llvm-branch-commits
llvm-branch-commits at lists.llvm.org
Mon Nov 2 20:57:47 PST 2026
https://github.com/j2kun updated https://github.com/llvm/llvm-project/pull/235957
>From d49de3e0c50e8138c255ef61ffef02bbdf5bc6e1 Mon Sep 17 00:00:00 2001
From: Jeremy Kun <jkun at google.com>
Date: Mon, 26 Oct 2026 13:24:04 -0700
Subject: [PATCH] [mlir][Presburger] Add IntegerRelation::gist (context-based
simplification)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Add IntegerRelation::gist(context), a port of ISL's isl_basic_map_gist
(uset_gist / uset_gist_full). It replaces the relation S by a relation
S' such that S' ∩ context == S ∩ context, with as few constraints as
possible: constraints of S that are implied by the context together with
the remaining constraints of S are removed, and the remaining constraints
may be rewritten using the equalities of the context. Outside of the
context S' may differ from S, so the result is only meaningful together
with the context. The result has at most as many constraints as S
(except that the constraints defining a division that is still used may
be restored, see below), never more local variables, and never involves
variables that S does not involve; in particular, locals of the context
are never introduced.
Trivial cases: an obviously empty context yields the universe; if the
intersection with the context is found to be empty later (inconsistent
combined equalities, a context that turns out to be rationally empty, or
an empty combined Simplex), the result is empty; an obviously empty S
stays empty; in the universe context only removeRedundantConstraints is
applied.
The algorithm:
- aligns the local variables of S and the context with mergeLocalVars
(isl_basic_map_align_divs) and works in the common space;
- checks whether the combined equalities (affine hulls) of S and the
context are inconsistent after Gaussian elimination;
- rewrites the constraints using the context equalities
(reduceUsingEqualities, i.e. isl_basic_set_reduce_using_equalities with
project_onto_involved);
- builds a Simplex of the context and drops inequalities of S that are
shifted copies of context inequalities (mark_shifted_constraints);
- adds the constraints of S to the Simplex, inequalities involving locals
first so that, among mutually redundant constraints, those are removed
in favor of constraints that do not involve locals
(isl_basic_set_sort_constraints); detects implicit equalities
(inequalities whose maximum is zero) and eliminates them pivoting on
their last variable; removes the rationally redundant constraints with
Simplex::detectRedundant restricted to the constraints of S, so that
the context constraints are never removed;
- integer-exact pass: each remaining inequality is dropped if its
negation, together with the context and the remaining constraints, has
no integer solution (the final loop of uset_gist_full). This costs one
integer emptiness check per remaining inequality. Equalities are only
removed using rational reasoning, GCD tightening and Gaussian
elimination;
- unlike ISL, the definition of a division is not stored separately from
the constraints, so if the constraints defining a local that is still
used in the result were removed (e.g. the context defines the same
division), they are added back so that the local keeps its meaning and
the result can be intersected with the context again. Since the
definition of a division may use other locals (nested divisions), this
is iterated to a fixpoint;
- finally, local variables that are no longer used, in particular those
only added from the context, are removed.
Deviations from ISL: no stride simplification (gist_strides); implicit
equalities of the context are not detected; no variable compression
(Simplex and reduceUsingEqualities are used instead); constraints are
only partitioned into those involving locals and those that do not,
rather than fully sorted; division definitions are restored as described
above; ISL's drop_irrelevant_constraints is not ported (TODO).
---
.../Analysis/Presburger/IntegerRelation.h | 49 +-
.../Analysis/Presburger/IntegerRelation.cpp | 281 ++++++++++
.../Presburger/IntegerPolyhedronTest.cpp | 489 ++++++++++++++++++
.../Presburger/IntegerRelationTest.cpp | 41 ++
mlir/unittests/Analysis/Presburger/Utils.h | 34 ++
5 files changed, 893 insertions(+), 1 deletion(-)
diff --git a/mlir/include/mlir/Analysis/Presburger/IntegerRelation.h b/mlir/include/mlir/Analysis/Presburger/IntegerRelation.h
index 3d1ae4c8358cbf..d0805a1b4a6351 100644
--- a/mlir/include/mlir/Analysis/Presburger/IntegerRelation.h
+++ b/mlir/include/mlir/Analysis/Presburger/IntegerRelation.h
@@ -671,6 +671,47 @@ class IntegerRelation {
/// removing redundant constraints.
void simplify();
+ /// Simplify `this` in the context of `context`: replace `this` by a relation
+ /// that has the same intersection with `context` as `this`, but that is as
+ /// simple as possible. Outside of `context`, the result may differ from
+ /// `this`, so the result is only meaningful together with `context`.
+ ///
+ /// Constraints of `this` that are implied by `context` together with the
+ /// remaining constraints of `this` are removed, and the remaining constraints
+ /// may be rewritten using the equalities of `context`. The result has at
+ /// most as many constraints as `this`, except that the constraints defining
+ /// a division (local variable) that is still used in the result are restored
+ /// if they were removed, so that the local keeps its meaning. The result
+ /// never has more local variables than `this`, and it does not involve any
+ /// variable that `this` does not involve; in particular, local variables of
+ /// `context` are never introduced into `this`.
+ ///
+ /// If `context` is obviously empty (see `isObviouslyEmpty`), `this` becomes
+ /// the universe. Otherwise, if the intersection of `this` and `context` is
+ /// found to be empty (including when `context` itself turns out to be
+ /// empty), `this` becomes empty. Redundancy of inequalities is
+ /// integer-exact: an inequality is removed if no integer point of the
+ /// context and the remaining constraints violates it. Equalities are removed
+ /// using rational reasoning (Simplex), GCD tightening and Gaussian
+ /// elimination, so some equalities that are only redundant over the integers
+ /// may be kept.
+ ///
+ /// The spaces of `this` and `context` must be compatible; their local
+ /// variables are aligned internally and may differ.
+ ///
+ /// This is a port of ISL's `isl_basic_map_gist`, with the following
+ /// deviations, due to the current lack of support in FPL for ISL
+ /// functionality.
+ ///
+ /// - no stride simplification (missing `isl_set_get_stride_info`);
+ /// - implicit equalities of the context are not detected (missing affine hull
+ /// computation).
+ /// - no variable compression (missing isl_mat_variable_compression); the
+ /// equalities are handled by Simplex and `reduceUsingEqualities` instead;
+ /// - the constraints are only partitioned into those involving locals and
+ /// those that do not, rather than fully sorted;
+ void gist(const IntegerRelation &context);
+
/// Converts variables of kind srcKind in the range [varStart, varLimit) to
/// variables of kind dstKind. If `pos` is given, the variables are placed at
/// position `pos` of dstKind, otherwise they are placed after all the other
@@ -955,6 +996,13 @@ class IntegerRelation {
/// be inconsistent, `this` becomes empty.
void reduceUsingEqualities(const IntegerRelation &eqs);
+ /// Implementation detail of `gist`. Precondition: `ctx` has the same space
+ /// as `this` with the local variables aligned (see `mergeLocalVars`), both
+ /// have GCD-tightened and normalized constraints, and the trivial cases have
+ /// already been handled. The result may contain unused local variables,
+ /// which `gist` removes.
+ void gistAligned(const IntegerRelation &ctx);
+
/// Returns false if the fields corresponding to various variable counts, or
/// equality/inequality buffer sizes aren't consistent; true otherwise. This
/// is meant to be used within an assert internally.
@@ -1106,7 +1154,6 @@ class IntegerPolyhedron : public IntegerRelation {
/// return `this \ set`.
PresburgerSet subtract(const PresburgerSet &other) const;
};
-
} // namespace presburger
} // namespace mlir
diff --git a/mlir/lib/Analysis/Presburger/IntegerRelation.cpp b/mlir/lib/Analysis/Presburger/IntegerRelation.cpp
index e68cb0c5a42657..2f61c0012891fc 100644
--- a/mlir/lib/Analysis/Presburger/IntegerRelation.cpp
+++ b/mlir/lib/Analysis/Presburger/IntegerRelation.cpp
@@ -1544,6 +1544,287 @@ void IntegerRelation::simplify() {
// Current set is not empty.
}
+/// Removes the inequalities of `rel` that are obviously implied by a single
+/// inequality of `context`, i.e., that have the same linear part as an
+/// inequality of `context` with a constant term that is at least as large, as
+/// well as trivially true inequalities. Both relations must have the same
+/// columns. This is a port of ISL's mark_shifted_constraints.
+static void removeShiftedConstraints(IntegerRelation &rel,
+ const IntegerRelation &context) {
+ assert(rel.getNumCols() == context.getNumCols() && "columns must match");
+
+ // Map from the linear part of a context inequality to its smallest constant
+ // term, i.e., the tightest context bound with that linear part.
+ SmallDenseMap<ArrayRef<DynamicAPInt>, DynamicAPInt> contextBounds;
+ for (unsigned i = 0, e = context.getNumInequalities(); i < e; ++i) {
+ ArrayRef<DynamicAPInt> ineq = context.getInequality(i);
+ DynamicAPInt constTerm = ineq.back();
+ auto [it, inserted] =
+ contextBounds.try_emplace(ineq.drop_back(), constTerm);
+ if (!inserted && constTerm < it->second)
+ it->second = constTerm;
+ }
+
+ for (unsigned i = rel.getNumInequalities(); i-- > 0;) {
+ ArrayRef<DynamicAPInt> ineq = rel.getInequality(i);
+ ArrayRef<DynamicAPInt> linearPart = ineq.drop_back();
+ DynamicAPInt constTerm = ineq.back();
+ if (constTerm >= 0 && rangeIsZero(linearPart)) {
+ rel.removeInequality(i);
+ continue;
+ }
+ auto it = contextBounds.find(linearPart);
+ if (it != contextBounds.end() && constTerm >= it->second)
+ rel.removeInequality(i);
+ }
+}
+
+void IntegerRelation::gist(const IntegerRelation &context) {
+ assert(space.isCompatible(context.getSpace()) &&
+ "Spaces must be compatible.");
+
+ // Trivial cases.
+ if (getNumConstraints() == 0)
+ return;
+ if (context.isObviouslyEmpty()) {
+ // The universe, without any local variables.
+ clearConstraints();
+ removeVarRange(VarKind::Local, 0, getNumLocalVars());
+ return;
+ }
+ if (isObviouslyEmpty())
+ return;
+ // In the universe context, only the constraints that are redundant on their
+ // own can be removed.
+ if (context.getNumConstraints() == 0) {
+ removeRedundantConstraints();
+ return;
+ }
+
+ // Establish the preconditions of gistAligned: both relations use the same
+ // columns, with locals that have the same division representation merged
+ // and one-sided locals appended as zero columns (the caller's `context` is
+ // left untouched), and both are GCD-tightened and normalized so that
+ // shifted-constraint matching compares canonical rows.
+ IntegerRelation ctx = context;
+ mergeLocalVars(ctx);
+ gcdTightenInequalities();
+ normalizeConstraintsByGCD();
+ ctx.gcdTightenInequalities();
+ ctx.normalizeConstraintsByGCD();
+ gistAligned(ctx);
+
+ // Drop the local variables that are no longer used, in particular those
+ // that were only added to align the locals with the context.
+ unsigned localOffset = getVarKindOffset(VarKind::Local);
+ for (unsigned i = getNumLocalVars(); i-- > 0;)
+ if (isColZero(localOffset + i))
+ removeVar(VarKind::Local, i);
+}
+
+void IntegerRelation::gistAligned(const IntegerRelation &ctx) {
+ assert(space.isEqual(ctx.getSpace()) && "spaces must be aligned");
+ assert(!ctx.isObviouslyEmpty() && !isObviouslyEmpty() &&
+ getNumConstraints() != 0 && "trivial cases should have been handled");
+ unsigned localOffset = getVarKindOffset(VarKind::Local);
+ unsigned numLocals = getNumLocalVars();
+
+ // Remember the constraints that define the division representations of the
+ // locals. Unlike ISL, we do not store the definition of a division
+ // separately from the constraints, so if the defining constraints of a local
+ // that is still used in the result are removed, they are added back below,
+ // such that the local keeps its meaning.
+ struct DivDef {
+ /// The defining equality, or the lower bound if `isEq` is false.
+ SmallVector<DynamicAPInt, 8> first;
+ /// The upper bound if `isEq` is false.
+ SmallVector<DynamicAPInt, 8> second;
+ bool isEq = false;
+ bool exists = false;
+ };
+ SmallVector<DivDef, 4> divDefs(numLocals);
+ {
+ std::vector<MaybeLocalRepr> reprs(numLocals);
+ getLocalReprs(&reprs);
+ for (unsigned i = 0; i < numLocals; ++i) {
+ DivDef &def = divDefs[i];
+ if (reprs[i].kind == ReprKind::Equality) {
+ ArrayRef<DynamicAPInt> eq = getEquality(reprs[i].repr.equalityIdx);
+ def.first.assign(eq.begin(), eq.end());
+ def.isEq = def.exists = true;
+ } else if (reprs[i].kind == ReprKind::Inequality) {
+ ArrayRef<DynamicAPInt> lb =
+ getInequality(reprs[i].repr.inequalityPair.lowerBoundIdx);
+ ArrayRef<DynamicAPInt> ub =
+ getInequality(reprs[i].repr.inequalityPair.upperBoundIdx);
+ def.first.assign(lb.begin(), lb.end());
+ def.second.assign(ub.begin(), ub.end());
+ def.exists = true;
+ }
+ }
+ }
+
+ // Check whether the intersection of the affine hulls of `this` and `ctx`
+ // (i.e., the combined equalities) is obviously empty, which may only become
+ // apparent after Gaussian elimination.
+ {
+ IntegerRelation combined = *this;
+ for (unsigned i = 0, e = ctx.getNumEqualities(); i < e; ++i)
+ combined.addEquality(ctx.getEquality(i));
+ combined.gaussianEliminate();
+ if (combined.isObviouslyEmpty()) {
+ *this = getEmpty(getSpace());
+ return;
+ }
+ }
+
+ // Rewrite the constraints using the equalities of the context. Equalities
+ // of `this` that are implied by those of the context become trivial and are
+ // dropped.
+ reduceUsingEqualities(ctx);
+ if (isObviouslyEmpty()) {
+ *this = getEmpty(getSpace());
+ return;
+ }
+
+ // Build a Simplex of the context. Checking the context for emptiness has to
+ // come before any constraint of `this` is removed, since a context that is
+ // found to be empty only now makes the result empty.
+ // TODO: port ISL's drop_irrelevant_constraints to drop the constraints of
+ // the context that cannot affect the redundancy of the constraints of `this`.
+ Simplex simplex(ctx);
+ if (simplex.isEmpty()) {
+ *this = getEmpty(getSpace());
+ return;
+ }
+
+ // Drop inequalities that are obviously implied by a single inequality of
+ // the context.
+ removeShiftedConstraints(*this, ctx);
+ if (getNumConstraints() == 0)
+ return;
+
+ // Among mutually redundant constraints, `Simplex::detectRedundant` marks the
+ // ones that come first as redundant. Move the inequalities that involve
+ // locals to the front so that they are removed in favor of those that do
+ // not, as ISL does.
+ auto moveLocalInequalitiesFirst = [&]() {
+ unsigned front = 0;
+ for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
+ if (!rangeIsZero(getInequality(i).slice(localOffset, numLocals)))
+ inequalities.swapRows(i, front++);
+ }
+ };
+
+ // Add the constraints of `this` to the Simplex of the context. Only the
+ // constraints of `this`, starting at `offset`, are checked for redundancy;
+ // the context constraints are always respected.
+ unsigned offset = simplex.getNumConstraints();
+ moveLocalInequalitiesFirst();
+ simplex.intersectIntegerRelation(*this);
+ if (simplex.isEmpty()) {
+ *this = getEmpty(getSpace());
+ return;
+ }
+
+ // Detect implicit equalities: an inequality whose maximum over the
+ // intersection with the context is zero holds as an equality there.
+ bool foundEquality = false;
+ for (unsigned i = getNumInequalities(); i-- > 0;) {
+ MaybeOptimum<Fraction> max =
+ simplex.computeOptimum(Simplex::Direction::Up, getInequality(i));
+ if (max.isBounded() && *max == Fraction(0, 1)) {
+ addEquality(getInequality(i));
+ removeInequality(i);
+ foundEquality = true;
+ }
+ }
+ if (foundEquality) {
+ // Use the equalities to eliminate variables from the other constraints,
+ // pivoting on the last variable of each equality (as in
+ // reduceUsingEqualities), so that locals are eliminated in favor of
+ // dimensions and later dimensions in favor of earlier ones.
+ SmallVector<unsigned, 8> cols(
+ llvm::reverse(llvm::seq<unsigned>(0, getNumVars())));
+ llvm::SmallBitVector rowUsed(getNumEqualities());
+ SmallVector<unsigned, 8> pivotRows, pivotCols;
+ reduceEqualityRows(equalities, cols, rowUsed, pivotRows, pivotCols);
+ for (auto [pivotRow, pivotCol] : llvm::zip_equal(pivotRows, pivotCols)) {
+ ArrayRef<DynamicAPInt> pivot = getEquality(pivotRow);
+ for (unsigned i = 0, e = getNumInequalities(); i < e; ++i)
+ eliminateColumnUsingEquality(inequalities.getRow(i), pivot, pivotCol);
+ }
+ // The unused rows are now constant; a non-zero constant means that the
+ // set is empty.
+ removeTrivialRedundancy();
+ removeTrivialEqualities();
+ if (isObviouslyEmpty()) {
+ *this = getEmpty(getSpace());
+ return;
+ }
+ // Rebuild the Simplex with the new constraint layout; the offset does not
+ // change since the context is unchanged.
+ simplex = Simplex(ctx);
+ moveLocalInequalitiesFirst();
+ simplex.intersectIntegerRelation(*this);
+ }
+
+ // Remove the constraints of `this` that are redundant in the context.
+ simplex.detectRedundant(offset);
+ removeRedundantConstraintsFromSimplex(simplex, offset);
+
+ // Integer-exact pass: an inequality is redundant if its negation together
+ // with the context and the remaining constraints has no integer solution.
+ // The negation of `c >= 0` is `-c - 1 >= 0`. This costs one integer
+ // emptiness check per remaining inequality.
+ if (getNumInequalities() != 0) {
+ IntegerRelation combined = ctx;
+ combined.append(*this);
+ unsigned ctxIneqs = ctx.getNumInequalities();
+ unsigned numCols = getNumCols();
+ for (unsigned i = getNumInequalities(); i-- > 0;) {
+ unsigned r = ctxIneqs + i;
+ combined.inequalities.negateRow(r);
+ --combined.atIneq(r, numCols - 1);
+ if (combined.isIntegerEmpty()) {
+ removeInequality(i);
+ combined.removeInequality(r);
+ continue;
+ }
+ // Restore the inequality.
+ ++combined.atIneq(r, numCols - 1);
+ combined.inequalities.negateRow(r);
+ }
+ }
+
+ // Add back the defining constraints of the locals that are still used but
+ // have lost their division representation. Since the definition of a local
+ // may use other locals (nested divisions), this is iterated to a fixpoint,
+ // recomputing the representations and used columns after each addition.
+ llvm::SmallBitVector readded(numLocals);
+ bool changed = true;
+ while (changed) {
+ changed = false;
+ DivisionRepr divs = getLocalReprs();
+ for (unsigned i = 0; i < numLocals; ++i) {
+ const DivDef &def = divDefs[i];
+ if (!def.exists || readded[i] || divs.hasRepr(i) ||
+ isColZero(localOffset + i))
+ continue;
+ if (def.isEq) {
+ addEquality(def.first);
+ } else {
+ addInequality(def.first);
+ addInequality(def.second);
+ }
+ readded[i] = true;
+ changed = true;
+ }
+ if (changed)
+ removeTrivialRedundancy();
+ }
+}
+
/// Removes local variables using equalities. Each equality is checked if it
/// can be reduced to the form: `e = affine-expr`, where `e` is a local
/// variable and `affine-expr` is an affine expression not containing `e`.
diff --git a/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp b/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp
index a4a48f0b8923de..83e8b5d7b6b6d0 100644
--- a/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp
+++ b/mlir/unittests/Analysis/Presburger/IntegerPolyhedronTest.cpp
@@ -1499,3 +1499,492 @@ TEST(IntegerPolyhedronTest, truncateEqualityRegressionTest) {
set.truncate(snapshot);
EXPECT_EQ(set.getNumEqualities(), 0u);
}
+
+static IntegerPolyhedron universe(unsigned numDims, unsigned numSymbols = 0) {
+ return IntegerPolyhedron::getUniverse(
+ PresburgerSpace::getSetSpace(numDims, numSymbols));
+}
+
+static IntegerPolyhedron empty(unsigned numDims, unsigned numSymbols = 0) {
+ return IntegerPolyhedron(IntegerRelation::getEmpty(
+ PresburgerSpace::getSetSpace(numDims, numSymbols)));
+}
+
+/// Computes the gist of `set` in the context of `context`, checks the gist
+/// invariants (see `expectGistInvariants`), checks that gist is idempotent
+/// (computing the gist of the result again yields the same constraints), and,
+/// if provided, checks that the result is equal to `expected` and has
+/// `expectedNumConstraints` constraints. Returns the gist.
+static IntegerPolyhedron
+expectGist(const IntegerPolyhedron &set, const IntegerPolyhedron &context,
+ std::optional<IntegerPolyhedron> expected = std::nullopt,
+ std::optional<unsigned> expectedNumConstraints = std::nullopt) {
+ IntegerPolyhedron contextCopy = context;
+ IntegerPolyhedron gist = set;
+ gist.gist(context);
+ // The context is never modified.
+ EXPECT_TRUE(context.isObviouslyEqual(contextCopy));
+ expectGistInvariants(set, context, gist);
+ IntegerPolyhedron gistAgain = gist;
+ gistAgain.gist(context);
+ EXPECT_TRUE(gistAgain.isObviouslyEqual(gist))
+ << "gist is not idempotent: " << gist << "became " << gistAgain
+ << "in context " << context;
+ if (expected)
+ EXPECT_TRUE(gist.isEqual(*expected))
+ << "gist " << gist << "of set " << set << "in context " << context
+ << "is not equal to the expected " << *expected;
+ if (expectedNumConstraints)
+ EXPECT_EQ(gist.getNumConstraints(), *expectedNumConstraints)
+ << "gist " << gist << "of set " << set << "in context " << context;
+ return gist;
+}
+
+static IntegerPolyhedron
+expectGist(StringRef set, StringRef context,
+ std::optional<StringRef> expected = std::nullopt,
+ std::optional<unsigned> expectedNumConstraints = std::nullopt) {
+ std::optional<IntegerPolyhedron> expectedPoly;
+ if (expected)
+ expectedPoly = parseIntegerPolyhedron(*expected);
+ return expectGist(parseIntegerPolyhedron(set),
+ parseIntegerPolyhedron(context), expectedPoly,
+ expectedNumConstraints);
+}
+
+TEST(IntegerPolyhedronTest, gistDropsConstraintImpliedByContext) {
+ // Constraints of the set that are implied by the context are removed.
+ expectGist("(x, y) : (x >= 0, -x + 10 >= 0, y >= 0)", "(x, y) : (x >= 0)",
+ "(x, y) : (-x + 10 >= 0, y >= 0)", 2);
+}
+
+TEST(IntegerPolyhedronTest, gistDropsConstraintImpliedByContextAndRest) {
+ // x + y >= 2 is implied by x >= 1 and y >= 1, but y >= 1 is not implied by
+ // x >= 1 and x + y >= 2.
+ expectGist("(x, y) : (x + y - 2 >= 0, y - 1 >= 0)", "(x, y) : (x - 1 >= 0)",
+ "(x, y) : (y - 1 >= 0)");
+}
+
+TEST(IntegerPolyhedronTest, gistKeepsConstraintNotImpliedByContext) {
+ // Nothing is redundant.
+ expectGist("(x) : (x - 5 >= 0)", "(x) : (x - 1 >= 0)", "(x) : (x - 5 >= 0)",
+ 1);
+}
+
+TEST(IntegerPolyhedronTest, gistDropsShiftedCopyOfContextConstraint) {
+ // x >= 0 is a relaxed (shifted) copy of the context constraint x >= 5.
+ expectGist(parseIntegerPolyhedron("(x) : (x >= 0)"),
+ parseIntegerPolyhedron("(x) : (x - 5 >= 0)"), universe(1), 0);
+}
+
+TEST(IntegerPolyhedronTest, gistKeepsTighterShiftedConstraint) {
+ expectGist("(x) : (x - 5 >= 0)", "(x) : (x >= 0)", "(x) : (x - 5 >= 0)", 1);
+}
+
+TEST(IntegerPolyhedronTest, gistDropsShiftedCopyWithMultipleVars) {
+ expectGist("(x, y) : (x - 2*y - 1 >= 0, -x + 2*y + 10 >= 0)",
+ "(x, y) : (x - 2*y - 4 >= 0)", "(x, y) : (-x + 2*y + 10 >= 0)", 1);
+}
+
+TEST(IntegerPolyhedronTest, gistDropsConstraintImpliedRationally) {
+ // 2x >= 1 implies x >= 0 (even rationally, x >= 1/2 > 0).
+ expectGist("(x) : (x >= 0, -x + 3 >= 0)", "(x) : (2*x - 1 >= 0)",
+ "(x) : (-x + 3 >= 0)", 1);
+}
+
+TEST(IntegerPolyhedronTest, gistEqualitiesReducedByContextEqualities) {
+ // From the ISL test suite. The set is the single point (1, -1, 3); in the
+ // context (a = 1, b + c = 2), only b = -1 is needed.
+ expectGist("(a, b, c) : (a - 1 == 0, b + 1 == 0, c - 3 == 0)",
+ "(a, b, c) : (a - 1 == 0, b + c - 2 == 0, b + 1 >= 0, "
+ "-b + 2 >= 0)",
+ "(a, b, c) : (b + 1 == 0)", 1);
+}
+
+TEST(IntegerPolyhedronTest, gistEqualityNotImpliedIsKept) {
+ // From the ISL test suite. The context implies a <= b, but not a == b;
+ // nothing is redundant.
+ expectGist("(a, b, c) : (a - b == 0, a - 10 >= 0)",
+ "(a, b, c) : (c - a >= 0, b - c >= 0, c - 2 >= 0)",
+ "(a, b, c) : (a - b == 0, a - 10 >= 0)", 2);
+}
+
+TEST(IntegerPolyhedronTest, gistPromotesImplicitEquality) {
+ // From the ISL test suite. Implicit equality: i >= 0 together with the
+ // context i <= 0 gives i = 0.
+ IntegerPolyhedron gist =
+ expectGist("(i, j) : (i >= 0, i + j >= 0)", "(i, j) : (-i >= 0)",
+ "(i, j) : (i == 0, j >= 0)", 2);
+ EXPECT_EQ(gist.getNumEqualities(), 1u);
+ EXPECT_EQ(gist.getNumInequalities(), 1u);
+}
+
+TEST(IntegerPolyhedronTest, gistPromotedEqualityEliminatesLastVariable) {
+ // After promoting x - y >= 0 to an equality, the last variable (y) is
+ // eliminated from the remaining constraints in favor of the first (x).
+ IntegerPolyhedron gist =
+ expectGist("(x, y) : (x - y >= 0, x + y >= 0)", "(x, y) : (-x + y >= 0)",
+ "(x, y) : (x - y == 0, x >= 0)", 2);
+ EXPECT_THAT(gist.getInequality(0), ElementsAre(1, 0, 0));
+}
+
+TEST(IntegerPolyhedronTest, gistEmptyIntersectionYieldsEmpty) {
+ // From the ISL test suite. The intersection with the context is empty.
+ expectGist(parseIntegerPolyhedron(
+ "(a, b, q, p) : (a == 0, b == 0, q + 5 >= 0, -q + 5 >= 0, "
+ "p >= 0)"),
+ parseIntegerPolyhedron("(a, b, q, p) : (b - a - 1 >= 0)"),
+ empty(4));
+}
+
+TEST(IntegerPolyhedronTest, gistRewritesUsingContextEquality) {
+ // The context equality is used to rewrite the constraint. The last variable
+ // (y) is eliminated in favor of the first (x), following ISL, so the result
+ // is x >= 1 rather than the equivalent (in the context) y >= 1.
+ expectGist("(x, y) : (2*x + y - 1 >= 0)", "(x, y) : (x - y == 0)",
+ "(x, y) : (x - 1 >= 0)", 1);
+}
+
+TEST(IntegerPolyhedronTest, gistContextEqualityOnUninvolvedVarsDoesNotLeak) {
+ // Context equalities that only involve variables not involved in the set
+ // are not used, so no constraints on y and z are introduced.
+ IntegerPolyhedron gist =
+ expectGist(parseIntegerPolyhedron("(x, y, z) : (x >= 0)"),
+ parseIntegerPolyhedron("(x, y, z) : (y - z == 0, x - 1 >= 0)"),
+ universe(3), 0);
+ EXPECT_EQ(gist.getNumVars(), 3u);
+}
+
+TEST(IntegerPolyhedronTest, gistInconsistentAffineHullsYieldEmpty) {
+ // The set is empty (a would have to be both odd and even), which is only
+ // detected after combining its equalities.
+ expectGist(parseIntegerPolyhedron(
+ "(a, b, c) : (2*b - a - 1 == 0, 2*c - a - 2 == 0)"),
+ parseIntegerPolyhedron("(a, b, c) : (2*c - a - 2 == 0)"),
+ empty(3));
+}
+
+/// The set used by the trivial-case tests below.
+static IntegerPolyhedron getTrivialCasesSet() {
+ return parseIntegerPolyhedron(
+ "(x, y)[N] : (x >= 0, -x + N >= 0, y - x >= 0)");
+}
+
+TEST(IntegerPolyhedronTest, gistUniverseContextKeepsIrredundantSet) {
+ // The universe context does not simplify anything.
+ IntegerPolyhedron set = getTrivialCasesSet();
+ expectGist(set, universe(2, 1), set, 3);
+}
+
+TEST(IntegerPolyhedronTest, gistSelfYieldsUniverse) {
+ // A set in its own context is the universe.
+ IntegerPolyhedron set = getTrivialCasesSet();
+ expectGist(set, set, universe(2, 1), 0);
+}
+
+TEST(IntegerPolyhedronTest, gistEmptySetStaysEmpty) {
+ IntegerPolyhedron gist = expectGist(empty(2, 1), getTrivialCasesSet());
+ EXPECT_TRUE(gist.isObviouslyEmpty());
+}
+
+TEST(IntegerPolyhedronTest, gistObviouslyEmptyContextYieldsUniverse) {
+ // Anything in an empty context is the universe.
+ expectGist(getTrivialCasesSet(), empty(2, 1), universe(2, 1), 0);
+}
+
+TEST(IntegerPolyhedronTest, gistEmptySetInEmptyContextYieldsUniverse) {
+ // From the ISL test suite.
+ expectGist(empty(2, 1), empty(2, 1), universe(2, 1), 0);
+}
+
+TEST(IntegerPolyhedronTest, gistUniverseStaysUniverse) {
+ expectGist(universe(2, 1), getTrivialCasesSet(), universe(2, 1), 0);
+}
+
+TEST(IntegerPolyhedronTest, gistAliasedSelfYieldsUniverse) {
+ // A set in its own context, passed as the same object.
+ IntegerPolyhedron self = getTrivialCasesSet();
+ self.gist(self);
+ EXPECT_EQ(self.getNumConstraints(), 0u);
+}
+
+TEST(IntegerPolyhedronTest,
+ gistUniverseContextEqualsRemoveRedundantConstraints) {
+ // In the universe context, gist behaves like removeRedundantConstraints.
+ IntegerPolyhedron redundant =
+ parseIntegerPolyhedron("(x, y) : (x >= 0, y >= 0, x + y >= 0)");
+ IntegerPolyhedron removed = redundant;
+ removed.removeRedundantConstraints();
+ IntegerPolyhedron gist = expectGist(redundant, universe(2), redundant);
+ EXPECT_EQ(gist.getNumConstraints(), removed.getNumConstraints());
+ EXPECT_EQ(gist.getNumConstraints(), 2u);
+}
+
+TEST(IntegerPolyhedronTest, gistRationallyEmptyContextYieldsEmpty) {
+ // Only an obviously empty context yields the universe. A context that is
+ // found to be empty later yields the empty set, since the intersection with
+ // the context is empty.
+ expectGist(parseIntegerPolyhedron("(x) : (x >= 0)"),
+ parseIntegerPolyhedron("(x) : (x - 1 >= 0, -x >= 0)"), empty(1));
+}
+
+TEST(IntegerPolyhedronTest, gistContextEmptyAfterGcdTighteningYieldsEmpty) {
+ // The context is rationally non-empty (x = 1/2) but has no integer points,
+ // which GCD tightening of the context reveals.
+ expectGist(parseIntegerPolyhedron("(x) : (x >= 0)"),
+ parseIntegerPolyhedron("(x) : (2*x - 1 >= 0, -2*x + 1 >= 0)"),
+ empty(1));
+}
+
+TEST(IntegerPolyhedronTest, gistContextWithInconsistentEqualitiesYieldsEmpty) {
+ expectGist(parseIntegerPolyhedron("(x) : (x >= 0)"),
+ parseIntegerPolyhedron("(x) : (x == 0, x - 1 == 0)"), empty(1));
+}
+
+TEST(IntegerPolyhedronTest, gistSymbolicContextBound) {
+ expectGist("(x)[N] : (x >= 0, N - x >= 0)", "(x)[N] : (N - 10 >= 0, x >= 0)",
+ "(x)[N] : (N - x >= 0)", 1);
+}
+
+TEST(IntegerPolyhedronTest, gistSymbolOnlyContextKeepsSet) {
+ expectGist("(x)[N] : (x >= 0, -x + N >= 0)", "(x)[N] : (N >= 0)",
+ "(x)[N] : (x >= 0, -x + N >= 0)", 2);
+}
+
+TEST(IntegerPolyhedronTest, gistContextEqualityOnSymbolIsSubstituted) {
+ // The context equality N = 5 is substituted into the constraints.
+ IntegerPolyhedron gist = expectGist("(x)[N] : (x - N >= 0, -x + N + 5 >= 0)",
+ "(x)[N] : (N - 5 == 0)",
+ "(x)[N] : (x - 5 >= 0, -x + 10 >= 0)", 2);
+ EXPECT_TRUE(isColumnZero(gist, 1));
+}
+
+TEST(IntegerPolyhedronTest, gistDropsSharedDivisionDefinition) {
+ // From the ISL test suite. The context defines the same division as the
+ // set; the set's constraint on it becomes redundant and the local is
+ // dropped.
+ IntegerPolyhedron gist = expectGist(
+ "(x)[n] : (x - n == 0, x - 32*(x floordiv 32) == 0)",
+ "(x)[n] : (x - 32*(x floordiv 32) == 0)", "(x)[n] : (x - n == 0)", 1);
+ EXPECT_EQ(gist.getNumLocalVars(), 0u);
+}
+
+TEST(IntegerPolyhedronTest, gistDropsContextOnlyLocals) {
+ // From the ISL test suite. The local of the context is not introduced into
+ // the set.
+ IntegerPolyhedron gist =
+ expectGist("(a, b, c) : (a - 1 >= 0, -a + 15 >= 0)",
+ "(a, b, c) : (a - 1 >= 0, -c + 30 >= 0, "
+ "32*((a - 1) floordiv 16) - 2*a - 2*b + c + 62 >= 0, "
+ "b >= 0)",
+ "(a, b, c) : (-a + 15 >= 0)", 1);
+ EXPECT_EQ(gist.getNumLocalVars(), 0u);
+}
+
+TEST(IntegerPolyhedronTest, gistKeepsUnrelatedLocalAndZeroColumn) {
+ // From the ISL test suite. No constraints on i6 are introduced in the gist,
+ // even though the context equality involves i6.
+ StringRef set = "(i4, i6)[t1] : (-5*((1530 - 4*t1 - 5*i4) floordiv 20) - t1 "
+ "+ 381 >= 0, -i4 + 1 >= 0)";
+ IntegerPolyhedron gist =
+ expectGist(set,
+ "(i4, i6)[t1] : (i6 - t1 - 5*((i6 - t1) floordiv 5) == 0, "
+ "-i6 + 6 >= 0, i6 - 3 >= 0)",
+ set);
+ EXPECT_TRUE(isColumnZero(gist, 1));
+ EXPECT_EQ(gist.getNumLocalVars(), 1u);
+}
+
+TEST(IntegerPolyhedronTest, gistDropsOnlySharedDivision) {
+ // Only the division shared with the context is dropped.
+ IntegerPolyhedron gist =
+ expectGist("(n, i, j, k) : (i - 3*(i floordiv 3) - 2 == 0, "
+ "j - 4*(j floordiv 4) - 2 == 0)",
+ "(n, i, j, k) : (j - 4*(j floordiv 4) - 2 == 0)",
+ "(n, i, j, k) : (i - 3*(i floordiv 3) - 2 == 0)");
+ EXPECT_EQ(gist.getNumLocalVars(), 1u);
+}
+
+TEST(IntegerPolyhedronTest, gistStrideAndSymbolEqualityYieldEmpty) {
+ // From the ISL test suite. The intersection with the context is empty:
+ // x = 2 mod 3 and x = 3M.
+ expectGist(parseIntegerPolyhedron("(x)[M] : (x - 3*(x floordiv 3) - 2 == 0)"),
+ parseIntegerPolyhedron("(x)[M] : (x - 3*M == 0)"), empty(1, 1));
+}
+
+TEST(IntegerPolyhedronTest, gistRestoresDivisionDefinitionOfUsedLocal) {
+ // The division constraints of a local shared with the context are kept if
+ // the local is still used, so that the result is meaningful on its own.
+ IntegerPolyhedron gist = expectGist("(x) : ((x floordiv 2) - 3 >= 0)",
+ "(x) : (x - 2*(x floordiv 2) >= 0)",
+ "(x) : ((x floordiv 2) - 3 >= 0)", 3);
+ EXPECT_EQ(gist.getNumLocalVars(), 1u);
+}
+
+TEST(IntegerPolyhedronTest, gistRestoresNestedDivisionDefinitions) {
+ // Nested divisions: restoring the definition of the outer division makes
+ // the inner division used again, so its definition is restored too.
+ IntegerPolyhedron gist =
+ expectGist("(x) : (((x floordiv 2) floordiv 2) - 1 >= 0)",
+ "(x) : (x - 4*((x floordiv 2) floordiv 2) >= 0)",
+ "(x) : (((x floordiv 2) floordiv 2) - 1 >= 0)", 5);
+ EXPECT_EQ(gist.getNumLocalVars(), 2u);
+}
+
+TEST(IntegerPolyhedronTest, gistEmptyContextYieldsUniverseWithoutLocals) {
+ // An obviously empty context yields the universe without locals.
+ IntegerPolyhedron gist =
+ expectGist(parseIntegerPolyhedron("(x) : ((x floordiv 2) - 3 >= 0)"),
+ empty(1), universe(1), 0);
+ EXPECT_EQ(gist.getNumLocalVars(), 0u);
+}
+
+// The following cases, from the ISL test suite, have a division in the set
+// that is different from the one in the context. Only the invariants are
+// checked.
+// TODO: ISL additionally simplifies stride (equality) constraints using the
+// equalities of the context (gist_strides), which would give `a - c == 0`,
+// `(a - c == 0, a - 3*(a floordiv 3) == 0)` and `x - 2*(x floordiv 2) == 0`
+// respectively.
+TEST(IntegerPolyhedronTest, gistStrideWithEqualityInvariantsOnly) {
+ expectGist("(a, b, c) : (a - 2*(a floordiv 2) == 0, a - c == 0)",
+ "(a, b, c) : (b - 2*(b floordiv 2) == 0, b - c == 0)");
+}
+
+TEST(IntegerPolyhedronTest, gistPartialStrideWithEqualityInvariantsOnly) {
+ expectGist("(a, b, c) : (a - 6*(a floordiv 6) == 0, a - c == 0)",
+ "(a, b, c) : (b - 2*(b floordiv 2) == 0, b - c == 0)");
+}
+
+TEST(IntegerPolyhedronTest, gistStrideDividingContextStrideInvariantsOnly) {
+ expectGist("(x) : (x - 6*(x floordiv 6) == 0)",
+ "(x) : (x - 3*(x floordiv 3) == 0)");
+}
+
+/// Check that `gist` has the same intersection with `context` as `set`, by
+/// checking which integer points in [-2, 12] are contained in each.
+static void expectSameIntersection1D(const IntegerPolyhedron &set,
+ const IntegerPolyhedron &context,
+ const IntegerPolyhedron &gist) {
+ IntegerPolyhedron setAndContext = set.intersect(context);
+ IntegerPolyhedron gistAndContext = gist.intersect(context);
+ for (int64_t i = -2; i <= 12; ++i)
+ EXPECT_EQ(containsPointNoLocal(setAndContext, {i}),
+ containsPointNoLocal(gistAndContext, {i}))
+ << "at point " << i;
+}
+
+/// Returns the set `(i) : exists e0, e1 : 3*e1 - 2*e0 - 1 >= 0,
+/// -8*e1 + 5*i - 5*e0 - 1 >= 0, 2*e1 - 2*i + 5*e0 - 1 >= 0` (from the ISL
+/// test suite), optionally with the bounds 0 <= i <= 10, where the locals e0
+/// and e1 have no division representation.
+static IntegerPolyhedron getNonDivLocalsSet(bool bounded) {
+ IntegerPolyhedron set = parseIntegerPolyhedron(
+ bounded ? "(i, e0, e1) : (3*e1 - 2*e0 - 1 >= 0, -8*e1 + 5*i - 5*e0 - 1 "
+ ">= 0, 2*e1 - 2*i + 5*e0 - 1 >= 0, i >= 0, -i + 10 >= 0)"
+ : "(i, e0, e1) : (3*e1 - 2*e0 - 1 >= 0, -8*e1 + 5*i - 5*e0 - 1 "
+ ">= 0, 2*e1 - 2*i + 5*e0 - 1 >= 0)");
+ set.convertToLocal(VarKind::SetDim, 1, 3);
+ EXPECT_FALSE(set.hasOnlyDivLocals());
+ return set;
+}
+
+/// Returns the context `(i) : exists a, b : 2*b - 2*i + 5*a - 1 >= 0,
+/// 5*i - 5*a - 8*b - 1 >= 0, 3*b - 2*a - 1 >= 0` (from the ISL test suite),
+/// whose locals have no division representation and which implies i >= 1
+/// (even rationally).
+static IntegerPolyhedron getNonDivLocalsContext() {
+ IntegerPolyhedron context = parseIntegerPolyhedron(
+ "(i, a, b) : (2*b - 2*i + 5*a - 1 >= 0, 5*i - 5*a - 8*b - 1 >= 0, "
+ "3*b - 2*a - 1 >= 0)");
+ context.convertToLocal(VarKind::SetDim, 1, 3);
+ return context;
+}
+
+TEST(IntegerPolyhedronTest, gistNonDivLocalsKept) {
+ // From the ISL test suite. Locals without a division representation.
+ IntegerPolyhedron set = getNonDivLocalsSet(/*bounded=*/false);
+ IntegerPolyhedron context = parseIntegerPolyhedron("(i) : (i >= 0)");
+ IntegerPolyhedron gist = set;
+ gist.gist(context);
+ EXPECT_EQ(gist.getNumConstraints(), 3u);
+ EXPECT_EQ(gist.getNumLocalVars(), 2u);
+ expectSameIntersection1D(set, context, gist);
+}
+
+TEST(IntegerPolyhedronTest, gistNonDivLocalsBoundsDropped) {
+ // From the ISL test suite. The bounds on i are implied by the context.
+ IntegerPolyhedron set = getNonDivLocalsSet(/*bounded=*/true);
+ IntegerPolyhedron context =
+ parseIntegerPolyhedron("(i) : (i >= 0, -i + 10 >= 0)");
+ IntegerPolyhedron gist = set;
+ gist.gist(context);
+ EXPECT_EQ(gist.getNumConstraints(), 3u);
+ expectSameIntersection1D(set, context, gist);
+}
+
+TEST(IntegerPolyhedronTest, gistNonDivLocalContextKeepsStrongerBound) {
+ // From the ISL test suite. i >= 100 is not implied by the context.
+ expectGist(parseIntegerPolyhedron("(i) : (i - 100 >= 0)"),
+ getNonDivLocalsContext(),
+ parseIntegerPolyhedron("(i) : (i - 100 >= 0)"), 1);
+}
+
+TEST(IntegerPolyhedronTest, gistNonDivLocalContextImpliesBound) {
+ // From the ISL test suite. i >= 0 is implied by the context.
+ expectGist(parseIntegerPolyhedron("(i) : (i >= 0)"), getNonDivLocalsContext(),
+ universe(1), 0);
+}
+
+TEST(IntegerPolyhedronTest, gistIntegerOnlyRedundancyWithStrideDropped) {
+ // x >= 2 is not implied by x >= 1 rationally, but it is implied for even x.
+ expectGist(
+ parseIntegerPolyhedron("(x) : (x - 2 >= 0)"),
+ parseIntegerPolyhedron("(x) : (x - 2*(x floordiv 2) == 0, x - 1 >= 0)"),
+ universe(1), 0);
+}
+
+TEST(IntegerPolyhedronTest, gistIntegerOnlyRedundancyDropped) {
+ // The rational point (1.2, 1.2) lies in the context but violates
+ // x + y <= 2, while all integer points of the context satisfy it.
+ expectGist(parseIntegerPolyhedron("(x, y) : (2 - x - y >= 0)"),
+ parseIntegerPolyhedron("(x, y) : (x >= 0, y >= 0, "
+ "6 - 2*x - 3*y >= 0, 6 - 3*x - 2*y >= 0)"),
+ universe(2), 0);
+}
+
+TEST(IntegerPolyhedronTest, gistIntegerExactBoxEnumeration) {
+ // A larger system: check the intersection with the context by enumerating
+ // all points of the box [0, 10]^3 that contains the set.
+ IntegerPolyhedron set = parseIntegerPolyhedron(
+ "(x, y, z) : (x >= 0, -x + 10 >= 0, y >= 0, -y + 10 >= 0, "
+ "z >= 0, -z + 10 >= 0, x + y - z >= 0, x - y + z + 5 >= 0, "
+ "-x + y + z + 3 >= 0, x + y + z - 4 >= 0)");
+ IntegerPolyhedron context =
+ parseIntegerPolyhedron("(x, y, z) : (x - 1 >= 0, y - 2 >= 0, z - 1 >= 0, "
+ "-x - y - z + 25 >= 0, 2*x - 3*y + 7 >= 0)");
+ IntegerPolyhedron gist = expectGist(set, context);
+ IntegerPolyhedron setAndContext = set.intersect(context);
+ IntegerPolyhedron gistAndContext = gist.intersect(context);
+ for (int64_t x = 0; x <= 10; ++x)
+ for (int64_t y = 0; y <= 10; ++y)
+ for (int64_t z = 0; z <= 10; ++z)
+ EXPECT_EQ(containsPointNoLocal(setAndContext, {x, y, z}),
+ containsPointNoLocal(gistAndContext, {x, y, z}))
+ << "at point (" << x << ", " << y << ", " << z << ")";
+}
+
+TEST(IntegerPolyhedronTest, gistStrideInCoarserStrideInvariantsOnly) {
+ // Stride constraints from the ISL test suite. Only the invariants are
+ // checked.
+ // TODO: ISL's gist_strides would give `x - 128*(x floordiv 128) == 0`.
+ expectGist("(x) : (x - 3200*(x floordiv 3200) == 0)",
+ "(x) : (x - 10000*(x floordiv 10000) == 0)");
+}
+
+TEST(IntegerPolyhedronTest, gistStrideInFinerStrideUnchanged) {
+ // From the ISL test suite; the set is unchanged in ISL too.
+ expectGist("(x) : (x - 3200*(x floordiv 3200) == 0)",
+ "(x) : (x - 10*(x floordiv 10) == 0)",
+ "(x) : (x - 3200*(x floordiv 3200) == 0)");
+}
diff --git a/mlir/unittests/Analysis/Presburger/IntegerRelationTest.cpp b/mlir/unittests/Analysis/Presburger/IntegerRelationTest.cpp
index c3da1c1556d266..a130267f32edb3 100644
--- a/mlir/unittests/Analysis/Presburger/IntegerRelationTest.cpp
+++ b/mlir/unittests/Analysis/Presburger/IntegerRelationTest.cpp
@@ -8,6 +8,7 @@
#include "mlir/Analysis/Presburger/IntegerRelation.h"
#include "Parser.h"
+#include "Utils.h"
#include "mlir/Analysis/Presburger/PresburgerSpace.h"
#include "mlir/Analysis/Presburger/Simplex.h"
@@ -777,3 +778,43 @@ TEST(IntegerRelationTest, isFullDim) {
rel = parseRelationFromSet("(x): (-1 >= 0)", 1);
EXPECT_FALSE(rel.isFullDim());
}
+
+TEST(IntegerRelationTest, gistPreservesDomainAndRange) {
+ IntegerRelation rel = parseRelationFromSet(
+ "(x, y) : (y - x - 1 >= 0, x >= 0, -x + 10 >= 0)", 1);
+ IntegerRelation context = parseRelationFromSet("(x, y) : (x >= 0)", 1);
+ IntegerRelation gist = rel;
+ gist.gist(context);
+
+ expectGistInvariants(rel, context, gist);
+ IntegerRelation gistAgain = gist;
+ gistAgain.gist(context);
+ EXPECT_TRUE(gistAgain.isObviouslyEqual(gist));
+ EXPECT_TRUE(gist.isEqual(
+ parseRelationFromSet("(x, y) : (y - x - 1 >= 0, -x + 10 >= 0)", 1)));
+ EXPECT_EQ(gist.getNumConstraints(), 2u);
+ EXPECT_EQ(gist.getNumDomainVars(), 1u);
+ EXPECT_EQ(gist.getNumRangeVars(), 1u);
+}
+
+TEST(IntegerRelationTest, gistWithSymbolsAndSharedLocal) {
+ // Domain, range and symbol variables, with the same division (local) on
+ // both sides.
+ IntegerRelation rel = parseRelationFromSet(
+ "(x, y)[N] : (y - 2*(y floordiv 2) == 0, x - N >= 0, y - x >= 0)", 1);
+ IntegerRelation context = parseRelationFromSet(
+ "(x, y)[N] : (y - 2*(y floordiv 2) == 0, x - N >= 0, N >= 0)", 1);
+ IntegerRelation gist = rel;
+ gist.gist(context);
+ expectGistInvariants(rel, context, gist);
+ IntegerRelation gistAgain = gist;
+ gistAgain.gist(context);
+ EXPECT_TRUE(gistAgain.isObviouslyEqual(gist));
+ EXPECT_TRUE(
+ gist.isEqual(parseRelationFromSet("(x, y)[N] : (y - x >= 0)", 1)));
+ EXPECT_EQ(gist.getNumConstraints(), 1u);
+ EXPECT_EQ(gist.getNumLocalVars(), 0u);
+ EXPECT_EQ(gist.getNumDomainVars(), 1u);
+ EXPECT_EQ(gist.getNumRangeVars(), 1u);
+ EXPECT_EQ(gist.getNumSymbolVars(), 1u);
+}
diff --git a/mlir/unittests/Analysis/Presburger/Utils.h b/mlir/unittests/Analysis/Presburger/Utils.h
index ef4355f9e38058..ab0978260b50e6 100644
--- a/mlir/unittests/Analysis/Presburger/Utils.h
+++ b/mlir/unittests/Analysis/Presburger/Utils.h
@@ -161,6 +161,40 @@ inline void expectComputedVolumeIsValidOverapprox(
llvm::transformOptional(resultBound, getDynamicAPInt));
}
+/// Returns true if no constraint of `rel` has a non-zero coefficient for the
+/// variable at column `col`.
+inline bool isColumnZero(const IntegerRelation &rel, unsigned col) {
+ for (unsigned i = 0, e = rel.getNumEqualities(); i < e; ++i)
+ if (rel.atEq(i, col) != 0)
+ return false;
+ for (unsigned i = 0, e = rel.getNumInequalities(); i < e; ++i)
+ if (rel.atIneq(i, col) != 0)
+ return false;
+ return true;
+}
+
+/// Check the invariants that `gist`, the result of `set.gist(context)`, must
+/// satisfy: it has the same intersection with `context` as `set`, it has no
+/// more constraints and no more local variables than `set`, and it does not
+/// involve any (non-local) variable that `set` does not involve.
+inline void expectGistInvariants(const IntegerRelation &set,
+ const IntegerRelation &context,
+ const IntegerRelation &gist) {
+ EXPECT_TRUE(gist.intersect(context).isEqual(set.intersect(context)))
+ << "gist " << gist << "of set " << set << "has a different intersection "
+ << "with context " << context;
+ EXPECT_LE(gist.getNumConstraints(), set.getNumConstraints());
+ EXPECT_LE(gist.getNumLocalVars(), set.getNumLocalVars());
+ ASSERT_EQ(gist.getNumVars() - gist.getNumLocalVars(),
+ set.getNumVars() - set.getNumLocalVars());
+ for (unsigned col = 0, e = set.getNumVars() - set.getNumLocalVars(); col < e;
+ ++col) {
+ if (isColumnZero(set, col))
+ EXPECT_TRUE(isColumnZero(gist, col))
+ << "gist " << gist << "involves variable " << col
+ << " that is not involved in set " << set;
+ }
+}
} // namespace presburger
} // namespace mlir
More information about the llvm-branch-commits
mailing list