26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallBitVector.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
40 #define DEBUG_TYPE "presburger"
43 using namespace presburger;
45 using llvm::SmallDenseMap;
46 using llvm::SmallDenseSet;
49 return std::make_unique<IntegerRelation>(*
this);
53 return std::make_unique<IntegerPolyhedron>(*
this);
62 assert(oSpace.
getNumLocalVars() == 0 &&
"no locals should be present!");
106 for (
unsigned j = 0;
j < cols; ++
j) {
112 for (
unsigned j = 0;
j < cols; ++
j) {
140 "Incorrect number of vars in lexMin!");
159 "Incorrect number of vars in lexMin!");
165 return llvm::all_of(range, [](
const MPInt &x) {
return x == 0; });
169 unsigned begin,
unsigned count) {
188 assert(num <= curNum &&
"Can't truncate to more vars!");
217 copy.getLocalReprs(&reprs);
221 unsigned numNonDivLocals = 0;
223 for (
unsigned i = 0, e =
copy.getNumLocalVars(); i < e - numNonDivLocals;) {
228 copy.swapVar(offset + i, offset + e - numNonDivLocals - 1);
229 std::swap(reprs[i], reprs[e - numNonDivLocals - 1]);
237 if (numNonDivLocals == 0)
254 copy.getNumVars() - numNonDivLocals)))
271 llvm::SmallBitVector isSymbol(
getNumVars(),
false);
315 symbolicIntegerLexMax(
318 for (
auto &flippedPiece :
320 IntMatrix mat = flippedPiece.output.getOutputMatrix();
321 for (
unsigned i = 0, e = mat.
getNumRows(); i < e; i++)
325 symbolicIntegerLexMax.lexopt.addPiece(piece);
327 symbolicIntegerLexMax.unboundedDomain =
329 return symbolicIntegerLexMax;
354 for (
unsigned i = 0, e = eq.size(); i < e; ++i)
361 for (
unsigned i = 0, e = inEq.size(); i < e; ++i)
375 if (varStart >= varLimit)
390 if (varStart >= varLimit)
396 auto removeVarKindInRange = [
this](
VarKind kind,
unsigned &start,
405 unsigned relativeStart =
406 start <= offset ? 0 :
std::min(num, start - offset);
407 unsigned relativeLimit =
408 limit <= offset ? 0 :
std::min(num, limit - offset);
416 limit -= relativeLimit - relativeStart;
446 assert(posA <
getNumVars() &&
"invalid position A");
447 assert(posB <
getNumVars() &&
"invalid position B");
467 unsigned offset,
unsigned num)
const {
468 assert(pos <
getNumVars() &&
"invalid position");
469 assert(offset + num <
getNumCols() &&
"invalid range");
473 auto containsConstraintDependentOnRange = [&](
unsigned r,
bool isEq) {
476 for (c = offset, f = offset + num; c < f; ++c) {
490 if (containsConstraintDependentOnRange(r,
false))
492 if (
atIneq(r, pos) >= 1) {
494 lbIndices->push_back(r);
495 }
else if (
atIneq(r, pos) <= -1) {
497 ubIndices->push_back(r);
507 if (
atEq(r, pos) == 0)
509 if (containsConstraintDependentOnRange(r,
true))
511 eqIndices->push_back(r);
527 "invalid position or too many values");
532 for (
unsigned i = 0, numVals = values.size(); i < numVals; ++i)
534 for (
unsigned i = 0, numVals = values.size(); i < numVals; ++i)
547 unsigned *rowIdx)
const {
548 assert(colIdx <
getNumCols() &&
"position out of bounds");
549 auto at = [&](
unsigned rowIdx) ->
MPInt {
550 return isEq ?
atEq(rowIdx, colIdx) :
atIneq(rowIdx, colIdx);
553 for (*rowIdx = 0; *rowIdx < e; ++(*rowIdx)) {
554 if (at(*rowIdx) != 0) {
570 auto check = [&](
bool isEq) ->
bool {
573 for (
unsigned i = 0, e = numRows; i < e; ++i) {
575 for (
j = 0;
j < numCols - 1; ++
j) {
581 if (
j < numCols - 1) {
587 if ((isEq && v != 0) || (!isEq && v < 0)) {
602 unsigned rowIdx,
unsigned pivotRow,
603 unsigned pivotCol,
unsigned elimColStart,
606 if (isEq && rowIdx == pivotRow)
608 auto at = [&](
unsigned i,
unsigned j) ->
MPInt {
609 return isEq ? constraints->
atEq(i,
j) : constraints->
atIneq(i,
j);
611 MPInt leadCoeff = at(rowIdx, pivotCol);
615 MPInt pivotCoeff = constraints->
atEq(pivotRow, pivotCol);
616 int sign = (leadCoeff * pivotCoeff > 0) ? -1 : 1;
618 MPInt pivotMultiplier = sign * (
lcm /
abs(pivotCoeff));
622 for (
unsigned j = 0;
j < numCols; ++
j) {
624 if (
j >= elimColStart &&
j < pivotCol)
626 MPInt v = pivotMultiplier * constraints->
atEq(pivotRow,
j) +
627 rowMultiplier * at(rowIdx,
j);
628 isEq ? constraints->
atEq(rowIdx,
j) = v
629 : constraints->
atIneq(rowIdx,
j) = v;
639 unsigned start,
unsigned end) {
642 auto getProductOfNumLowerUpperBounds = [&](
unsigned pos) {
646 if (cst.
atIneq(r, pos) > 0) {
648 }
else if (cst.
atIneq(r, pos) < 0) {
652 return numLb * numUb;
655 unsigned minLoc = start;
656 unsigned min = getProductOfNumLowerUpperBounds(start);
657 for (
unsigned c = start + 1; c < end; c++) {
658 unsigned numLbUbProduct = getProductOfNumLowerUpperBounds(c);
659 if (numLbUbProduct <
min) {
660 min = numLbUbProduct;
683 unsigned currentPos = 0;
696 for (
unsigned i = 0, e = tmpCst.
getNumVars(); i < e; i++) {
705 LLVM_DEBUG(llvm::dbgs() <<
"FM constraint explosion detected\n");
742 for (
unsigned j = 1;
j < numCols - 1; ++
j) {
746 if (
gcd > 0 && (v %
gcd != 0)) {
767 assert(!simplex.
isEmpty() &&
"It is not meaningful to ask whether a "
768 "direction is bounded in an empty set.");
775 boundedIneqs.push_back(i);
785 for (
unsigned i : boundedIneqs) {
786 for (
unsigned col = 0; col < dirsNumCols; ++col)
787 dirs(row, col) =
atIneq(i, col);
793 for (
unsigned col = 0; col < dirsNumCols; ++col)
794 dirs(row, col) =
atEq(i, col);
848 std::optional<SmallVector<MPInt, 8>>
872 std::pair<unsigned, LinearTransform> result =
881 unsigned numBoundedDims = result.first;
882 unsigned numUnboundedDims =
getNumVars() - numBoundedDims;
888 std::optional<SmallVector<MPInt, 8>> boundedSample =
893 "Simplex returned an invalid sample!");
937 Simplex shrunkenConeSimplex(cone);
938 assert(!shrunkenConeSimplex.
isEmpty() &&
"Shrunken cone cannot be empty!");
948 sample.append(coneSample.begin(), coneSample.end());
956 assert(expr.size() == 1 + point.size() &&
957 "Dimensionalities of point and expression don't match!");
958 MPInt value = expr.back();
959 for (
unsigned i = 0; i < point.size(); ++i)
960 value += expr[i] * point[i];
987 std::optional<SmallVector<MPInt, 8>>
990 "Point should contain all vars except locals!");
992 "This function depends on locals being stored last!");
994 copy.setAndEliminate(0, point);
995 return copy.findIntegerSample();
1002 foundRepr[i] =
true;
1012 if (!foundRepr[i + localOffset]) {
1022 foundRepr[localOffset + i] =
true;
1054 unsigned posLimit) {
1059 if (posStart >= posLimit)
1064 unsigned pivotCol = 0;
1065 for (pivotCol = posStart; pivotCol < posLimit; ++pivotCol) {
1095 posLimit = pivotCol;
1098 return posLimit - posStart;
1104 unsigned nowDone, eqs, pivotRow;
1107 for (; firstVar < vars; ++firstVar) {
1113 if (firstVar >= vars)
1117 if (pivotRow > nowDone) {
1123 for (
unsigned i = nowDone + 1; i < eqs; ++i) {
1140 for (
unsigned i = nowDone; i < eqs; ++i) {
1141 if (
atEq(i, vars) == 0)
1198 for (
unsigned r = 0; r < numIneqs; r++) {
1242 bool hasUnboundedVar =
false;
1248 assert((!
min.isEmpty() && !
max.isEmpty()) &&
1249 "Polytope should be rationally non-empty!");
1253 if (
min.isUnbounded() ||
max.isUnbounded()) {
1254 hasUnboundedVar =
true;
1260 if (
min.getBoundedOptimum() >
max.getBoundedOptimum())
1263 count *= (*
max - *
min + 1);
1268 if (hasUnboundedVar)
1278 posA += localOffset;
1279 posB += localOffset;
1306 auto merge = [&relA, &relB, oldALocals](
unsigned i,
unsigned j) ->
bool {
1335 auto merge = [
this](
unsigned i,
unsigned j) ->
bool {
1343 bool changed =
true;
1369 unsigned i, e,
j, f;
1388 if (
atEq(k,
j) != 0) {
1405 unsigned varLimit,
VarKind dstKind,
1407 assert(varLimit <=
getNumVarKind(srcKind) &&
"Invalid id range");
1409 if (varStart >= varLimit)
1413 unsigned convertCount = varLimit - varStart;
1414 unsigned newVarsBegin =
insertVar(dstKind, pos, convertCount);
1424 for (
unsigned i = 0; i < convertCount; ++i)
1425 swapVar(offset + varStart + i, newVarsBegin + i);
1432 const MPInt &value) {
1447 const MPInt &value) {
1451 for (
unsigned i = 0, e = expr.size(); i < e; ++i)
1463 const MPInt &divisor) {
1464 assert(dividend.size() ==
getNumCols() &&
"incorrect dividend size");
1465 assert(divisor > 0 &&
"positive divisor expected");
1470 dividendCopy.insert(dividendCopy.end() - 1,
MPInt(0));
1483 bool symbolic =
false) {
1484 assert(pos < cst.
getNumVars() &&
"invalid position");
1492 for (c = 0; c < f; c++) {
1495 if (cst.
atEq(r, c) != 0) {
1508 assert(pos <
getNumVars() &&
"invalid position");
1514 assert(
atEq(rowIdx, pos) *
atEq(rowIdx, pos) == 1);
1521 for (
unsigned s = pos, t = pos, e = pos + num; s < e; s++) {
1544 assert(pos <
getNumDimVars() &&
"Invalid variable position");
1555 [](
const MPInt &coeff) { return coeff == 0; }))
1556 return std::nullopt;
1572 (*ub)[c] = (*lb)[c];
1574 assert(boundFloorDivisor &&
1575 "both lb and divisor or none should be provided");
1576 *boundFloorDivisor = 1;
1593 return std::nullopt;
1606 std::optional<MPInt> minDiff;
1607 unsigned minLbPosition = 0, minUbPosition = 0;
1608 for (
auto ubPos : ubIndices) {
1609 for (
auto lbPos : lbIndices) {
1627 diff = std::max<MPInt>(diff,
MPInt(0));
1628 if (minDiff == std::nullopt || diff < minDiff) {
1630 minLbPosition = lbPos;
1631 minUbPosition = ubPos;
1635 if (lb && minDiff) {
1644 *boundFloorDivisor =
atIneq(minLbPosition, pos);
1645 assert(*boundFloorDivisor == -
atIneq(minUbPosition, pos));
1660 *minLbPos = minLbPosition;
1662 *minUbPos = minUbPosition;
1666 template <
bool isLower>
1667 std::optional<MPInt>
1669 assert(pos <
getNumVars() &&
"invalid position");
1687 return std::nullopt;
1689 std::optional<MPInt> minOrMaxConst;
1698 }
else if (
atIneq(r, 0) >= 0) {
1703 for (c = 0, f =
getNumCols() - 1; c < f; c++)
1704 if (c != 0 &&
atIneq(r, c) != 0)
1714 if (minOrMaxConst == std::nullopt || boundConst > minOrMaxConst)
1715 minOrMaxConst = boundConst;
1717 if (minOrMaxConst == std::nullopt || boundConst < minOrMaxConst)
1718 minOrMaxConst = boundConst;
1721 return minOrMaxConst;
1725 unsigned pos)
const {
1728 .computeConstantLowerOrUpperBound<
true>(pos);
1731 .computeConstantLowerOrUpperBound<
false>(pos);
1734 std::optional<MPInt> lb =
1737 std::optional<MPInt> ub =
1739 .computeConstantLowerOrUpperBound<
false>(pos);
1740 return (lb && ub && *lb == *ub) ? std::optional<MPInt>(*ub) : std::nullopt;
1749 for (
unsigned c = pos; c < pos + num; c++) {
1758 for (
unsigned c = pos; c < pos + num; c++) {
1759 if (
atEq(r, c) != 0)
1781 SmallDenseMap<ArrayRef<MPInt>, std::pair<unsigned, MPInt>>
1782 rowsWithoutConstTerm;
1784 SmallDenseSet<ArrayRef<MPInt>, 8> rowSet;
1787 auto isTriviallyValid = [&](
unsigned r) ->
bool {
1788 for (
unsigned c = 0, e =
getNumCols() - 1; c < e; c++) {
1800 if (isTriviallyValid(r) || !rowSet.insert(row).second) {
1801 redunIneq[r] =
true;
1812 rowsWithoutConstTerm.insert({rowWithoutConstTerm, {r, constTerm}});
1815 auto &val = ret.first->second;
1816 if (val.second > constTerm) {
1818 redunIneq[val.first] =
true;
1819 val = {r, constTerm};
1822 redunIneq[r] =
true;
1840 #define DEBUG_TYPE "fm"
1886 bool *isResultIntegerExact) {
1887 LLVM_DEBUG(llvm::dbgs() <<
"FM input (eliminate pos " << pos <<
"):\n");
1889 assert(pos <
getNumVars() &&
"invalid position");
1894 if (
atEq(r, pos) != 0) {
1898 assert(
succeeded(ret) &&
"Gaussian elimination guaranteed to succeed");
1899 LLVM_DEBUG(llvm::dbgs() <<
"FM output (through Gaussian elimination):\n");
1913 LLVM_DEBUG(llvm::dbgs() <<
"FM output:\n");
1923 std::vector<unsigned> nbIndices;
1930 if (
atIneq(r, pos) == 0) {
1932 nbIndices.push_back(r);
1933 }
else if (
atIneq(r, pos) >= 1) {
1935 lbIndices.push_back(r);
1938 ubIndices.push_back(r);
1945 newSpace.
removeVarRange(idKindRemove, relativePos, relativePos + 1);
1948 IntegerRelation newRel(lbIndices.size() * ubIndices.size() + nbIndices.size(),
1952 bool allLCMsAreOne =
true;
1964 for (
auto ubPos : ubIndices) {
1965 for (
auto lbPos : lbIndices) {
1974 for (
unsigned l = 0, e =
getNumCols(); l < e; l++) {
1977 assert(lbCoeff >= 1 && ubCoeff >= 1 &&
"bounds wrongly identified");
1979 ineq.push_back(
atIneq(ubPos, l) * (
lcm / ubCoeff) +
1981 assert(
lcm > 0 &&
"lcm should be positive!");
1983 allLCMsAreOne =
false;
1988 ineq[ineq.size() - 1] += lbCoeff * ubCoeff - lbCoeff - ubCoeff + 1;
1996 LLVM_DEBUG(llvm::dbgs() <<
"FM isResultIntegerExact: " << allLCMsAreOne
1998 if (allLCMsAreOne && isResultIntegerExact)
1999 *isResultIntegerExact =
true;
2002 for (
auto nbPos : nbIndices) {
2005 for (
unsigned l = 0, e =
getNumCols(); l < e; l++) {
2008 ineq.push_back(
atIneq(nbPos, l));
2014 lbIndices.size() * ubIndices.size() + nbIndices.size());
2020 for (
unsigned l = 0, e =
getNumCols(); l < e; l++) {
2023 eq.push_back(
atEq(r, l));
2034 LLVM_DEBUG(llvm::dbgs() <<
"FM output:\n");
2039 #define DEBUG_TYPE "presburger"
2047 assert(pos + num <
getNumCols() &&
"invalid range");
2050 unsigned currentPos = pos;
2051 unsigned numToEliminate = num;
2052 unsigned numGaussianEliminated = 0;
2055 unsigned curNumEliminated =
2058 numToEliminate -= curNumEliminated + 1;
2059 numGaussianEliminated += curNumEliminated;
2063 for (
unsigned i = 0; i < num - numGaussianEliminated; i++) {
2064 unsigned numToEliminate = num - numGaussianEliminated - i;
2078 enum BoundCmpResult { Greater, Less, Equal, Unknown };
2083 assert(a.size() == b.size());
2089 if (!std::equal(a.begin(), a.end() - 1, b.begin()))
2092 if (a.back() == b.back())
2095 return a.back() < b.back() ? Less : Greater;
2134 std::vector<SmallVector<MPInt, 8>> boundingLbs;
2135 std::vector<SmallVector<MPInt, 8>> boundingUbs;
2147 MPInt lbFloorDivisor, otherLbFloorDivisor;
2150 if (!extent.has_value())
2156 d, &otherLb, &otherLbFloorDivisor, &otherUb);
2157 if (!otherExtent.has_value() || lbFloorDivisor != otherLbFloorDivisor)
2161 assert(lbFloorDivisor > 0 &&
"divisor always expected to be positive");
2163 auto res = compareBounds(lb, otherLb);
2165 if (res == BoundCmpResult::Less || res == BoundCmpResult::Equal) {
2170 minLb.back() -= lbFloorDivisor - 1;
2171 }
else if (res == BoundCmpResult::Greater) {
2173 minLb.back() -= otherLbFloorDivisor - 1;
2178 if (!constLb.has_value() || !constOtherLb.has_value())
2180 std::fill(minLb.begin(), minLb.end(), 0);
2181 minLb.back() =
std::min(*constLb, *constOtherLb);
2185 auto uRes = compareBounds(ub, otherUb);
2186 if (uRes == BoundCmpResult::Greater || uRes == BoundCmpResult::Equal) {
2188 }
else if (uRes == BoundCmpResult::Less) {
2194 if (!constUb.has_value() || !constOtherUb.has_value())
2196 std::fill(maxUb.begin(), maxUb.end(), 0);
2197 maxUb.back() =
std::max(*constUb, *constOtherUb);
2200 std::fill(newLb.begin(), newLb.end(), 0);
2201 std::fill(newUb.begin(), newUb.end(), 0);
2205 newLb[d] = lbFloorDivisor;
2206 newUb[d] = -lbFloorDivisor;
2209 std::transform(newLb.begin() +
getNumDimVars(), newLb.end(),
2213 boundingLbs.push_back(newLb);
2214 boundingUbs.push_back(newUb);
2247 assert(pos < cst.
getNumVars() &&
"invalid start position");
2248 assert(pos + num <= cst.
getNumVars() &&
"invalid limit");
2253 for (c = pos; c < pos + num; ++c) {
2254 if (cst.
atIneq(r, c) != 0)
2258 nbIneqIndices.push_back(r);
2264 for (c = pos; c < pos + num; ++c) {
2265 if (cst.
atEq(r, c) != 0)
2269 nbEqIndices.push_back(r);
2274 assert(pos + num <=
getNumVars() &&
"invalid range");
2283 for (
auto nbIndex : llvm::reverse(nbIneqIndices))
2285 for (
auto nbIndex : llvm::reverse(nbEqIndices))
2304 bool changed =
false;
2305 SmallDenseMap<ArrayRef<MPInt>,
unsigned> hashTable;
2313 hashTable.insert({row, 0});
2314 for (
unsigned k = 1; k < ineqs; ++k) {
2316 if (!hashTable.contains(row)) {
2317 hashTable.insert({row, k});
2322 unsigned l = hashTable[row];
2333 for (
unsigned k = 0; k < ineqs; ++k) {
2335 negIneq.assign(row.begin(), row.end());
2336 for (
MPInt &ele : negIneq)
2338 if (!hashTable.contains(negIneq))
2343 unsigned l = hashTable[row];
2345 if (sum > 0 || l == k)
2380 "Domain set is not compatible with poly");
2396 "Range set is not compatible with poly");
2416 "Range of `this` should be compatible with Domain of `rel`");
2459 os <<
atEq(i,
j) <<
"\t";
2478 "Domain has to be zero in a set");
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static MPInt valueAt(ArrayRef< MPInt > expr, ArrayRef< MPInt > point)
Helper to evaluate an affine expression at a point.
static void getIndependentConstraints(const IntegerRelation &cst, unsigned pos, unsigned num, SmallVectorImpl< unsigned > &nbIneqIndices, SmallVectorImpl< unsigned > &nbEqIndices)
Find positions of inequalities and equalities that do not have a coefficient for [pos,...
static bool rangeIsZero(ArrayRef< MPInt > range)
static void removeConstraintsInvolvingVarRange(IntegerRelation &poly, unsigned begin, unsigned count)
static int findEqualityToConstant(const IntegerRelation &cst, unsigned pos, bool symbolic=false)
Finds an equality that equates the specified variable to a constant.
static unsigned getBestVarToEliminate(const IntegerRelation &cst, unsigned start, unsigned end)
Returns the position of the variable that has the minimum <number of lower bounds> times <number of u...
static void getCommonConstraints(const IntegerRelation &a, const IntegerRelation &b, IntegerRelation &c)
static void eliminateFromConstraint(IntegerRelation *constraints, unsigned rowIdx, unsigned pivotRow, unsigned pivotCol, unsigned elimColStart, bool isEq)
Eliminate variable from constraint at rowIdx based on coefficient at pivotRow, pivotCol.
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
Class storing division representation of local variables of a constraint system.
void removeDuplicateDivs(llvm::function_ref< bool(unsigned i, unsigned j)> merge)
Removes duplicate divisions.
MPInt & getDenom(unsigned i)
void clearRepr(unsigned i)
MutableArrayRef< MPInt > getDividend(unsigned i)
MPInt normalizeRow(unsigned row, unsigned nCols)
Divide the first nCols of the specified row by their GCD.
An IntegerPolyhedron represents the set of points from a PresburgerSpace that satisfy a list of affin...
IntegerPolyhedron intersect(const IntegerPolyhedron &other) const
Return the intersection of the two relations.
unsigned insertVar(VarKind kind, unsigned pos, unsigned num=1) override
Insert num variables of the specified kind at position pos.
PresburgerSet subtract(const PresburgerSet &other) const
Return the set difference of this set and the given set, i.e., return this \ set.
IntegerPolyhedron(unsigned numReservedInequalities, unsigned numReservedEqualities, unsigned numReservedCols, const PresburgerSpace &space)
Constructs a set reserving memory for the specified number of constraints and variables.
std::unique_ptr< IntegerPolyhedron > clone() const
An IntegerRelation represents the set of points from a PresburgerSpace that satisfy a list of affine ...
virtual void swapVar(unsigned posA, unsigned posB)
Swap the posA^th variable with the posB^th variable.
MPInt atEq(unsigned i, unsigned j) const
Returns the value at the specified equality row and column.
void removeIndependentConstraints(unsigned pos, unsigned num)
Removes constraints that are independent of (i.e., do not have a coefficient) variables in the range ...
ArrayRef< MPInt > getEquality(unsigned idx) const
void compose(const IntegerRelation &rel)
Let the relation this be R1, and the relation rel be R2.
void applyRange(const IntegerRelation &rel)
Given a relation rel, apply the relation to the range of this relation.
unsigned getVarKindEnd(VarKind kind) const
Return the index at Which the specified kind of vars ends.
void addInequality(ArrayRef< MPInt > inEq)
Adds an inequality (>= 0) from the coefficients specified in inEq.
std::optional< MPInt > getConstantBound(BoundType type, unsigned pos) const
Returns the constant bound for the pos^th variable if there is one; std::nullopt otherwise.
void removeTrivialRedundancy()
Removes duplicate constraints, trivially true constraints, and constraints that can be detected as re...
static IntegerRelation getEmpty(const PresburgerSpace &space)
Return an empty system containing an invalid equation 0 = 1.
void addEquality(ArrayRef< MPInt > eq)
Adds an equality from the coefficients specified in eq.
void removeInequalityRange(unsigned start, unsigned end)
void normalizeConstraintsByGCD()
Normalized each constraints by the GCD of its coefficients.
void truncate(const CountsSnapshot &counts)
virtual void eliminateRedundantLocalVar(unsigned posA, unsigned posB)
Eliminate the posB^th local variable, replacing every instance of it with the posA^th local variable.
CountsSnapshot getCounts() const
void removeEqualityRange(unsigned start, unsigned end)
Remove the (in)equalities at positions [start, end).
std::optional< MPInt > computeVolume() const
Compute an overapproximation of the number of integer points in the relation.
LogicalResult constantFoldVar(unsigned pos)
Tries to fold the specified variable to a constant using a trivial equality detection; if successful,...
unsigned getNumSymbolVars() const
void removeEquality(unsigned pos)
bool isObviouslyEqual(const IntegerRelation &other) const
Perform a quick equality check on this and other.
IntegerPolyhedron getRangeSet() const
Return a set corresponding to all points in the range of the relation.
unsigned getNumVarKind(VarKind kind) const
Get the number of vars of the specified kind.
bool isEmptyByGCDTest() const
Runs the GCD test on all equality constraints.
void simplify()
Simplify the constraint system by removing canonicalizing constraints and removing redundant constrai...
void convertVarKind(VarKind srcKind, unsigned varStart, unsigned varLimit, VarKind dstKind, unsigned pos)
Converts variables of kind srcKind in the range [varStart, varLimit) to variables of kind dstKind.
void removeDuplicateDivs()
unsigned appendVar(VarKind kind, unsigned num=1)
Append num variables of the specified kind after the last variable of that kind.
void intersectRange(const IntegerPolyhedron &poly)
Intersect the given poly with the range in-place.
void print(raw_ostream &os) const
bool isIntegerEmpty() const
Returns true if the set of constraints is found to have no solution, false if a solution exists.
std::optional< SmallVector< MPInt, 8 > > findIntegerSample() const
Find an integer sample point satisfying the constraints using a branch and bound algorithm with gener...
MaybeOptimum< SmallVector< MPInt, 8 > > findIntegerLexMin() const
Same as above, but returns lexicographically minimal integer point.
virtual unsigned insertVar(VarKind kind, unsigned pos, unsigned num=1)
Insert num variables of the specified kind at position pos.
bool hasInvalidConstraint() const
Checks all rows of equality/inequality constraints for trivial contradictions (for example: 1 == 0,...
LogicalResult unionBoundingBox(const IntegerRelation &other)
Updates the constraints to be the smallest bounding (enclosing) box that contains the points of this ...
IntegerRelation(unsigned numReservedInequalities, unsigned numReservedEqualities, unsigned numReservedCols, const PresburgerSpace &space)
Constructs a relation reserving memory for the specified number of constraints and variables.
bool isHyperRectangular(unsigned pos, unsigned num) const
Returns true if the set can be trivially detected as being hyper-rectangular on the specified contigu...
IntMatrix getBoundedDirections() const
Returns a matrix where each row is a vector along which the polytope is bounded.
unsigned getNumDomainVars() const
LogicalResult gaussianEliminateVar(unsigned position)
Eliminates a single variable at position from equality and inequality constraints.
void clearConstraints()
Removes all equalities and inequalities.
IntegerRelation intersect(IntegerRelation other) const
Return the intersection of the two relations.
void addLocalFloorDiv(ArrayRef< MPInt > dividend, const MPInt &divisor)
Adds a new local variable as the floordiv of an affine function of other variables,...
ArrayRef< MPInt > getInequality(unsigned idx) const
SymbolicLexOpt findSymbolicIntegerLexMin() const
Compute the symbolic integer lexmin of the relation.
void setSpace(const PresburgerSpace &oSpace)
Set the space to oSpace, which should have the same number of ids as the current space.
std::optional< SmallVector< MPInt, 8 > > containsPointNoLocal(ArrayRef< MPInt > point) const
Given the values of non-local vars, return a satisfying assignment to the local if one exists,...
MPInt atIneq(unsigned i, unsigned j) const
Returns the value at the specified inequality row and column.
unsigned getNumVars() const
void inverse()
Invert the relation i.e., swap its domain and range.
void append(const IntegerRelation &other)
Appends constraints from other into this.
void applyDomain(const IntegerRelation &rel)
Given a relation rel, apply the relation to the domain of this relation.
void intersectDomain(const IntegerPolyhedron &poly)
Intersect the given poly with the domain in-place.
PresburgerRelation subtract(const PresburgerRelation &set) const
Return the set difference of this set and the given set, i.e., return this \ set.
bool isEqual(const IntegerRelation &other) const
Return whether this and other are equal.
virtual void printSpace(raw_ostream &os) const
Prints the number of constraints, dimensions, symbols and locals in the IntegerRelation.
unsigned getNumRangeVars() const
unsigned getNumLocalVars() const
void removeRedundantConstraints()
Removes redundant constraints using Simplex.
PresburgerRelation computeReprWithOnlyDivLocals() const
Compute an equivalent representation of the same set, such that all local vars in all disjuncts have ...
void removeRedundantInequalities()
A more expensive check than removeTrivialRedundancy to detect redundant inequalities.
bool isObviouslyEmpty() const
Performs GCD checks and invalid constraint checks.
IntMatrix equalities
Coefficients of affine equalities (in == 0 form).
SymbolicLexOpt findSymbolicIntegerLexMax() const
Same as findSymbolicIntegerLexMin but produces lexmax instead of lexmin.
unsigned getNumDimAndSymbolVars() const
bool gaussianEliminate()
Perform a Gaussian elimination operation to reduce all equations to standard form.
void truncateVarKind(VarKind kind, unsigned num)
Truncate the vars of the specified kind to the specified number by dropping some vars at the end.
void constantFoldVarRange(unsigned pos, unsigned num)
This method calls constantFoldVar for the specified range of variables, num variables starting at pos...
std::optional< MPInt > getConstantBoundOnDimSize(unsigned pos, SmallVectorImpl< MPInt > *lb=nullptr, MPInt *boundFloorDivisor=nullptr, SmallVectorImpl< MPInt > *ub=nullptr, unsigned *minLbPos=nullptr, unsigned *minUbPos=nullptr) const
Returns the smallest known constant bound for the extent of the specified variable (pos^th),...
bool isEmpty() const
Checks for emptiness by performing variable elimination on all variables, running the GCD test on eac...
unsigned getNumCols() const
Returns the number of columns in the constraint system.
void getLowerAndUpperBoundIndices(unsigned pos, SmallVectorImpl< unsigned > *lbIndices, SmallVectorImpl< unsigned > *ubIndices, SmallVectorImpl< unsigned > *eqIndices=nullptr, unsigned offset=0, unsigned num=0) const
Gather positions of all lower and upper bounds of the variable at pos, and optionally any equalities ...
void gcdTightenInequalities()
Tightens inequalities given that we are dealing with integer spaces.
void removeVar(VarKind kind, unsigned pos)
Removes variables of the specified kind with the specified pos (or within the specified range) from t...
void setSpaceExceptLocals(const PresburgerSpace &oSpace)
Set the space to oSpace, which should not have any local ids.
unsigned gaussianEliminateVars(unsigned posStart, unsigned posLimit)
Eliminates variables from equality and inequality constraints in column range [posStart,...
void removeInequality(unsigned pos)
void addBound(BoundType type, unsigned pos, const MPInt &value)
Adds a constant bound for the specified variable.
IntegerPolyhedron getDomainSet() const
Return a set corresponding to all points in the domain of the relation.
DivisionRepr getLocalReprs(std::vector< MaybeLocalRepr > *repr=nullptr) const
Returns a DivisonRepr representing the division representation of local variables in the constraint s...
bool hasOnlyDivLocals() const
Check whether all local ids have a division representation.
constexpr static unsigned kExplosionFactor
A parameter that controls detection of an unrealistic number of constraints.
void setAndEliminate(unsigned pos, ArrayRef< MPInt > values)
Sets the values.size() variables starting at pos to the specified values and removes them.
virtual void clearAndCopyFrom(const IntegerRelation &other)
Replaces the contents of this IntegerRelation with other.
void projectOut(unsigned pos, unsigned num)
Projects out (aka eliminates) num variables starting at position pos.
std::optional< MPInt > computeConstantLowerOrUpperBound(unsigned pos)
Returns the constant lower bound if isLower is true, and the upper bound if isLower is false.
void removeRedundantLocalVars()
Removes local variables using equalities.
unsigned mergeLocalVars(IntegerRelation &other)
Adds additional local vars to the sets such that they both have the union of the local vars in each s...
unsigned getNumConstraints() const
MaybeOptimum< SmallVector< Fraction, 8 > > findRationalLexMin() const
Get the lexicographically minimum rational point satisfying the constraints.
IntMatrix inequalities
Coefficients of affine inequalities (in >= 0 form).
virtual bool hasConsistentState() const
Returns false if the fields corresponding to various variable counts, or equality/inequality buffer s...
unsigned getNumInequalities() const
bool findConstraintWithNonZeroAt(unsigned colIdx, bool isEq, unsigned *rowIdx) const
Searches for a constraint with a non-zero coefficient at colIdx in equality (isEq=true) or inequality...
bool isSubsetOf(const IntegerRelation &other) const
Return whether this is a subset of the given IntegerRelation.
std::unique_ptr< IntegerRelation > clone() const
const PresburgerSpace & getSpace() const
Returns a reference to the underlying space.
bool containsPoint(ArrayRef< MPInt > point) const
Returns true if the given point satisfies the constraints, or false otherwise.
unsigned getNumEqualities() const
bool isColZero(unsigned pos) const
Returns true if the pos^th column is all zero for both inequalities and equalities.
unsigned getVarKindOffset(VarKind kind) const
Return the index at which the specified kind of vars starts.
unsigned getNumDimVars() const
virtual void removeVarRange(VarKind kind, unsigned varStart, unsigned varLimit)
virtual void fourierMotzkinEliminate(unsigned pos, bool darkShadow=false, bool *isResultIntegerExact=nullptr)
Eliminates the variable at the specified position using Fourier-Motzkin variable elimination,...
bool removeDuplicateConstraints()
Checks for identical inequalities and eliminates redundant inequalities.
A class for lexicographic optimization without any symbols.
MaybeOptimum< SmallVector< MPInt, 8 > > findIntegerLexMin()
Return the lexicographically minimum integer solution to the constraints.
MaybeOptimum< SmallVector< Fraction, 8 > > findRationalLexMin()
Return the lexicographically minimum rational solution to the constraints.
This class provides support for multi-precision arithmetic.
bool hasConsistentState() const
Return whether the Matrix is in a consistent state with all its invariants satisfied.
unsigned getNumRows() const
void swapColumns(unsigned column, unsigned otherColumn)
Swap the given columns.
unsigned appendExtraRow()
Add an extra row at the bottom of the matrix and return its position.
void addToColumn(unsigned sourceColumn, unsigned targetColumn, const T &scale)
Add scale multiples of the source column to the target column.
void copyRow(unsigned sourceRow, unsigned targetRow)
void removeColumns(unsigned pos, unsigned count)
Remove the columns having positions pos, pos + 1, ...
void insertColumns(unsigned pos, unsigned count)
Insert columns having positions pos, pos + 1, ...
void removeRow(unsigned pos)
void resizeVertically(unsigned newNRows)
void swapRows(unsigned row, unsigned otherRow)
Swap the given rows.
void reserveRows(unsigned rows)
Reserve enough space to resize to the specified number of rows without reallocations.
void fillRow(unsigned row, const T &value)
void negateRow(unsigned row)
Negate the specified row.
void removeRows(unsigned pos, unsigned count)
Remove the rows having positions pos, pos + 1, ...
OptimumKind getKind() const
This class represents a multi-affine function with the domain as Z^d, where d is the number of domain...
const PresburgerSpace & getSpace() const
void removeOutputs(unsigned start, unsigned end)
Remove the specified range of outputs.
unsigned getNumOutputs() const
ArrayRef< Piece > getAllPieces() const
Return all the pieces of this piece-wise function.
PresburgerSet getDomain() const
Return the domain of this piece-wise MultiAffineFunction.
A PresburgerRelation represents a union of IntegerRelations that live in the same PresburgerSpace wit...
void setSpace(const PresburgerSpace &oSpace)
Set the space to oSpace.
PresburgerRelation subtract(const PresburgerRelation &set) const
Return the set difference of this set and the given set, i.e., return this \ set.
bool isSubsetOf(const PresburgerRelation &set) const
Return true if this set is a subset of the given set, and false otherwise.
bool isEqual(const PresburgerRelation &set) const
Return true if this set is equal to the given set, and false otherwise.
PresburgerSet unionSet(const PresburgerRelation &set) const
These operations are the same as the ones in PresburgeRelation, they just forward the arguement and r...
PresburgerSpace is the space of all possible values of a tuple of integer valued variables/variables.
unsigned getNumVarKind(VarKind kind) const
Get the number of vars of the specified kind.
bool isEqual(const PresburgerSpace &other) const
Returns true if both the spaces are equal including local variables i.e.
void removeVarRange(VarKind kind, unsigned varStart, unsigned varLimit)
Removes variables of the specified kind in the column range [varStart, varLimit).
unsigned getVarKindOffset(VarKind kind) const
Return the index at which the specified kind of var starts.
unsigned getNumVars() const
unsigned getNumLocalVars() const
VarKind getVarKindAt(unsigned pos) const
Return the VarKind of the var at the specified position.
static PresburgerSpace getSetSpace(unsigned numDims=0, unsigned numSymbols=0, unsigned numLocals=0)
bool isCompatible(const PresburgerSpace &other) const
Returns true if both the spaces are compatible i.e.
void print(llvm::raw_ostream &os) const
static PresburgerSpace getRelationSpace(unsigned numDomain=0, unsigned numRange=0, unsigned numSymbols=0, unsigned numLocals=0)
unsigned insertVar(VarKind kind, unsigned pos, unsigned num=1)
Insert num variables of the specified kind at position pos.
bool isEmpty() const
Returns true if the tableau is empty (has conflicting constraints), false otherwise.
The Simplex class uses the Normal pivot rule and supports integer emptiness checks as well as detecti...
bool isMarkedRedundant(unsigned constraintIndex) const
Returns whether the specified constraint has been marked as redundant.
std::optional< SmallVector< MPInt, 8 > > findIntegerSample()
Returns an integer sample point if one exists, or std::nullopt otherwise.
std::pair< MaybeOptimum< MPInt >, MaybeOptimum< MPInt > > computeIntegerBounds(ArrayRef< MPInt > coeffs)
Returns a (min, max) pair denoting the minimum and maximum integer values of the given expression.
bool isBoundedAlongConstraint(unsigned constraintIndex)
Returns whether the perpendicular of the specified constraint is a is a direction along which the pol...
bool isUnbounded()
Returns true if the polytope is unbounded, i.e., extends to infinity in some direction.
void detectRedundant(unsigned offset, unsigned count)
Finds a subset of constraints that is redundant, i.e., such that the set of solutions does not change...
std::optional< SmallVector< Fraction, 8 > > getRationalSample() const
Returns the current sample point, which may contain non-integer (rational) coordinates.
A class to perform symbolic lexicographic optimization, i.e., to find, for every assignment to the sy...
SymbolicLexOpt computeSymbolicIntegerLexMin()
The lexmin will be stored as a function lexopt from symbols to non-symbols in the result.
BoundType
The type of bound: equal, lower bound or upper bound.
LLVM_ATTRIBUTE_ALWAYS_INLINE MPInt gcd(const MPInt &a, const MPInt &b)
SmallVector< MPInt, 8 > getDivLowerBound(ArrayRef< MPInt > dividend, const MPInt &divisor, unsigned localVarIdx)
LLVM_ATTRIBUTE_ALWAYS_INLINE MPInt ceilDiv(const MPInt &lhs, const MPInt &rhs)
SmallVector< MPInt, 8 > getDivUpperBound(ArrayRef< MPInt > dividend, const MPInt &divisor, unsigned localVarIdx)
If q is defined to be equal to expr floordiv d, this equivalent to saying that q is an integer and q ...
void mergeLocalVars(IntegerRelation &relA, IntegerRelation &relB, llvm::function_ref< bool(unsigned i, unsigned j)> merge)
Given two relations, A and B, add additional local vars to the sets such that both have the union of ...
LLVM_ATTRIBUTE_ALWAYS_INLINE MPInt abs(const MPInt &x)
MaybeLocalRepr computeSingleVarRepr(const IntegerRelation &cst, ArrayRef< bool > foundRepr, unsigned pos, MutableArrayRef< MPInt > dividend, MPInt &divisor)
Returns the MaybeLocalRepr struct which contains the indices of the constraints that can be expressed...
MPInt ceil(const Fraction &f)
LLVM_ATTRIBUTE_ALWAYS_INLINE MPInt lcm(const MPInt &a, const MPInt &b)
Returns the least common multiple of 'a' and 'b'.
LLVM_ATTRIBUTE_ALWAYS_INLINE MPInt floorDiv(const MPInt &lhs, const MPInt &rhs)
Include the generated interface declarations.
LogicalResult failure(bool isFailure=true)
Utility function to generate a LogicalResult.
bool succeeded(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a success value.
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
bool failed(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a failure value.
This class represents an efficient way to signal success or failure.
The struct CountsSnapshot stores the count of each VarKind, and also of each constraint type.
const PresburgerSpace & getSpace() const
unsigned getNumIneqs() const
unsigned getNumEqs() const
MaybeLocalRepr contains the indices of the constraints that can be expressed as a floordiv of an affi...
Represents the result of a symbolic lexicographic optimization computation.
PWMAFunction lexopt
This maps assignments of symbols to the corresponding lexopt.
PresburgerSet unboundedDomain
Contains all assignments to the symbols that made the lexopt unbounded.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.