15#include "llvm/ADT/DynamicAPInt.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallBitVector.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/SmallVectorExtras.h"
20#include "llvm/Support/Compiler.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/raw_ostream.h"
35const int nullIndex = std::numeric_limits<int>::max();
42 assert(a.size() ==
b.size());
44 res.reserve(a.size());
45 for (
unsigned i = 0, e = a.size(); i < e; ++i)
46 res.emplace_back(a[i] + scale *
b[i]);
56 for (
unsigned i = 0; i < nVar; ++i) {
64 const llvm::SmallBitVector &isSymbol)
66 assert(isSymbol.size() == nVar &&
"invalid bitmask!");
70 for (
unsigned symbolIdx : isSymbol.set_bits()) {
71 var[symbolIdx].isSymbol =
true;
78 assert(
index !=
nullIndex &&
"nullIndex passed to unknownFromIndex");
93 assert(
index !=
nullIndex &&
"nullIndex passed to unknownFromIndex");
109 unsigned newRow =
tableau.appendExtraRow();
122 bool makeRestricted) {
123 assert(coeffs.size() ==
var.size() + 1 &&
124 "Incorrect number of coefficients!");
126 "inconsistent column count!");
129 tableau(newRow, 1) = coeffs.back();
145 DynamicAPInt bigMCoeff(0);
146 for (
unsigned i = 0; i < coeffs.size() - 1; ++i)
147 if (!
var[i].isSymbol)
148 bigMCoeff -= coeffs[i];
150 tableau(newRow, 2) = bigMCoeff;
154 for (
unsigned i = 0; i <
var.size(); ++i) {
155 unsigned pos =
var[i].pos;
171 DynamicAPInt lcm = llvm::lcm(
tableau(newRow, 0),
tableau(pos, 0));
172 DynamicAPInt nRowCoeff = lcm /
tableau(newRow, 0);
173 DynamicAPInt idxRowCoeff = coeffs[i] * (lcm /
tableau(pos, 0));
177 nRowCoeff *
tableau(newRow, col) + idxRowCoeff *
tableau(pos, col);
182 return con.size() - 1;
186bool signMatchesDirection(
const DynamicAPInt &elem,
Direction direction) {
187 assert(elem != 0 &&
"elem should not be 0");
188 return direction == Direction::Up ? elem > 0 : elem < 0;
192 return direction == Direction::Up ? Direction::Down : Simplex::Direction::Up;
236 if (restoreRationalConsistency().failed()) {
240 return getRationalSample();
282 DynamicAPInt d =
tableau(row, 0);
292std::optional<unsigned> LexSimplex::maybeGetNonIntegralVarRow()
const {
299 unsigned row = u.pos;
308 if (restoreRationalConsistency().failed())
312 while (std::optional<unsigned> maybeRow = maybeGetNonIntegralVarRow()) {
323 if (
addCut(*maybeRow).failed())
325 if (restoreRationalConsistency().failed())
330 assert(!sample.
isEmpty() &&
"If we reached here the sample should exist!");
347SymbolicLexSimplex::getSymbolicSampleNumerator(
unsigned row)
const {
350 for (
unsigned col = 3; col < 3 +
nSymbol; ++col)
351 sample.emplace_back(
tableau(row, col));
352 sample.emplace_back(
tableau(row, 1));
357SymbolicLexSimplex::getSymbolicSampleIneq(
unsigned row)
const {
367 var.back().isSymbol =
true;
372 const DynamicAPInt &divisor) {
373 assert(divisor > 0 &&
"divisor must be positive!");
375 range, [divisor](
const DynamicAPInt &x) {
return x % divisor == 0; });
378bool SymbolicLexSimplex::isSymbolicSampleIntegral(
unsigned row)
const {
379 DynamicAPInt denom =
tableau(row, 0);
380 return tableau(row, 1) % denom == 0 &&
417LogicalResult SymbolicLexSimplex::addSymbolicCut(
unsigned row) {
418 DynamicAPInt d =
tableau(row, 0);
427 SmallVector<DynamicAPInt, 8> divCoeffs;
428 divCoeffs.reserve(
nSymbol + 1);
429 DynamicAPInt divDenom = d;
430 for (
unsigned col = 3; col < 3 +
nSymbol; ++col)
431 divCoeffs.emplace_back(mod(-
tableau(row, col), divDenom));
432 divCoeffs.emplace_back(mod(-
tableau(row, 1), divDenom));
435 domainSimplex.addDivisionVariable(divCoeffs, divDenom);
436 (void)domainPoly.addLocalFloorDiv(divCoeffs, divDenom);
447 for (
unsigned col = 3; col < 3 +
nSymbol - 1; ++col)
457 IntMatrix output(0, domainPoly.getNumVars() + 1);
458 output.reserveRows(
result.lexopt.getNumOutputs());
466 result.unboundedDomain.unionInPlace(domainPoly);
470 DynamicAPInt denom =
tableau(u.pos, 0);
471 if (
tableau(u.pos, 2) < denom) {
475 result.unboundedDomain.unionInPlace(domainPoly);
478 assert(
tableau(u.pos, 2) == denom &&
479 "Coefficient of M should not be greater than 1!");
481 SmallVector<DynamicAPInt, 8> sample = getSymbolicSampleNumerator(u.pos);
482 for (DynamicAPInt &elem : sample) {
483 assert(elem % denom == 0 &&
"coefficients must be integral!");
486 output.appendExtraRow(sample);
490 PresburgerSpace funcSpace =
result.lexopt.getSpace();
494 {PresburgerSet(domainPoly),
495 MultiAffineFunction(funcSpace, output, domainPoly.getLocalReprs())});
498std::optional<unsigned> SymbolicLexSimplex::maybeGetAlwaysViolatedRow() {
501 for (
unsigned row = 0, e =
getNumRows(); row < e; ++row)
505 for (
unsigned row = 0, e =
getNumRows(); row < e; ++row) {
508 if (domainSimplex.isSeparateInequality(getSymbolicSampleIneq(row))) {
516std::optional<unsigned> SymbolicLexSimplex::maybeGetNonIntegralVarRow() {
520 assert(!u.isSymbol &&
"Symbol should not be in row orientation!");
521 if (!isSymbolicSampleIntegral(u.pos))
529LogicalResult SymbolicLexSimplex::doNonBranchingPivots() {
530 while (std::optional<unsigned> row = maybeGetAlwaysViolatedRow())
538 domainPoly.getNumDimVars(),
540 domainPoly.getNumSymbolVars()));
559 unsigned domainSnapshot;
565 assert(level >= stack.size());
566 if (level > stack.size()) {
567 if (
empty || domainSimplex.findIntegerLexMin().isEmpty()) {
573 if (doNonBranchingPivots().failed()) {
580 unsigned splitRow = 0;
581 for (
unsigned e =
getNumRows(); splitRow < e; ++splitRow) {
584 assert(
tableau(splitRow, 2) == 0 &&
585 "Non-branching pivots should have been handled already!");
587 symbolicSample = getSymbolicSampleIneq(splitRow);
588 if (domainSimplex.isRedundantInequality(symbolicSample))
594 assert(!domainSimplex.isSeparateInequality(symbolicSample) &&
595 "Non-branching pivots should have been handled already!");
600 unsigned domainSnapshot = domainSimplex.getSnapshot();
602 domainPoly.getCounts();
608 domainSimplex.addInequality(symbolicSample);
609 domainPoly.addInequality(symbolicSample);
625 StackFrame{splitIndex, snapshot, domainSnapshot, domainPolyCounts});
632 if (std::optional<unsigned> row = maybeGetNonIntegralVarRow()) {
633 if (addSymbolicCut(*row).failed()) {
649 if (level == stack.size()) {
651 const StackFrame &frame = stack.back();
652 domainPoly.truncate(frame.domainPolyCounts);
653 domainSimplex.rollback(frame.domainSnapshot);
663 "The split row should have been returned to row orientation!");
675 domainSimplex.addInequality(splitIneq);
676 domainPoly.addInequality(splitIneq);
687bool LexSimplex::rowIsViolated(
unsigned row)
const {
695std::optional<unsigned> LexSimplex::maybeGetViolatedRow()
const {
696 for (
unsigned row = 0, e =
getNumRows(); row < e; ++row)
697 if (rowIsViolated(row))
705LogicalResult LexSimplex::restoreRationalConsistency() {
708 while (std::optional<unsigned> maybeViolatedRow = maybeGetViolatedRow())
777 std::optional<unsigned> maybeColumn;
788 pivot(row, *maybeColumn);
793 unsigned colB)
const {
838 auto getSampleChangeCoeffForVar = [
this, row](
unsigned col,
840 DynamicAPInt a =
tableau(row, col);
855 DynamicAPInt c =
tableau(u.pos, col);
860 Fraction changeA = getSampleChangeCoeffForVar(colA, u);
861 Fraction changeB = getSampleChangeCoeffForVar(colB, u);
862 if (changeA < changeB)
864 if (changeA > changeB)
885std::optional<SimplexBase::Pivot>
886Simplex::findPivot(
int row,
Direction direction)
const {
887 std::optional<unsigned> col;
889 DynamicAPInt elem =
tableau(row,
j);
894 !signMatchesDirection(elem, direction))
904 tableau(row, *col) < 0 ? flippedDirection(direction) : direction;
905 std::optional<unsigned> maybePivotRow = findPivotRow(row, newDirection, *col);
906 return Pivot{maybePivotRow.value_or(row), *col};
951 assert(pivotCol >=
getNumFixedCols() &&
"Refusing to pivot invalid column");
957 if (
tableau(pivotRow, 0) < 0) {
963 for (
unsigned col = 1, e =
getNumColumns(); col < e; ++col) {
969 tableau.normalizeRow(pivotRow);
971 for (
unsigned row = 0, numRows =
getNumRows(); row < numRows; ++row) {
974 if (
tableau(row, pivotCol) == 0)
977 for (
unsigned col = 1, numCols =
getNumColumns(); col < numCols; ++col) {
992LogicalResult Simplex::restoreRow(
Unknown &u) {
993 assert(!
empty &&
"Cannot restore a row of an empty tableau");
995 "unknown should be in row position");
997 while (
tableau(u.pos, 1) < 0) {
998 std::optional<Pivot> maybePivot = findPivot(u.pos, Direction::Up);
1031std::optional<unsigned> Simplex::findPivotRow(std::optional<unsigned> skipRow,
1033 unsigned col)
const {
1034 std::optional<unsigned> retRow;
1039 DynamicAPInt retElem, retConst;
1041 if (skipRow && row == *skipRow)
1043 DynamicAPInt elem =
tableau(row, col);
1048 if (signMatchesDirection(elem, direction))
1050 DynamicAPInt constTerm =
tableau(row, 1);
1055 retConst = constTerm;
1059 DynamicAPInt diff = retConst * elem - constTerm * retElem;
1061 (diff != 0 && !signMatchesDirection(diff, direction))) {
1064 retConst = constTerm;
1083 "Invalid columns provided!");
1116 unsigned conIndex =
addRow(coeffs,
true);
1119 LogicalResult
result = restoreRow(
con[conIndex]);
1133 negatedCoeffs.reserve(coeffs.size());
1134 for (
const DynamicAPInt &coeff : coeffs)
1135 negatedCoeffs.emplace_back(-coeff);
1151 basis.emplace_back(
index);
1202 unsigned column =
con.back().pos;
1203 if (std::optional<unsigned> maybeRow =
1204 findPivotRow({}, Direction::Up, column)) {
1205 pivot(*maybeRow, column);
1206 }
else if (std::optional<unsigned> maybeRow =
1207 findPivotRow({}, Direction::Down, column)) {
1208 pivot(*maybeRow, column);
1211 assert(row &&
"Pivot should always exist for a constraint!");
1212 pivot(*row, column);
1228 unsigned column =
con.back().pos;
1230 assert(row &&
"Pivot should always exist for a constraint!");
1231 pivot(*row, column);
1252 "Variable to be removed must be in column orientation!");
1254 if (
var.back().isSymbol)
1268 assert(!
savedBases.empty() &&
"No bases saved!");
1273 for (
int index : basis) {
1280 "Column should not be a fixed column!");
1281 if (llvm::is_contained(basis,
colUnknown[col]))
1299 while (
undoLog.size() > snapshot) {
1312 const DynamicAPInt &denom) {
1313 assert(denom > 0 &&
"Denominator must be positive!");
1317 DynamicAPInt constTerm = ineq.back();
1318 ineq.back() = -denom;
1319 ineq.emplace_back(constTerm);
1322 for (DynamicAPInt &coeff : ineq)
1324 ineq.back() += denom - 1;
1331 var.reserve(
var.size() + count);
1333 for (
unsigned i = 0; i < count; ++i) {
1345 "IntegerRelation must have same dimensionality as simplex");
1354 assert(!
empty &&
"Cannot optimize over an empty Simplex!");
1356 while (std::optional<Pivot> maybePivot = findPivot(row, direction)) {
1359 if (maybePivot->row == row)
1378 unsigned conIndex =
addRow(coeffs);
1379 unsigned row =
con[conIndex].pos;
1388 unsigned column = u.pos;
1389 std::optional<unsigned> pivotRow = findPivotRow({}, direction, column);
1394 pivot(*pivotRow, column);
1397 unsigned row = u.pos;
1399 if (u.restricted && direction == Direction::Down &&
1401 if (restoreRow(u).failed())
1402 llvm_unreachable(
"Could not restore row!");
1408 assert(!
empty &&
"It is not meaningful to ask whether a direction is bounded "
1409 "in an empty set.");
1427void Simplex::markRowRedundant(
Unknown &u) {
1429 "Unknown should be in row position!");
1430 assert(u.pos >=
nRedundant &&
"Unknown is already marked redundant!");
1438 assert(offset + count <=
con.size() &&
"invalid range!");
1452 for (
unsigned i = 0; i < count; ++i) {
1455 unsigned column = u.
pos;
1456 std::optional<unsigned> pivotRow =
1457 findPivotRow({}, Direction::Down, column);
1462 pivot(*pivotRow, column);
1465 unsigned row = u.
pos;
1470 if (restoreRow(u).failed())
1471 llvm_unreachable(
"Could not restore non-redundant row!");
1475 markRowRedundant(u);
1484 for (
unsigned i = 0; i <
var.size(); ++i) {
1512 result.tableau.reserveRows(numCon);
1517 result.reserve(v.size() + w.size());
1518 llvm::append_range(
result, v);
1519 llvm::append_range(
result, w);
1525 auto indexFromBIndex = [&](
int index) {
1533 result.unknownFromIndex(
result.colUnknown.back()).pos =
1534 result.colUnknown.size() - 1;
1536 for (
unsigned i = 2, e =
b.getNumColumns(); i < e; ++i) {
1537 result.colUnknown.emplace_back(indexFromBIndex(
b.colUnknown[i]));
1538 result.unknownFromIndex(
result.colUnknown.back()).pos =
1539 result.colUnknown.size() - 1;
1542 auto appendRowFromA = [&](
unsigned row) {
1543 unsigned resultRow =
result.tableau.appendExtraRow();
1544 for (
unsigned col = 0, e = a.
getNumColumns(); col < e; ++col)
1547 result.unknownFromIndex(
result.rowUnknown.back()).pos =
1548 result.rowUnknown.size() - 1;
1553 auto appendRowFromB = [&](
unsigned row) {
1554 unsigned resultRow =
result.tableau.appendExtraRow();
1555 result.tableau(resultRow, 0) =
b.tableau(row, 0);
1556 result.tableau(resultRow, 1) =
b.tableau(row, 1);
1559 for (
unsigned col = 2, e =
b.getNumColumns(); col < e; ++col)
1560 result.tableau(resultRow, offset + col) =
b.tableau(row, col);
1561 result.rowUnknown.emplace_back(indexFromBIndex(
b.rowUnknown[row]));
1562 result.unknownFromIndex(
result.rowUnknown.back()).pos =
1563 result.rowUnknown.size() - 1;
1567 for (
unsigned row = 0; row < a.
nRedundant; ++row)
1568 appendRowFromA(row);
1569 for (
unsigned row = 0; row <
b.nRedundant; ++row)
1570 appendRowFromB(row);
1572 appendRowFromA(row);
1573 for (
unsigned row =
b.nRedundant, e =
b.getNumRows(); row < e; ++row)
1574 appendRowFromB(row);
1584 sample.reserve(
var.size());
1589 sample.emplace_back(0, 1);
1593 DynamicAPInt denom =
tableau(u.pos, 0);
1594 sample.emplace_back(
tableau(u.pos, 1), denom);
1609 sample.reserve(
var.size());
1625 DynamicAPInt denom =
tableau(u.pos, 0);
1627 if (
tableau(u.pos, 2) != denom)
1629 sample.emplace_back(
tableau(u.pos, 1), denom);
1634std::optional<SmallVector<DynamicAPInt, 8>>
1643 integerSample.reserve(
var.size());
1644 for (
const Fraction &coord : rationalSample) {
1646 if (coord.num % coord.den != 0)
1648 integerSample.emplace_back(coord.num / coord.den);
1650 return integerSample;
1668 : simplex(
Simplex::makeProduct(originalSimplex, originalSimplex)),
1669 simplexConstraintOffset(simplex.getNumConstraints()) {}
1675 assert(llvm::any_of(dir, [](
const DynamicAPInt &X) {
return X != 0; }) &&
1676 "Direction passed is the zero vector!");
1677 snapshotStack.emplace_back(simplex.getSnapshot());
1678 simplex.addEquality(getCoeffsForDirection(dir));
1683 simplex.computeOptimum(Direction::Up, getCoeffsForDirection(dir));
1684 assert(maybeWidth.
isBounded() &&
"Width should be bounded!");
1692 DynamicAPInt &dualDenom) {
1700 unsigned conIndex = simplex.addRow(getCoeffsForDirection(dir));
1701 unsigned row = simplex.con[conIndex].pos;
1703 simplex.computeRowOptimum(Simplex::Direction::Up, row);
1704 assert(maybeWidth.
isBounded() &&
"Width should be bounded!");
1705 dualDenom = simplex.tableau(row, 0);
1707 dual.reserve((conIndex - simplexConstraintOffset) / 2);
1711 for (
unsigned i = simplexConstraintOffset; i < conIndex; i += 2) {
1732 assert((simplex.con[i].orientation != Orientation::Column ||
1733 simplex.con[i + 1].orientation != Orientation::Column) &&
1734 "Both inequalities for the equality cannot be in column "
1736 if (simplex.con[i].orientation == Orientation::Column)
1737 dual.emplace_back(-simplex.tableau(row, simplex.con[i].pos));
1738 else if (simplex.con[i + 1].orientation == Orientation::Column)
1739 dual.emplace_back(simplex.tableau(row, simplex.con[i + 1].pos));
1741 dual.emplace_back(0);
1751 assert(!snapshotStack.empty() &&
"Snapshot stack is empty!");
1752 simplex.rollback(snapshotStack.back());
1753 snapshotStack.pop_back();
1763 assert(2 * dir.size() == simplex.getNumVariables() &&
1764 "Direction vector has wrong dimensionality");
1766 coeffs.reserve(dir.size() + 1);
1767 for (
const DynamicAPInt &coeff : dir)
1768 coeffs.emplace_back(-coeff);
1769 coeffs.emplace_back(0);
1776 unsigned simplexConstraintOffset;
1836void Simplex::reduceBasis(
IntMatrix &basis,
unsigned level) {
1845 DynamicAPInt dualDenom;
1865 auto updateBasisWithUAndGetFCandidate = [&](
unsigned i) ->
Fraction {
1866 assert(i < level + dual.size() &&
"dual_i is not known!");
1868 DynamicAPInt u = floorDiv(dual[i - level], dualDenom);
1870 if (dual[i - level] % dualDenom != 0) {
1872 DynamicAPInt candidateDualDenom[2];
1876 widthI[0] = gbrSimplex.computeWidthAndDuals(
1877 basis.
getRow(i + 1), candidateDual[0], candidateDualDenom[0]);
1882 widthI[1] = gbrSimplex.computeWidthAndDuals(
1883 basis.
getRow(i + 1), candidateDual[1], candidateDualDenom[1]);
1885 unsigned j = widthI[0] < widthI[1] ? 0 : 1;
1899 basis.
getRow(i + 1), DynamicAPInt(-1), basis.
getRow(i))) >=
1901 "Computed u value does not minimize the width!");
1904 basis.
getRow(i + 1), DynamicAPInt(+1), basis.
getRow(i))) >=
1906 "Computed u value does not minimize the width!");
1908 dual = std::move(candidateDual[
j]);
1909 dualDenom = candidateDualDenom[
j];
1913 assert(i + 1 - level < width.size() &&
"width_{i+1} wasn't saved");
1917 assert(gbrSimplex.computeWidth(basis.
getRow(i + 1)) ==
1918 width[i + 1 - level]);
1919 return width[i + 1 - level];
1926 if (i >= level + width.size()) {
1931 assert((i == 0 || i - 1 < level + width.size()) &&
1932 "We are at level i but we don't know the value of width_{i-1}");
1937 assert(i == level &&
"This case should only occur when i == level");
1939 gbrSimplex.computeWidthAndDuals(basis.
getRow(i), dual, dualDenom));
1942 if (i >= level + dual.size()) {
1943 assert(i + 1 >= level + width.size() &&
1944 "We don't know dual_i but we know width_{i+1}");
1946 gbrSimplex.addEqualityForDirection(basis.
getRow(i));
1947 width.emplace_back(gbrSimplex.computeWidthAndDuals(basis.
getRow(i + 1),
1949 gbrSimplex.removeLastEquality();
1953 Fraction widthICandidate = updateBasisWithUAndGetFCandidate(i);
1954 if (widthICandidate < epsilon * width[i - level]) {
1956 width[i - level] = widthICandidate;
1959 width.resize(i - level + 1);
1965 gbrSimplex.removeLastEquality();
1972 gbrSimplex.addEqualityForDirection(basis.
getRow(i));
2009 unsigned nDims =
var.size();
2023 while (level != -1u) {
2033 if (level >= upperBoundStack.size()) {
2039 llvm::to_vector<8>(basis.
getRow(level));
2040 basisCoeffs.emplace_back(0);
2046 if (minRoundedUp.isEmpty() || maxRoundedDown.isEmpty()) {
2047 assert((minRoundedUp.isEmpty() && maxRoundedDown.isEmpty()) &&
2048 "If one bound is empty, both should be.");
2049 snapshotStack.pop_back();
2050 nextValueStack.pop_back();
2051 upperBoundStack.pop_back();
2057 assert((minRoundedUp.isBounded() && maxRoundedDown.isBounded()) &&
2058 "Polyhedron should be bounded!");
2063 return *maybeSample;
2065 if (*minRoundedUp < *maxRoundedDown) {
2066 reduceBasis(basis, level);
2067 basisCoeffs = llvm::to_vector<8>(basis.
getRow(level));
2068 basisCoeffs.emplace_back(0);
2069 std::tie(minRoundedUp, maxRoundedDown) =
2077 nextValueStack.emplace_back(*minRoundedUp);
2078 upperBoundStack.emplace_back(*maxRoundedDown);
2081 assert((snapshotStack.size() - 1 == level &&
2082 nextValueStack.size() - 1 == level &&
2083 upperBoundStack.size() - 1 == level) &&
2084 "Mismatched variable stack sizes!");
2090 DynamicAPInt nextValue = nextValueStack.back();
2091 ++nextValueStack.back();
2092 if (nextValue > upperBoundStack.back()) {
2095 snapshotStack.pop_back();
2096 nextValueStack.pop_back();
2097 upperBoundStack.pop_back();
2104 basis.
getRow(level).end());
2105 basisCoeffs.emplace_back(-nextValue);
2121 return {minRoundedUp, maxRoundedDown};
2125 assert(!
isEmpty() &&
"cannot check for flatness of empty simplex!");
2129 if (!upOpt.isBounded())
2131 if (!downOpt.isBounded())
2134 return *upOpt == *downOpt;
2140 os <<
"Simplex marked empty!\n";
2142 for (
unsigned i = 0; i <
var.size(); ++i) {
2148 for (
unsigned i = 0; i <
con.size(); ++i) {
2154 for (
unsigned row = 0, e =
getNumRows(); row < e; ++row) {
2160 os <<
"c0: denom, c1: const";
2162 os <<
", c" << col <<
": " <<
colUnknown[col];
2165 for (
unsigned row = 0, numRows =
getNumRows(); row < numRows; ++row)
2166 for (
unsigned col = 0, numCols =
getNumColumns(); col < numCols; ++col)
2168 unsigned minSpacing = 1;
2169 for (
unsigned row = 0, numRows =
getNumRows(); row < numRows; ++row) {
2170 for (
unsigned col = 0, numCols =
getNumColumns(); col < numCols; ++col) {
2179#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2213 assert(!
empty &&
"It is not meaningful to classify an inequality with "
2214 "respect to an empty set!");
2231 "It is not meaningful to ask about redundancy in an empty set!");
2241 "It is not meaningful to ask about redundancy in an empty set!");
2245 "Optima should be non-empty for a non-empty set");
false
Parses a map_entries map type from a string format back into its numeric value.
Simplex::Direction Direction
static bool isRangeDivisibleBy(ArrayRef< DynamicAPInt > range, const DynamicAPInt &divisor)
static SmallVector< DynamicAPInt, 8 > scaleAndAddForAssert(ArrayRef< DynamicAPInt > a, const DynamicAPInt &scale, ArrayRef< DynamicAPInt > b)
static IntMatrix identity(unsigned dimension)
Return the identity matrix of the specified dimension.
An IntegerRelation represents the set of points from a PresburgerSpace that satisfy a list of affine ...
ArrayRef< DynamicAPInt > getEquality(unsigned idx) const
ArrayRef< DynamicAPInt > getInequality(unsigned idx) const
unsigned getNumVars() const
unsigned getNumInequalities() const
unsigned getNumEqualities() const
void undoLastConstraint() final
Undo the addition of the last constraint.
LogicalResult moveRowUnknownToColumn(unsigned row)
Try to move the specified row to column orientation while preserving the lexicopositivity of the basi...
LogicalResult addCut(unsigned row)
Given a row that has a non-integer sample value, add an inequality to cut away this fractional sample...
unsigned getLexMinPivotColumn(unsigned row, unsigned colA, unsigned colB) const
Given two potential pivot columns for a row, return the one that results in the lexicographically sma...
void addInequality(ArrayRef< DynamicAPInt > coeffs) final
Add an inequality to the tableau.
unsigned getSnapshot()
Get a snapshot of the current state. This is used for rolling back.
void appendSymbol()
Add new symbolic variables to the end of the list of variables.
MaybeOptimum< SmallVector< Fraction, 8 > > findRationalLexMin()
Return the lexicographically minimum rational solution to the constraints.
bool isSeparateInequality(ArrayRef< DynamicAPInt > coeffs)
Return whether the specified inequality is redundant/separate for the polytope.
bool isRedundantInequality(ArrayRef< DynamicAPInt > coeffs)
MaybeOptimum< SmallVector< DynamicAPInt, 8 > > findIntegerLexMin()
Return the lexicographically minimum integer solution to the constraints.
unsigned getNumRows() const
MutableArrayRef< T > getRow(unsigned row)
Get a [Mutable]ArrayRef corresponding to the specified row.
void swapRows(unsigned row, unsigned otherRow)
Swap the given rows.
void addToRow(unsigned sourceRow, unsigned targetRow, const T &scale)
Add scale multiples of the source row to the target row.
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.
unsigned addZeroRow(bool makeRestricted=false)
Add a new row to the tableau and the associated data structures.
bool isEmpty() const
Returns true if the tableau is empty (has conflicting constraints), false otherwise.
void appendVariable(unsigned count=1)
Add new variables to the end of the list of variables.
virtual void undoLastConstraint()=0
Undo the addition of the last constraint.
SmallVector< int, 8 > rowUnknown
These hold the indexes of the unknown at a given row or column position.
SmallVector< SmallVector< int, 8 >, 8 > savedBases
Holds a vector of bases.
void intersectIntegerRelation(const IntegerRelation &rel)
Add all the constraints from the given IntegerRelation.
SmallVector< UndoLogEntry, 8 > undoLog
Holds a log of operations, used for rolling back to a previous state.
bool usingBigM
Stores whether or not a big M column is present in the tableau.
unsigned getSnapshot() const
Get a snapshot of the current state.
void print(raw_ostream &os) const
Print the tableau's internal state.
UndoLogEntry
Enum to denote operations that need to be undone during rollback.
unsigned getNumRows() const
const Unknown & unknownFromRow(unsigned row) const
Returns the unknown associated with row.
SmallVector< int, 8 > colUnknown
SmallVector< Unknown, 8 > var
void addEquality(ArrayRef< DynamicAPInt > coeffs)
Add an equality to the tableau.
unsigned getSnapshotBasis()
Get a snapshot of the current state including the basis.
unsigned getNumFixedCols() const
Return the number of fixed columns, as described in the constructor above, this is the number of colu...
SmallVector< Unknown, 8 > con
These hold information about each unknown.
void markEmpty()
Mark the tableau as being empty.
bool empty
This is true if the tableau has been detected to be empty, false otherwise.
void addDivisionVariable(ArrayRef< DynamicAPInt > coeffs, const DynamicAPInt &denom)
Append a new variable to the simplex and constrain it such that its only integer value is the floor d...
void swapColumns(unsigned i, unsigned j)
void removeLastConstraintRowOrientation()
Remove the last constraint, which must be in row orientation.
LLVM_DUMP_METHOD void dump() const
std::optional< unsigned > findAnyPivotRow(unsigned col)
Return any row that this column can be pivoted with, ignoring tableau consistency.
virtual void addInequality(ArrayRef< DynamicAPInt > coeffs)=0
Add an inequality to the tableau.
const Unknown & unknownFromColumn(unsigned col) const
Returns the unknown associated with col.
void rollback(unsigned snapshot)
Rollback to a snapshot. This invalidates all later snapshots.
IntMatrix tableau
The matrix representing the tableau.
void pivot(unsigned row, unsigned col)
Pivot the row with the column.
void swapRows(unsigned i, unsigned j)
Swap the two rows/columns in the tableau and associated data structures.
void undo(UndoLogEntry entry)
Undo the operation represented by the log entry.
const Unknown & unknownFromIndex(int index) const
Returns the unknown associated with index.
unsigned nSymbol
The number of parameters.
unsigned nRedundant
The number of redundant rows in the tableau.
unsigned addRow(ArrayRef< DynamicAPInt > coeffs, bool makeRestricted=false)
Add a new row to the tableau and the associated data structures.
unsigned getNumVariables() const
Returns the number of variables in the tableau.
void swapRowWithCol(unsigned row, unsigned col)
Swap the row with the column in the tableau's data structures but not the tableau itself.
unsigned getNumColumns() const
unsigned getNumConstraints() const
Returns the number of constraints in the tableau.
Takes a snapshot of the simplex state on construction and rolls back to the snapshot on destruction.
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.
std::optional< SmallVector< DynamicAPInt, 8 > > getSamplePointIfIntegral() const
Returns the current sample point if it is integral.
bool isFlatAlong(ArrayRef< DynamicAPInt > coeffs)
Check if the simplex takes only one rational value along the direction of coeffs.
bool isRedundantEquality(ArrayRef< DynamicAPInt > coeffs)
Check if the specified equality already holds in the polytope.
IneqType findIneqType(ArrayRef< DynamicAPInt > coeffs)
Returns the type of the inequality with coefficients coeffs.
static Simplex makeProduct(const Simplex &a, const Simplex &b)
Make a tableau to represent a pair of points in the given tableaus, one in tableau A and one in B.
MaybeOptimum< Fraction > computeRowOptimum(Direction direction, unsigned row)
Compute the maximum or minimum value of the given row, depending on direction.
bool isRationalSubsetOf(const IntegerRelation &rel)
Returns true if this Simplex's polytope is a rational subset of rel.
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.
bool isRedundantInequality(ArrayRef< DynamicAPInt > coeffs)
Check if the specified inequality already holds in the polytope.
void addInequality(ArrayRef< DynamicAPInt > coeffs) final
Add an inequality to the tableau.
MaybeOptimum< Fraction > computeOptimum(Direction direction, ArrayRef< DynamicAPInt > coeffs)
Compute the maximum or minimum value of the given expression, depending on direction.
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.
SymbolicLexOpt computeSymbolicIntegerLexMin()
The lexmin will be stored as a function lexopt from symbols to non-symbols in the result.
Given a simplex for a polytope, construct a new simplex whose variables are identified with a pair of...
Fraction computeWidthAndDuals(ArrayRef< DynamicAPInt > dir, SmallVectorImpl< DynamicAPInt > &dual, DynamicAPInt &dualDenom)
Compute max(dotProduct(dir, x - y)) and save the dual variables for only the direction equalities to ...
void removeLastEquality()
Remove the last equality that was added through addEqualityForDirection.
Fraction computeWidth(ArrayRef< DynamicAPInt > dir)
Compute max(dotProduct(dir, x - y)).
GBRSimplex(const Simplex &originalSimplex)
void addEqualityForDirection(ArrayRef< DynamicAPInt > dir)
Add an equality dotProduct(dir, x - y) == 0.
void normalizeDiv(MutableArrayRef< DynamicAPInt > num, DynamicAPInt &denom)
Normalize the given (numerator, denominator) pair by dividing out the common factors between them.
DynamicAPInt floor(const Fraction &f)
DynamicAPInt ceil(const Fraction &f)
void printWithPrintMetrics(raw_ostream &os, T val, unsigned minSpacing, const PrintTableMetrics &m)
Print val in the table with metrics specified in 'm'.
void updatePrintMetrics(T val, PrintTableMetrics &m)
Iterate over each val in the table and update 'm' where .maxPreIndent and .maxPostIndent are initiali...
DynamicAPInt normalizeRange(MutableArrayRef< DynamicAPInt > range)
Divide the range by its gcd and return the gcd.
SmallVector< DynamicAPInt, 8 > getComplementIneq(ArrayRef< DynamicAPInt > ineq)
Return the complement of the given inequality.
Include the generated interface declarations.
A class to represent fractions.
DynamicAPInt getAsInteger() const
The struct CountsSnapshot stores the count of each VarKind, and also of each constraint type.
Example usage: Print .12, 3.4, 56.7 preAlign = ".", minSpacing = 1, .12 .12 3.4 3....
An Unknown is either a variable or a constraint.
Represents the result of a symbolic lexicographic optimization computation.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.