23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/Sequence.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/LogicalResult.h"
30 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "presburger"
45 using namespace presburger;
47 using llvm::SmallDenseMap;
48 using llvm::SmallDenseSet;
51 return std::make_unique<IntegerRelation>(*
this);
55 return std::make_unique<IntegerPolyhedron>(*
this);
64 assert(oSpace.
getNumLocalVars() == 0 &&
"no locals should be present!");
73 "space must be using identifiers to set an identifier");
74 assert(kind !=
VarKind::Local &&
"local variables cannot have identifiers");
122 for (
unsigned j = 0;
j <
cols; ++
j) {
128 for (
unsigned j = 0;
j <
cols; ++
j) {
156 "Incorrect number of vars in lexMin!");
176 "Incorrect number of vars in lexMin!");
182 return llvm::all_of(range, [](
const DynamicAPInt &x) {
return x == 0; });
186 unsigned begin,
unsigned count) {
205 assert(num <= curNum &&
"Can't truncate to more vars!");
234 copy.getLocalReprs(&reprs);
238 unsigned numNonDivLocals = 0;
240 for (
unsigned i = 0, e =
copy.getNumLocalVars(); i < e - numNonDivLocals;) {
245 copy.swapVar(offset + i, offset + e - numNonDivLocals - 1);
246 std::swap(reprs[i], reprs[e - numNonDivLocals - 1]);
254 if (numNonDivLocals == 0)
271 copy.getNumVars() - numNonDivLocals)))
288 llvm::SmallBitVector isSymbol(
getNumVars(),
false);
332 symbolicIntegerLexMax(
335 for (
auto &flippedPiece :
337 IntMatrix mat = flippedPiece.output.getOutputMatrix();
338 for (
unsigned i = 0, e = mat.
getNumRows(); i < e; i++)
342 symbolicIntegerLexMax.lexopt.addPiece(piece);
344 symbolicIntegerLexMax.unboundedDomain =
346 return symbolicIntegerLexMax;
371 for (
unsigned i = 0, e = eq.size(); i < e; ++i)
378 for (
unsigned i = 0, e = inEq.size(); i < e; ++i)
392 if (varStart >= varLimit)
407 if (varStart >= varLimit)
413 auto removeVarKindInRange = [
this](
VarKind kind,
unsigned &start,
422 unsigned relativeStart =
423 start <= offset ? 0 :
std::min(num, start - offset);
424 unsigned relativeLimit =
425 limit <= offset ? 0 :
std::min(num, limit - offset);
433 limit -= relativeLimit - relativeStart;
463 assert(posA <
getNumVars() &&
"invalid position A");
464 assert(posB <
getNumVars() &&
"invalid position B");
473 space.
swapVar(kindA, kindB, relativePosA, relativePosB);
490 unsigned offset,
unsigned num)
const {
491 assert(pos <
getNumVars() &&
"invalid position");
492 assert(offset + num <
getNumCols() &&
"invalid range");
496 auto containsConstraintDependentOnRange = [&](
unsigned r,
bool isEq) {
499 for (c = offset, f = offset + num; c < f; ++c) {
513 if (containsConstraintDependentOnRange(r,
false))
515 if (
atIneq(r, pos) >= 1) {
517 lbIndices->emplace_back(r);
518 }
else if (
atIneq(r, pos) <= -1) {
520 ubIndices->emplace_back(r);
530 if (
atEq(r, pos) == 0)
532 if (containsConstraintDependentOnRange(r,
true))
534 eqIndices->emplace_back(r);
551 "invalid position or too many values");
556 for (
unsigned i = 0, numVals = values.size(); i < numVals; ++i)
558 for (
unsigned i = 0, numVals = values.size(); i < numVals; ++i)
571 unsigned *rowIdx)
const {
572 assert(colIdx <
getNumCols() &&
"position out of bounds");
573 auto at = [&](
unsigned rowIdx) -> DynamicAPInt {
574 return isEq ?
atEq(rowIdx, colIdx) :
atIneq(rowIdx, colIdx);
577 for (*rowIdx = 0; *rowIdx < e; ++(*rowIdx)) {
578 if (at(*rowIdx) != 0) {
594 auto check = [&](
bool isEq) ->
bool {
597 for (
unsigned i = 0, e = numRows; i < e; ++i) {
599 for (
j = 0;
j < numCols - 1; ++
j) {
605 if (
j < numCols - 1) {
610 DynamicAPInt v = isEq ?
atEq(i, numCols - 1) :
atIneq(i, numCols - 1);
611 if ((isEq && v != 0) || (!isEq && v < 0)) {
626 unsigned rowIdx,
unsigned pivotRow,
627 unsigned pivotCol,
unsigned elimColStart,
630 if (isEq && rowIdx == pivotRow)
632 auto at = [&](
unsigned i,
unsigned j) -> DynamicAPInt {
633 return isEq ? constraints->
atEq(i,
j) : constraints->
atIneq(i,
j);
635 DynamicAPInt leadCoeff = at(rowIdx, pivotCol);
639 DynamicAPInt pivotCoeff = constraints->
atEq(pivotRow, pivotCol);
640 int sign = (leadCoeff * pivotCoeff > 0) ? -1 : 1;
641 DynamicAPInt lcm = llvm::lcm(pivotCoeff, leadCoeff);
642 DynamicAPInt pivotMultiplier = sign * (lcm /
abs(pivotCoeff));
643 DynamicAPInt rowMultiplier = lcm /
abs(leadCoeff);
646 for (
unsigned j = 0;
j < numCols; ++
j) {
648 if (
j >= elimColStart &&
j < pivotCol)
650 DynamicAPInt v = pivotMultiplier * constraints->
atEq(pivotRow,
j) +
651 rowMultiplier * at(rowIdx,
j);
652 isEq ? constraints->
atEq(rowIdx,
j) = v
653 : constraints->
atIneq(rowIdx,
j) = v;
663 unsigned start,
unsigned end) {
666 auto getProductOfNumLowerUpperBounds = [&](
unsigned pos) {
670 if (cst.
atIneq(r, pos) > 0) {
672 }
else if (cst.
atIneq(r, pos) < 0) {
676 return numLb * numUb;
679 unsigned minLoc = start;
680 unsigned min = getProductOfNumLowerUpperBounds(start);
681 for (
unsigned c = start + 1; c < end; c++) {
682 unsigned numLbUbProduct = getProductOfNumLowerUpperBounds(c);
683 if (numLbUbProduct <
min) {
684 min = numLbUbProduct;
707 unsigned currentPos = 0;
720 for (
unsigned i = 0, e = tmpCst.
getNumVars(); i < e; i++) {
729 LLVM_DEBUG(llvm::dbgs() <<
"FM constraint explosion detected\n");
763 DynamicAPInt gcd =
abs(
atEq(i, 0));
764 for (
unsigned j = 1;
j < numCols - 1; ++
j) {
765 gcd = llvm::gcd(gcd,
abs(
atEq(i,
j)));
767 DynamicAPInt v =
abs(
atEq(i, numCols - 1));
768 if (gcd > 0 && (v % gcd != 0)) {
789 assert(!simplex.
isEmpty() &&
"It is not meaningful to ask whether a "
790 "direction is bounded in an empty set.");
797 boundedIneqs.emplace_back(i);
807 for (
unsigned i : boundedIneqs) {
808 for (
unsigned col = 0; col < dirsNumCols; ++col)
809 dirs(row, col) =
atIneq(i, col);
815 for (
unsigned col = 0; col < dirsNumCols; ++col)
816 dirs(row, col) =
atEq(i, col);
870 std::optional<SmallVector<DynamicAPInt, 8>>
894 std::pair<unsigned, LinearTransform> result =
903 unsigned numBoundedDims = result.first;
904 unsigned numUnboundedDims =
getNumVars() - numBoundedDims;
910 std::optional<SmallVector<DynamicAPInt, 8>> boundedSample =
915 "Simplex returned an invalid sample!");
949 DynamicAPInt coeff = cone.
atIneq(i,
j);
959 Simplex shrunkenConeSimplex(cone);
960 assert(!shrunkenConeSimplex.
isEmpty() &&
"Shrunken cone cannot be empty!");
967 llvm::map_range(shrunkenConeSample,
ceil));
971 sample.append(coneSample.begin(), coneSample.end());
980 assert(expr.size() == 1 + point.size() &&
981 "Dimensionalities of point and expression don't match!");
982 DynamicAPInt value = expr.back();
983 for (
unsigned i = 0; i < point.size(); ++i)
984 value += expr[i] * point[i];
1011 std::optional<SmallVector<DynamicAPInt, 8>>
1014 "Point should contain all vars except locals!");
1016 "This function depends on locals being stored last!");
1018 copy.setAndEliminate(0, point);
1019 return copy.findIntegerSample();
1026 foundRepr[i] =
true;
1036 if (!foundRepr[i + localOffset]) {
1046 foundRepr[localOffset + i] =
true;
1071 atIneq(i, numCols - 1) = floorDiv(
atIneq(i, numCols - 1), gcd);
1078 unsigned posLimit) {
1083 if (posStart >= posLimit)
1088 unsigned pivotCol = 0;
1089 for (pivotCol = posStart; pivotCol < posLimit; ++pivotCol) {
1119 posLimit = pivotCol;
1122 return posLimit - posStart;
1128 unsigned nowDone, eqs, pivotRow;
1131 for (; firstVar < vars; ++firstVar) {
1137 if (firstVar >= vars)
1141 if (pivotRow > nowDone) {
1147 for (
unsigned i = nowDone + 1; i < eqs; ++i) {
1164 for (
unsigned i = nowDone; i < eqs; ++i) {
1165 if (
atEq(i, vars) == 0)
1222 for (
unsigned r = 0; r < numIneqs; r++) {
1248 return DynamicAPInt(0);
1264 DynamicAPInt count(1);
1266 bool hasUnboundedVar =
false;
1272 assert((!
min.isEmpty() && !
max.isEmpty()) &&
1273 "Polytope should be rationally non-empty!");
1277 if (
min.isUnbounded() ||
max.isUnbounded()) {
1278 hasUnboundedVar =
true;
1284 if (
min.getBoundedOptimum() >
max.getBoundedOptimum())
1285 return DynamicAPInt(0);
1287 count *= (*
max - *
min + 1);
1291 return DynamicAPInt(0);
1292 if (hasUnboundedVar)
1302 posA += localOffset;
1303 posB += localOffset;
1316 "both relations need to have identifers to merge and align");
1325 const Identifier *itr = std::find(findBegin, findEnd, identifier);
1326 if (itr != findEnd) {
1329 std::distance(findBegin, itr));
1364 auto merge = [&relA, &relB, oldALocals](
unsigned i,
unsigned j) ->
bool {
1393 auto merge = [
this](
unsigned i,
unsigned j) ->
bool {
1401 bool changed =
true;
1427 unsigned i, e,
j, f;
1446 if (
atEq(k,
j) != 0) {
1463 unsigned varLimit,
VarKind dstKind,
1465 assert(varLimit <=
getNumVarKind(srcKind) &&
"invalid id range");
1467 if (varStart >= varLimit)
1472 unsigned convertCount = varLimit - varStart;
1473 int forwardMoveOffset = dstOffset > srcOffset ? -convertCount : 0;
1476 dstOffset + pos + forwardMoveOffset);
1478 dstOffset + pos + forwardMoveOffset);
1484 const DynamicAPInt &value) {
1499 const DynamicAPInt &value) {
1503 for (
unsigned i = 0, e = expr.size(); i < e; ++i)
1515 const DynamicAPInt &divisor) {
1516 assert(dividend.size() ==
getNumCols() &&
"incorrect dividend size");
1517 assert(divisor > 0 &&
"positive divisor expected");
1522 dividendCopy.insert(dividendCopy.end() - 1, DynamicAPInt(0));
1535 bool symbolic =
false) {
1536 assert(pos < cst.
getNumVars() &&
"invalid position");
1538 DynamicAPInt v = cst.
atEq(r, pos);
1544 for (c = 0; c < f; c++) {
1547 if (cst.
atEq(r, c) != 0) {
1560 assert(pos <
getNumVars() &&
"invalid position");
1566 assert(
atEq(rowIdx, pos) *
atEq(rowIdx, pos) == 1);
1573 for (
unsigned s = pos, t = pos, e = pos + num; s < e; s++) {
1596 unsigned *minLbPos,
unsigned *minUbPos)
const {
1597 assert(pos <
getNumDimVars() &&
"Invalid variable position");
1608 [](
const DynamicAPInt &coeff) { return coeff == 0; }))
1609 return std::nullopt;
1618 DynamicAPInt v =
atEq(eqPos, pos);
1625 (*ub)[c] = (*lb)[c];
1627 assert(boundFloorDivisor &&
1628 "both lb and divisor or none should be provided");
1629 *boundFloorDivisor = 1;
1635 return DynamicAPInt(1);
1646 return std::nullopt;
1659 std::optional<DynamicAPInt> minDiff;
1660 unsigned minLbPosition = 0, minUbPosition = 0;
1661 for (
auto ubPos : ubIndices) {
1662 for (
auto lbPos : lbIndices) {
1680 diff = std::max<DynamicAPInt>(diff, DynamicAPInt(0));
1681 if (minDiff == std::nullopt || diff < minDiff) {
1683 minLbPosition = lbPos;
1684 minUbPosition = ubPos;
1688 if (lb && minDiff) {
1697 *boundFloorDivisor =
atIneq(minLbPosition, pos);
1698 assert(*boundFloorDivisor == -
atIneq(minUbPosition, pos));
1713 *minLbPos = minLbPosition;
1715 *minUbPos = minUbPosition;
1719 template <
bool isLower>
1720 std::optional<DynamicAPInt>
1722 assert(pos <
getNumVars() &&
"invalid position");
1740 return std::nullopt;
1742 std::optional<DynamicAPInt> minOrMaxConst;
1751 }
else if (
atIneq(r, 0) >= 0) {
1756 for (c = 0, f =
getNumCols() - 1; c < f; c++)
1757 if (c != 0 &&
atIneq(r, c) != 0)
1763 DynamicAPInt boundConst =
1767 if (minOrMaxConst == std::nullopt || boundConst > minOrMaxConst)
1768 minOrMaxConst = boundConst;
1770 if (minOrMaxConst == std::nullopt || boundConst < minOrMaxConst)
1771 minOrMaxConst = boundConst;
1774 return minOrMaxConst;
1777 std::optional<DynamicAPInt>
1781 .computeConstantLowerOrUpperBound<
true>(pos);
1784 .computeConstantLowerOrUpperBound<
false>(pos);
1787 std::optional<DynamicAPInt> lb =
1790 std::optional<DynamicAPInt> ub =
1792 .computeConstantLowerOrUpperBound<
false>(pos);
1793 return (lb && ub && *lb == *ub) ? std::optional<DynamicAPInt>(*ub)
1803 for (
unsigned c = pos; c < pos + num; c++) {
1812 for (
unsigned c = pos; c < pos + num; c++) {
1813 if (
atEq(r, c) != 0)
1835 SmallDenseMap<ArrayRef<DynamicAPInt>, std::pair<unsigned, DynamicAPInt>>
1836 rowsWithoutConstTerm;
1838 SmallDenseSet<ArrayRef<DynamicAPInt>, 8> rowSet;
1841 auto isTriviallyValid = [&](
unsigned r) ->
bool {
1842 for (
unsigned c = 0, e =
getNumCols() - 1; c < e; c++) {
1854 if (isTriviallyValid(r) || !rowSet.insert(row).second) {
1855 redunIneq[r] =
true;
1864 auto rowWithoutConstTerm =
1867 rowsWithoutConstTerm.insert({rowWithoutConstTerm, {r, constTerm}});
1870 auto &val = ret.first->second;
1871 if (val.second > constTerm) {
1873 redunIneq[val.first] =
true;
1874 val = {r, constTerm};
1877 redunIneq[r] =
true;
1895 #define DEBUG_TYPE "fm"
1941 bool *isResultIntegerExact) {
1942 LLVM_DEBUG(llvm::dbgs() <<
"FM input (eliminate pos " << pos <<
"):\n");
1944 assert(pos <
getNumVars() &&
"invalid position");
1949 if (
atEq(r, pos) != 0) {
1953 assert(ret.succeeded() &&
"Gaussian elimination guaranteed to succeed");
1954 LLVM_DEBUG(llvm::dbgs() <<
"FM output (through Gaussian elimination):\n");
1968 LLVM_DEBUG(llvm::dbgs() <<
"FM output:\n");
1978 std::vector<unsigned> nbIndices;
1985 if (
atIneq(r, pos) == 0) {
1987 nbIndices.emplace_back(r);
1988 }
else if (
atIneq(r, pos) >= 1) {
1990 lbIndices.emplace_back(r);
1993 ubIndices.emplace_back(r);
2000 newSpace.
removeVarRange(idKindRemove, relativePos, relativePos + 1);
2003 IntegerRelation newRel(lbIndices.size() * ubIndices.size() + nbIndices.size(),
2007 bool allLCMsAreOne =
true;
2019 for (
auto ubPos : ubIndices) {
2020 for (
auto lbPos : lbIndices) {
2023 DynamicAPInt lbCoeff =
atIneq(lbPos, pos);
2027 DynamicAPInt ubCoeff = -
atIneq(ubPos, pos);
2029 for (
unsigned l = 0, e =
getNumCols(); l < e; l++) {
2032 assert(lbCoeff >= 1 && ubCoeff >= 1 &&
"bounds wrongly identified");
2033 DynamicAPInt lcm = llvm::lcm(lbCoeff, ubCoeff);
2034 ineq.emplace_back(
atIneq(ubPos, l) * (lcm / ubCoeff) +
2035 atIneq(lbPos, l) * (lcm / lbCoeff));
2036 assert(lcm > 0 &&
"lcm should be positive!");
2038 allLCMsAreOne =
false;
2043 ineq[ineq.size() - 1] += lbCoeff * ubCoeff - lbCoeff - ubCoeff + 1;
2051 LLVM_DEBUG(llvm::dbgs() <<
"FM isResultIntegerExact: " << allLCMsAreOne
2053 if (allLCMsAreOne && isResultIntegerExact)
2054 *isResultIntegerExact =
true;
2057 for (
auto nbPos : nbIndices) {
2060 for (
unsigned l = 0, e =
getNumCols(); l < e; l++) {
2063 ineq.emplace_back(
atIneq(nbPos, l));
2069 lbIndices.size() * ubIndices.size() + nbIndices.size());
2075 for (
unsigned l = 0, e =
getNumCols(); l < e; l++) {
2078 eq.emplace_back(
atEq(r, l));
2089 LLVM_DEBUG(llvm::dbgs() <<
"FM output:\n");
2094 #define DEBUG_TYPE "presburger"
2102 assert(pos + num <
getNumCols() &&
"invalid range");
2105 unsigned currentPos = pos;
2106 unsigned numToEliminate = num;
2107 unsigned numGaussianEliminated = 0;
2110 unsigned curNumEliminated =
2113 numToEliminate -= curNumEliminated + 1;
2114 numGaussianEliminated += curNumEliminated;
2118 for (
unsigned i = 0; i < num - numGaussianEliminated; i++) {
2119 unsigned numToEliminate = num - numGaussianEliminated - i;
2133 enum BoundCmpResult { Greater, Less, Equal, Unknown };
2139 assert(a.size() == b.size());
2145 if (!std::equal(a.begin(), a.end() - 1, b.begin()))
2148 if (a.back() == b.back())
2151 return a.back() < b.back() ? Less : Greater;
2190 std::vector<SmallVector<DynamicAPInt, 8>> boundingLbs;
2191 std::vector<SmallVector<DynamicAPInt, 8>> boundingUbs;
2203 DynamicAPInt lbFloorDivisor, otherLbFloorDivisor;
2206 if (!extent.has_value())
2212 d, &otherLb, &otherLbFloorDivisor, &otherUb);
2213 if (!otherExtent.has_value() || lbFloorDivisor != otherLbFloorDivisor)
2217 assert(lbFloorDivisor > 0 &&
"divisor always expected to be positive");
2219 auto res = compareBounds(lb, otherLb);
2221 if (res == BoundCmpResult::Less || res == BoundCmpResult::Equal) {
2226 minLb.back() -= lbFloorDivisor - 1;
2227 }
else if (res == BoundCmpResult::Greater) {
2229 minLb.back() -= otherLbFloorDivisor - 1;
2234 if (!constLb.has_value() || !constOtherLb.has_value())
2236 std::fill(minLb.begin(), minLb.end(), 0);
2237 minLb.back() =
std::min(*constLb, *constOtherLb);
2241 auto uRes = compareBounds(ub, otherUb);
2242 if (uRes == BoundCmpResult::Greater || uRes == BoundCmpResult::Equal) {
2244 }
else if (uRes == BoundCmpResult::Less) {
2250 if (!constUb.has_value() || !constOtherUb.has_value())
2252 std::fill(maxUb.begin(), maxUb.end(), 0);
2253 maxUb.back() =
std::max(*constUb, *constOtherUb);
2256 std::fill(newLb.begin(), newLb.end(), 0);
2257 std::fill(newUb.begin(), newUb.end(), 0);
2261 newLb[d] = lbFloorDivisor;
2262 newUb[d] = -lbFloorDivisor;
2265 std::transform(newLb.begin() +
getNumDimVars(), newLb.end(),
2267 std::negate<DynamicAPInt>());
2270 boundingLbs.emplace_back(newLb);
2271 boundingUbs.emplace_back(newUb);
2304 assert(pos < cst.
getNumVars() &&
"invalid start position");
2305 assert(pos + num <= cst.
getNumVars() &&
"invalid limit");
2310 for (c = pos; c < pos + num; ++c) {
2311 if (cst.
atIneq(r, c) != 0)
2315 nbIneqIndices.emplace_back(r);
2321 for (c = pos; c < pos + num; ++c) {
2322 if (cst.
atEq(r, c) != 0)
2326 nbEqIndices.emplace_back(r);
2331 assert(pos + num <=
getNumVars() &&
"invalid range");
2340 for (
auto nbIndex : llvm::reverse(nbIneqIndices))
2342 for (
auto nbIndex : llvm::reverse(nbEqIndices))
2361 bool changed =
false;
2362 SmallDenseMap<ArrayRef<DynamicAPInt>,
unsigned> hashTable;
2370 hashTable.insert({row, 0});
2371 for (
unsigned k = 1; k < ineqs; ++k) {
2373 if (hashTable.try_emplace(row, k).second)
2377 unsigned l = hashTable[row];
2388 for (
unsigned k = 0; k < ineqs; ++k) {
2390 negIneq.assign(row.begin(), row.end());
2391 for (DynamicAPInt &ele : negIneq)
2393 if (!hashTable.contains(negIneq))
2398 unsigned l = hashTable[row];
2400 if (sum > 0 || l == k)
2435 "Domain set is not compatible with poly");
2451 "Range set is not compatible with poly");
2471 "Range of `this` should be compatible with Domain of `rel`");
2535 "Domain of this and range of other do not match");
2598 updatePrintMetrics<DynamicAPInt>(
atEq(i,
j), ptm);
2601 updatePrintMetrics<DynamicAPInt>(
atIneq(i,
j), ptm);
2603 unsigned MIN_SPACING = 1;
2606 printWithPrintMetrics<DynamicAPInt>(os,
atEq(i,
j), MIN_SPACING, ptm);
2612 printWithPrintMetrics<DynamicAPInt>(os,
atIneq(i,
j), MIN_SPACING, ptm);
2624 "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 bool rangeIsZero(ArrayRef< DynamicAPInt > range)
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 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 DynamicAPInt valueAt(ArrayRef< DynamicAPInt > expr, ArrayRef< DynamicAPInt > point)
Helper to evaluate an affine expression at a point.
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.
void clearRepr(unsigned i)
DynamicAPInt & getDenom(unsigned i)
MutableArrayRef< DynamicAPInt > getDividend(unsigned i)
An Identifier stores a pointer to an object, such as a Value or an Operation.
DynamicAPInt 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 ...
std::optional< DynamicAPInt > getConstantBoundOnDimSize(unsigned pos, SmallVectorImpl< DynamicAPInt > *lb=nullptr, DynamicAPInt *boundFloorDivisor=nullptr, SmallVectorImpl< DynamicAPInt > *ub=nullptr, unsigned *minLbPos=nullptr, unsigned *minUbPos=nullptr) const
Returns the smallest known constant bound for the extent of the specified variable (pos^th),...
void setId(VarKind kind, unsigned i, Identifier id)
Set the identifier for the ith variable of the specified kind of the IntegerRelation's PresburgerSpac...
virtual void swapVar(unsigned posA, unsigned posB)
Swap the posA^th variable with the posB^th variable.
void removeIndependentConstraints(unsigned pos, unsigned num)
Removes constraints that are independent of (i.e., do not have a coefficient) variables in the range ...
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.
ArrayRef< Identifier > getIds(VarKind kind)
Get the identifiers for the variables of specified varKind.
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 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
std::optional< DynamicAPInt > computeConstantLowerOrUpperBound(unsigned pos)
Returns the constant lower bound if isLower is true, and the upper bound if isLower is false.
void removeEqualityRange(unsigned start, unsigned end)
Remove the (in)equalities at positions [start, end).
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.
std::optional< SmallVector< DynamicAPInt, 8 > > containsPointNoLocal(ArrayRef< DynamicAPInt > point) const
Given the values of non-local vars, return a satisfying assignment to the local if one exists,...
ArrayRef< DynamicAPInt > getInequality(unsigned idx) const
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()
void addBound(BoundType type, unsigned pos, const DynamicAPInt &value)
Adds a constant bound for the specified variable.
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 addLocalFloorDiv(ArrayRef< DynamicAPInt > dividend, const DynamicAPInt &divisor)
Adds a new local variable as the floordiv of an affine function of other variables,...
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.
DynamicAPInt atIneq(unsigned i, unsigned j) const
Returns the value at the specified inequality row and column.
virtual unsigned insertVar(VarKind kind, unsigned pos, unsigned num=1)
Insert num variables of the specified kind at position pos.
bool containsPoint(ArrayRef< DynamicAPInt > point) const
Returns true if the given point satisfies the constraints, or false otherwise.
std::optional< SmallVector< DynamicAPInt, 8 > > findIntegerSample() const
Find an integer sample point satisfying the constraints using a branch and bound algorithm with gener...
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...
void convertToLocal(VarKind kind, unsigned varStart, unsigned varLimit)
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.
DynamicAPInt atEq(unsigned i, unsigned j) const
Returns the value at the specified equality row and column.
IntegerRelation intersect(IntegerRelation other) const
Return the intersection of the two relations.
std::optional< DynamicAPInt > computeVolume() const
Compute an overapproximation of the number of integer points in the relation.
MaybeOptimum< SmallVector< DynamicAPInt, 8 > > findIntegerLexMin() const
Same as above, but returns lexicographically minimal integer point.
void removeTrivialEqualities()
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.
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.
void addEquality(ArrayRef< DynamicAPInt > eq)
Adds an equality from the coefficients specified in eq.
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...
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 mergeAndCompose(const IntegerRelation &other)
Given a relation other: (A -> B), this operation merges the symbol and local variables and then takes...
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.
std::optional< DynamicAPInt > getConstantBound(BoundType type, unsigned pos) const
Returns the constant bound for the pos^th variable if there is one; std::nullopt otherwise.
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.
void addInequality(ArrayRef< DynamicAPInt > inEq)
Adds an inequality (>= 0) from the coefficients specified in inEq.
void mergeAndAlignSymbols(IntegerRelation &other)
Merge and align symbol variables of this and other with respect to identifiers.
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...
ArrayRef< DynamicAPInt > getEquality(unsigned idx) const
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.
void setAndEliminate(unsigned pos, ArrayRef< DynamicAPInt > values)
Sets the values.size() variables starting at pos to the specified values and removes them.
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< Fraction, 8 > > findRationalLexMin()
Return the lexicographically minimum rational solution to the constraints.
MaybeOptimum< SmallVector< DynamicAPInt, 8 > > findIntegerLexMin()
Return the lexicographically minimum integer solution to the constraints.
void moveColumns(unsigned srcPos, unsigned num, unsigned dstPos)
Move the columns in the source range [srcPos, srcPos + num) to the specified destination [dstPos,...
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.
void setId(VarKind kind, unsigned pos, Identifier id)
Set the identifier of pos^th variable of the specified kind.
unsigned getNumVarKind(VarKind kind) const
Get the number of vars of the specified kind.
void resetIds()
Reset the stored identifiers in the space.
bool isEqual(const PresburgerSpace &other) const
Returns true if both the spaces are equal including local variables i.e.
bool isUsingIds() const
Returns if identifiers are being used.
void convertVarKind(VarKind srcKind, unsigned srcPos, unsigned num, VarKind dstKind, unsigned dstPos)
Converts variables of the specified kind in the column range [srcPos, srcPos + num) to variables of t...
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.
Identifier getId(VarKind kind, unsigned pos) const
Get the identifier of pos^th variable of the specified kind.
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)
ArrayRef< Identifier > getIds(VarKind kind) const
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)
void swapVar(VarKind kindA, VarKind kindB, unsigned posA, unsigned posB)
Swaps the posA^th variable of kindA and posB^th variable of kindB.
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...
std::pair< MaybeOptimum< DynamicAPInt >, MaybeOptimum< DynamicAPInt > > computeIntegerBounds(ArrayRef< DynamicAPInt > coeffs)
Returns a (min, max) pair denoting the minimum and maximum integer values of the given expression.
bool isMarkedRedundant(unsigned constraintIndex) const
Returns whether the specified constraint has been marked as redundant.
bool isFlatAlong(ArrayRef< DynamicAPInt > coeffs)
Check if the simplex takes only one rational value along the direction of coeffs.
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.
std::optional< SmallVector< DynamicAPInt, 8 > > findIntegerSample()
Returns an integer sample point if one exists, or std::nullopt otherwise.
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.
MaybeLocalRepr computeSingleVarRepr(const IntegerRelation &cst, ArrayRef< bool > foundRepr, unsigned pos, MutableArrayRef< DynamicAPInt > dividend, DynamicAPInt &divisor)
Returns the MaybeLocalRepr struct which contains the indices of the constraints that can be expressed...
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 ...
DynamicAPInt ceil(const Fraction &f)
Fraction abs(const Fraction &f)
SmallVector< DynamicAPInt, 8 > getDivUpperBound(ArrayRef< DynamicAPInt > dividend, const DynamicAPInt &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 ...
SmallVector< DynamicAPInt, 8 > getDivLowerBound(ArrayRef< DynamicAPInt > dividend, const DynamicAPInt &divisor, unsigned localVarIdx)
Include the generated interface declarations.
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...
Example usage: Print .12, 3.4, 56.7 preAlign = ".", minSpacing = 1, .12 .12 3.4 3....
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.