1 //===- Simplex.cpp - MLIR Simplex Class -----------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "mlir/Analysis/Presburger/Simplex.h" 10 #include "mlir/Analysis/Presburger/Matrix.h" 11 #include "mlir/Support/MathExtras.h" 12 #include "llvm/ADT/Optional.h" 13 #include "llvm/Support/Compiler.h" 14 15 using namespace mlir; 16 using namespace presburger; 17 18 using Direction = Simplex::Direction; 19 20 const int nullIndex = std::numeric_limits<int>::max(); 21 22 // Return a + scale*b; 23 LLVM_ATTRIBUTE_UNUSED 24 static SmallVector<int64_t, 8> 25 scaleAndAddForAssert(ArrayRef<int64_t> a, int64_t scale, ArrayRef<int64_t> b) { 26 assert(a.size() == b.size()); 27 SmallVector<int64_t, 8> res; 28 res.reserve(a.size()); 29 for (unsigned i = 0, e = a.size(); i < e; ++i) 30 res.push_back(a[i] + scale * b[i]); 31 return res; 32 } 33 34 SimplexBase::SimplexBase(unsigned nVar, bool mustUseBigM, unsigned symbolOffset, 35 unsigned nSymbol) 36 : usingBigM(mustUseBigM), nRow(0), nCol(getNumFixedCols() + nVar), 37 nRedundant(0), nSymbol(nSymbol), tableau(0, nCol), empty(false) { 38 assert(symbolOffset + nSymbol <= nVar); 39 40 colUnknown.insert(colUnknown.begin(), getNumFixedCols(), nullIndex); 41 for (unsigned i = 0; i < nVar; ++i) { 42 var.emplace_back(Orientation::Column, /*restricted=*/false, 43 /*pos=*/getNumFixedCols() + i); 44 colUnknown.push_back(i); 45 } 46 47 // Move the symbols to be in columns [3, 3 + nSymbol). 48 for (unsigned i = 0; i < nSymbol; ++i) { 49 var[symbolOffset + i].isSymbol = true; 50 swapColumns(var[symbolOffset + i].pos, getNumFixedCols() + i); 51 } 52 } 53 54 const Simplex::Unknown &SimplexBase::unknownFromIndex(int index) const { 55 assert(index != nullIndex && "nullIndex passed to unknownFromIndex"); 56 return index >= 0 ? var[index] : con[~index]; 57 } 58 59 const Simplex::Unknown &SimplexBase::unknownFromColumn(unsigned col) const { 60 assert(col < nCol && "Invalid column"); 61 return unknownFromIndex(colUnknown[col]); 62 } 63 64 const Simplex::Unknown &SimplexBase::unknownFromRow(unsigned row) const { 65 assert(row < nRow && "Invalid row"); 66 return unknownFromIndex(rowUnknown[row]); 67 } 68 69 Simplex::Unknown &SimplexBase::unknownFromIndex(int index) { 70 assert(index != nullIndex && "nullIndex passed to unknownFromIndex"); 71 return index >= 0 ? var[index] : con[~index]; 72 } 73 74 Simplex::Unknown &SimplexBase::unknownFromColumn(unsigned col) { 75 assert(col < nCol && "Invalid column"); 76 return unknownFromIndex(colUnknown[col]); 77 } 78 79 Simplex::Unknown &SimplexBase::unknownFromRow(unsigned row) { 80 assert(row < nRow && "Invalid row"); 81 return unknownFromIndex(rowUnknown[row]); 82 } 83 84 unsigned SimplexBase::addZeroRow(bool makeRestricted) { 85 ++nRow; 86 // If the tableau is not big enough to accomodate the extra row, we extend it. 87 if (nRow >= tableau.getNumRows()) 88 tableau.resizeVertically(nRow); 89 rowUnknown.push_back(~con.size()); 90 con.emplace_back(Orientation::Row, makeRestricted, nRow - 1); 91 undoLog.push_back(UndoLogEntry::RemoveLastConstraint); 92 93 // Zero out the new row. 94 tableau.fillRow(nRow - 1, 0); 95 96 tableau(nRow - 1, 0) = 1; 97 return con.size() - 1; 98 } 99 100 /// Add a new row to the tableau corresponding to the given constant term and 101 /// list of coefficients. The coefficients are specified as a vector of 102 /// (variable index, coefficient) pairs. 103 unsigned SimplexBase::addRow(ArrayRef<int64_t> coeffs, bool makeRestricted) { 104 assert(coeffs.size() == var.size() + 1 && 105 "Incorrect number of coefficients!"); 106 107 addZeroRow(makeRestricted); 108 tableau(nRow - 1, 1) = coeffs.back(); 109 if (usingBigM) { 110 // When the lexicographic pivot rule is used, instead of the variables 111 // 112 // x, y, z ... 113 // 114 // we internally use the variables 115 // 116 // M, M + x, M + y, M + z, ... 117 // 118 // where M is the big M parameter. As such, when the user tries to add 119 // a row ax + by + cz + d, we express it in terms of our internal variables 120 // as -(a + b + c)M + a(M + x) + b(M + y) + c(M + z) + d. 121 // 122 // Symbols don't use the big M parameter since they do not get lex 123 // optimized. 124 int64_t bigMCoeff = 0; 125 for (unsigned i = 0; i < coeffs.size() - 1; ++i) 126 if (!var[i].isSymbol) 127 bigMCoeff -= coeffs[i]; 128 // The coefficient to the big M parameter is stored in column 2. 129 tableau(nRow - 1, 2) = bigMCoeff; 130 } 131 132 // Process each given variable coefficient. 133 for (unsigned i = 0; i < var.size(); ++i) { 134 unsigned pos = var[i].pos; 135 if (coeffs[i] == 0) 136 continue; 137 138 if (var[i].orientation == Orientation::Column) { 139 // If a variable is in column position at column col, then we just add the 140 // coefficient for that variable (scaled by the common row denominator) to 141 // the corresponding entry in the new row. 142 tableau(nRow - 1, pos) += coeffs[i] * tableau(nRow - 1, 0); 143 continue; 144 } 145 146 // If the variable is in row position, we need to add that row to the new 147 // row, scaled by the coefficient for the variable, accounting for the two 148 // rows potentially having different denominators. The new denominator is 149 // the lcm of the two. 150 int64_t lcm = mlir::lcm(tableau(nRow - 1, 0), tableau(pos, 0)); 151 int64_t nRowCoeff = lcm / tableau(nRow - 1, 0); 152 int64_t idxRowCoeff = coeffs[i] * (lcm / tableau(pos, 0)); 153 tableau(nRow - 1, 0) = lcm; 154 for (unsigned col = 1; col < nCol; ++col) 155 tableau(nRow - 1, col) = 156 nRowCoeff * tableau(nRow - 1, col) + idxRowCoeff * tableau(pos, col); 157 } 158 159 normalizeRow(nRow - 1); 160 // Push to undo log along with the index of the new constraint. 161 return con.size() - 1; 162 } 163 164 /// Normalize the row by removing factors that are common between the 165 /// denominator and all the numerator coefficients. 166 void SimplexBase::normalizeRow(unsigned row) { 167 int64_t gcd = 0; 168 for (unsigned col = 0; col < nCol; ++col) { 169 gcd = llvm::greatestCommonDivisor(gcd, std::abs(tableau(row, col))); 170 // If the gcd becomes 1 then the row is already normalized. 171 if (gcd == 1) 172 return; 173 } 174 175 // Note that the gcd can never become zero since the first element of the row, 176 // the denominator, is non-zero. 177 assert(gcd != 0); 178 for (unsigned col = 0; col < nCol; ++col) 179 tableau(row, col) /= gcd; 180 } 181 182 namespace { 183 bool signMatchesDirection(int64_t elem, Direction direction) { 184 assert(elem != 0 && "elem should not be 0"); 185 return direction == Direction::Up ? elem > 0 : elem < 0; 186 } 187 188 Direction flippedDirection(Direction direction) { 189 return direction == Direction::Up ? Direction::Down : Simplex::Direction::Up; 190 } 191 } // namespace 192 193 /// We simply make the tableau consistent while maintaining a lexicopositive 194 /// basis transform, and then return the sample value. If the tableau becomes 195 /// empty, we return empty. 196 /// 197 /// Let the variables be x = (x_1, ... x_n). 198 /// Let the basis unknowns be y = (y_1, ... y_n). 199 /// We have that x = A*y + b for some n x n matrix A and n x 1 column vector b. 200 /// 201 /// As we will show below, A*y is either zero or lexicopositive. 202 /// Adding a lexicopositive vector to b will make it lexicographically 203 /// greater, so A*y + b is always equal to or lexicographically greater than b. 204 /// Thus, since we can attain x = b, that is the lexicographic minimum. 205 /// 206 /// We have that that every column in A is lexicopositive, i.e., has at least 207 /// one non-zero element, with the first such element being positive. Since for 208 /// the tableau to be consistent we must have non-negative sample values not 209 /// only for the constraints but also for the variables, we also have x >= 0 and 210 /// y >= 0, by which we mean every element in these vectors is non-negative. 211 /// 212 /// Proof that if every column in A is lexicopositive, and y >= 0, then 213 /// A*y is zero or lexicopositive. Begin by considering A_1, the first row of A. 214 /// If this row is all zeros, then (A*y)_1 = (A_1)*y = 0; proceed to the next 215 /// row. If we run out of rows, A*y is zero and we are done; otherwise, we 216 /// encounter some row A_i that has a non-zero element. Every column is 217 /// lexicopositive and so has some positive element before any negative elements 218 /// occur, so the element in this row for any column, if non-zero, must be 219 /// positive. Consider (A*y)_i = (A_i)*y. All the elements in both vectors are 220 /// non-negative, so if this is non-zero then it must be positive. Then the 221 /// first non-zero element of A*y is positive so A*y is lexicopositive. 222 /// 223 /// Otherwise, if (A_i)*y is zero, then for every column j that had a non-zero 224 /// element in A_i, y_j is zero. Thus these columns have no contribution to A*y 225 /// and we can completely ignore these columns of A. We now continue downwards, 226 /// looking for rows of A that have a non-zero element other than in the ignored 227 /// columns. If we find one, say A_k, once again these elements must be positive 228 /// since they are the first non-zero element in each of these columns, so if 229 /// (A_k)*y is not zero then we have that A*y is lexicopositive and if not we 230 /// add these to the set of ignored columns and continue to the next row. If we 231 /// run out of rows, then A*y is zero and we are done. 232 MaybeOptimum<SmallVector<Fraction, 8>> LexSimplex::findRationalLexMin() { 233 if (restoreRationalConsistency().failed()) 234 return OptimumKind::Empty; 235 return getRationalSample(); 236 } 237 238 /// Given a row that has a non-integer sample value, add an inequality such 239 /// that this fractional sample value is cut away from the polytope. The added 240 /// inequality will be such that no integer points are removed. i.e., the 241 /// integer lexmin, if it exists, is the same with and without this constraint. 242 /// 243 /// Let the row be 244 /// (c + coeffM*M + a_1*s_1 + ... + a_m*s_m + b_1*y_1 + ... + b_n*y_n)/d, 245 /// where s_1, ... s_m are the symbols and 246 /// y_1, ... y_n are the other basis unknowns. 247 /// 248 /// For this to be an integer, we want 249 /// coeffM*M + a_1*s_1 + ... + a_m*s_m + b_1*y_1 + ... + b_n*y_n = -c (mod d) 250 /// Note that this constraint must always hold, independent of the basis, 251 /// becuse the row unknown's value always equals this expression, even if *we* 252 /// later compute the sample value from a different expression based on a 253 /// different basis. 254 /// 255 /// Let us assume that M has a factor of d in it. Imposing this constraint on M 256 /// does not in any way hinder us from finding a value of M that is big enough. 257 /// Moreover, this function is only called when the symbolic part of the sample, 258 /// a_1*s_1 + ... + a_m*s_m, is known to be an integer. 259 /// 260 /// Also, we can safely reduce the coefficients modulo d, so we have: 261 /// 262 /// (b_1%d)y_1 + ... + (b_n%d)y_n = (-c%d) + k*d for some integer `k` 263 /// 264 /// Note that all coefficient modulos here are non-negative. Also, all the 265 /// unknowns are non-negative here as both constraints and variables are 266 /// non-negative in LexSimplexBase. (We used the big M trick to make the 267 /// variables non-negative). Therefore, the LHS here is non-negative. 268 /// Since 0 <= (-c%d) < d, k is the quotient of dividing the LHS by d and 269 /// is therefore non-negative as well. 270 /// 271 /// So we have 272 /// ((b_1%d)y_1 + ... + (b_n%d)y_n - (-c%d))/d >= 0. 273 /// 274 /// The constraint is violated when added (it would be useless otherwise) 275 /// so we immediately try to move it to a column. 276 LogicalResult LexSimplexBase::addCut(unsigned row) { 277 int64_t d = tableau(row, 0); 278 addZeroRow(/*makeRestricted=*/true); 279 tableau(nRow - 1, 0) = d; 280 tableau(nRow - 1, 1) = -mod(-tableau(row, 1), d); // -c%d. 281 tableau(nRow - 1, 2) = 0; 282 for (unsigned col = 3 + nSymbol; col < nCol; ++col) 283 tableau(nRow - 1, col) = mod(tableau(row, col), d); // b_i%d. 284 return moveRowUnknownToColumn(nRow - 1); 285 } 286 287 Optional<unsigned> LexSimplex::maybeGetNonIntegralVarRow() const { 288 for (const Unknown &u : var) { 289 if (u.orientation == Orientation::Column) 290 continue; 291 // If the sample value is of the form (a/d)M + b/d, we need b to be 292 // divisible by d. We assume M contains all possible 293 // factors and is divisible by everything. 294 unsigned row = u.pos; 295 if (tableau(row, 1) % tableau(row, 0) != 0) 296 return row; 297 } 298 return {}; 299 } 300 301 MaybeOptimum<SmallVector<int64_t, 8>> LexSimplex::findIntegerLexMin() { 302 // We first try to make the tableau consistent. 303 if (restoreRationalConsistency().failed()) 304 return OptimumKind::Empty; 305 306 // Then, if the sample value is integral, we are done. 307 while (Optional<unsigned> maybeRow = maybeGetNonIntegralVarRow()) { 308 // Otherwise, for the variable whose row has a non-integral sample value, 309 // we add a cut, a constraint that remove this rational point 310 // while preserving all integer points, thus keeping the lexmin the same. 311 // We then again try to make the tableau with the new constraint 312 // consistent. This continues until the tableau becomes empty, in which 313 // case there is no integer point, or until there are no variables with 314 // non-integral sample values. 315 // 316 // Failure indicates that the tableau became empty, which occurs when the 317 // polytope is integer empty. 318 if (addCut(*maybeRow).failed()) 319 return OptimumKind::Empty; 320 if (restoreRationalConsistency().failed()) 321 return OptimumKind::Empty; 322 } 323 324 MaybeOptimum<SmallVector<Fraction, 8>> sample = getRationalSample(); 325 assert(!sample.isEmpty() && "If we reached here the sample should exist!"); 326 if (sample.isUnbounded()) 327 return OptimumKind::Unbounded; 328 return llvm::to_vector<8>( 329 llvm::map_range(*sample, std::mem_fn(&Fraction::getAsInteger))); 330 } 331 332 bool LexSimplex::isSeparateInequality(ArrayRef<int64_t> coeffs) { 333 SimplexRollbackScopeExit scopeExit(*this); 334 addInequality(coeffs); 335 return findIntegerLexMin().isEmpty(); 336 } 337 338 bool LexSimplex::isRedundantInequality(ArrayRef<int64_t> coeffs) { 339 return isSeparateInequality(getComplementIneq(coeffs)); 340 } 341 342 SmallVector<int64_t, 8> 343 SymbolicLexSimplex::getSymbolicSampleNumerator(unsigned row) const { 344 SmallVector<int64_t, 8> sample; 345 sample.reserve(nSymbol + 1); 346 for (unsigned col = 3; col < 3 + nSymbol; ++col) 347 sample.push_back(tableau(row, col)); 348 sample.push_back(tableau(row, 1)); 349 return sample; 350 } 351 352 void LexSimplexBase::appendSymbol() { 353 appendVariable(); 354 swapColumns(3 + nSymbol, nCol - 1); 355 var.back().isSymbol = true; 356 nSymbol++; 357 } 358 359 static bool isRangeDivisibleBy(ArrayRef<int64_t> range, int64_t divisor) { 360 assert(divisor > 0 && "divisor must be positive!"); 361 return llvm::all_of(range, [divisor](int64_t x) { return x % divisor == 0; }); 362 } 363 364 bool SymbolicLexSimplex::isSymbolicSampleIntegral(unsigned row) const { 365 int64_t denom = tableau(row, 0); 366 return tableau(row, 1) % denom == 0 && 367 isRangeDivisibleBy(tableau.getRow(row).slice(3, nSymbol), denom); 368 } 369 370 /// This proceeds similarly to LexSimplex::addCut(). We are given a row that has 371 /// a symbolic sample value with fractional coefficients. 372 /// 373 /// Let the row be 374 /// (c + coeffM*M + sum_i a_i*s_i + sum_j b_j*y_j)/d, 375 /// where s_1, ... s_m are the symbols and 376 /// y_1, ... y_n are the other basis unknowns. 377 /// 378 /// As in LexSimplex::addCut, for this to be an integer, we want 379 /// 380 /// coeffM*M + sum_j b_j*y_j = -c + sum_i (-a_i*s_i) (mod d) 381 /// 382 /// This time, a_1*s_1 + ... + a_m*s_m may not be an integer. We find that 383 /// 384 /// sum_i (b_i%d)y_i = ((-c%d) + sum_i (-a_i%d)s_i)%d + k*d for some integer k 385 /// 386 /// where we take a modulo of the whole symbolic expression on the right to 387 /// bring it into the range [0, d - 1]. Therefore, as in LexSimplex::addCut, 388 /// k is the quotient on dividing the LHS by d, and since LHS >= 0, we have 389 /// k >= 0 as well. We realize the modulo of the symbolic expression by adding a 390 /// division variable 391 /// 392 /// q = ((-c%d) + sum_i (-a_i%d)s_i)/d 393 /// 394 /// to the symbol domain, so the equality becomes 395 /// 396 /// sum_i (b_i%d)y_i = (-c%d) + sum_i (-a_i%d)s_i - q*d + k*d for some integer k 397 /// 398 /// So the cut is 399 /// (sum_i (b_i%d)y_i - (-c%d) - sum_i (-a_i%d)s_i + q*d)/d >= 0 400 /// This constraint is violated when added so we immediately try to move it to a 401 /// column. 402 LogicalResult SymbolicLexSimplex::addSymbolicCut(unsigned row) { 403 int64_t d = tableau(row, 0); 404 405 // Add the division variable `q` described above to the symbol domain. 406 // q = ((-c%d) + sum_i (-a_i%d)s_i)/d. 407 SmallVector<int64_t, 8> domainDivCoeffs; 408 domainDivCoeffs.reserve(nSymbol + 1); 409 for (unsigned col = 3; col < 3 + nSymbol; ++col) 410 domainDivCoeffs.push_back(mod(-tableau(row, col), d)); // (-a_i%d)s_i 411 domainDivCoeffs.push_back(mod(-tableau(row, 1), d)); // -c%d. 412 413 domainSimplex.addDivisionVariable(domainDivCoeffs, d); 414 domainPoly.addLocalFloorDiv(domainDivCoeffs, d); 415 416 // Update `this` to account for the additional symbol we just added. 417 appendSymbol(); 418 419 // Add the cut (sum_i (b_i%d)y_i - (-c%d) + sum_i -(-a_i%d)s_i + q*d)/d >= 0. 420 addZeroRow(/*makeRestricted=*/true); 421 tableau(nRow - 1, 0) = d; 422 tableau(nRow - 1, 2) = 0; 423 424 tableau(nRow - 1, 1) = -mod(-tableau(row, 1), d); // -(-c%d). 425 for (unsigned col = 3; col < 3 + nSymbol - 1; ++col) 426 tableau(nRow - 1, col) = -mod(-tableau(row, col), d); // -(-a_i%d)s_i. 427 tableau(nRow - 1, 3 + nSymbol - 1) = d; // q*d. 428 429 for (unsigned col = 3 + nSymbol; col < nCol; ++col) 430 tableau(nRow - 1, col) = mod(tableau(row, col), d); // (b_i%d)y_i. 431 return moveRowUnknownToColumn(nRow - 1); 432 } 433 434 void SymbolicLexSimplex::recordOutput(SymbolicLexMin &result) const { 435 Matrix output(0, domainPoly.getNumIds() + 1); 436 output.reserveRows(result.lexmin.getNumOutputs()); 437 for (const Unknown &u : var) { 438 if (u.isSymbol) 439 continue; 440 441 if (u.orientation == Orientation::Column) { 442 // M + u has a sample value of zero so u has a sample value of -M, i.e, 443 // unbounded. 444 result.unboundedDomain.unionInPlace(domainPoly); 445 return; 446 } 447 448 int64_t denom = tableau(u.pos, 0); 449 if (tableau(u.pos, 2) < denom) { 450 // M + u has a sample value of fM + something, where f < 1, so 451 // u = (f - 1)M + something, which has a negative coefficient for M, 452 // and so is unbounded. 453 result.unboundedDomain.unionInPlace(domainPoly); 454 return; 455 } 456 assert(tableau(u.pos, 2) == denom && 457 "Coefficient of M should not be greater than 1!"); 458 459 SmallVector<int64_t, 8> sample = getSymbolicSampleNumerator(u.pos); 460 for (int64_t &elem : sample) { 461 assert(elem % denom == 0 && "coefficients must be integral!"); 462 elem /= denom; 463 } 464 output.appendExtraRow(sample); 465 } 466 result.lexmin.addPiece(domainPoly, output); 467 } 468 469 Optional<unsigned> SymbolicLexSimplex::maybeGetAlwaysViolatedRow() { 470 // First look for rows that are clearly violated just from the big M 471 // coefficient, without needing to perform any simplex queries on the domain. 472 for (unsigned row = 0; row < nRow; ++row) 473 if (tableau(row, 2) < 0) 474 return row; 475 476 for (unsigned row = 0; row < nRow; ++row) { 477 if (tableau(row, 2) > 0) 478 continue; 479 if (domainSimplex.isSeparateInequality(getSymbolicSampleNumerator(row))) { 480 // Sample numerator always takes negative values in the symbol domain. 481 return row; 482 } 483 } 484 return {}; 485 } 486 487 Optional<unsigned> SymbolicLexSimplex::maybeGetNonIntegralVarRow() { 488 for (const Unknown &u : var) { 489 if (u.orientation == Orientation::Column) 490 continue; 491 assert(!u.isSymbol && "Symbol should not be in row orientation!"); 492 if (!isSymbolicSampleIntegral(u.pos)) 493 return u.pos; 494 } 495 return {}; 496 } 497 498 /// The non-branching pivots are just the ones moving the rows 499 /// that are always violated in the symbol domain. 500 LogicalResult SymbolicLexSimplex::doNonBranchingPivots() { 501 while (Optional<unsigned> row = maybeGetAlwaysViolatedRow()) 502 if (moveRowUnknownToColumn(*row).failed()) 503 return failure(); 504 return success(); 505 } 506 507 SymbolicLexMin SymbolicLexSimplex::computeSymbolicIntegerLexMin() { 508 SymbolicLexMin result(nSymbol, var.size() - nSymbol); 509 510 /// The algorithm is more naturally expressed recursively, but we implement 511 /// it iteratively here to avoid potential issues with stack overflows in the 512 /// compiler. We explicitly maintain the stack frames in a vector. 513 /// 514 /// To "recurse", we store the current "stack frame", i.e., state variables 515 /// that we will need when we "return", into `stack`, increment `level`, and 516 /// `continue`. To "tail recurse", we just `continue`. 517 /// To "return", we decrement `level` and `continue`. 518 /// 519 /// When there is no stack frame for the current `level`, this indicates that 520 /// we have just "recursed" or "tail recursed". When there does exist one, 521 /// this indicates that we have just "returned" from recursing. There is only 522 /// one point at which non-tail calls occur so we always "return" there. 523 unsigned level = 1; 524 struct StackFrame { 525 int splitIndex; 526 unsigned snapshot; 527 unsigned domainSnapshot; 528 IntegerRelation::CountsSnapshot domainPolyCounts; 529 }; 530 SmallVector<StackFrame, 8> stack; 531 532 while (level > 0) { 533 assert(level >= stack.size()); 534 if (level > stack.size()) { 535 if (empty || domainSimplex.findIntegerLexMin().isEmpty()) { 536 // No integer points; return. 537 --level; 538 continue; 539 } 540 541 if (doNonBranchingPivots().failed()) { 542 // Could not find pivots for violated constraints; return. 543 --level; 544 continue; 545 } 546 547 unsigned splitRow; 548 SmallVector<int64_t, 8> symbolicSample; 549 for (splitRow = 0; splitRow < nRow; ++splitRow) { 550 if (tableau(splitRow, 2) > 0) 551 continue; 552 assert(tableau(splitRow, 2) == 0 && 553 "Non-branching pivots should have been handled already!"); 554 555 symbolicSample = getSymbolicSampleNumerator(splitRow); 556 if (domainSimplex.isRedundantInequality(symbolicSample)) 557 continue; 558 559 // It's neither redundant nor separate, so it takes both positive and 560 // negative values, and hence constitutes a row for which we need to 561 // split the domain and separately run each case. 562 assert(!domainSimplex.isSeparateInequality(symbolicSample) && 563 "Non-branching pivots should have been handled already!"); 564 break; 565 } 566 567 if (splitRow < nRow) { 568 unsigned domainSnapshot = domainSimplex.getSnapshot(); 569 IntegerRelation::CountsSnapshot domainPolyCounts = 570 domainPoly.getCounts(); 571 572 // First, we consider the part of the domain where the row is not 573 // violated. We don't have to do any pivots for the row in this case, 574 // but we record the additional constraint that defines this part of 575 // the domain. 576 domainSimplex.addInequality(symbolicSample); 577 domainPoly.addInequality(symbolicSample); 578 579 // Recurse. 580 // 581 // On return, the basis as a set is preserved but not the internal 582 // ordering within rows or columns. Thus, we take note of the index of 583 // the Unknown that caused the split, which may be in a different 584 // row when we come back from recursing. We will need this to recurse 585 // on the other part of the split domain, where the row is violated. 586 // 587 // Note that we have to capture the index above and not a reference to 588 // the Unknown itself, since the array it lives in might get 589 // reallocated. 590 int splitIndex = rowUnknown[splitRow]; 591 unsigned snapshot = getSnapshot(); 592 stack.push_back( 593 {splitIndex, snapshot, domainSnapshot, domainPolyCounts}); 594 ++level; 595 continue; 596 } 597 598 // The tableau is rationally consistent for the current domain. 599 // Now we look for non-integral sample values and add cuts for them. 600 if (Optional<unsigned> row = maybeGetNonIntegralVarRow()) { 601 if (addSymbolicCut(*row).failed()) { 602 // No integral points; return. 603 --level; 604 continue; 605 } 606 607 // Rerun this level with the added cut constraint (tail recurse). 608 continue; 609 } 610 611 // Record output and return. 612 recordOutput(result); 613 --level; 614 continue; 615 } 616 617 if (level == stack.size()) { 618 // We have "returned" from "recursing". 619 const StackFrame &frame = stack.back(); 620 domainPoly.truncate(frame.domainPolyCounts); 621 domainSimplex.rollback(frame.domainSnapshot); 622 rollback(frame.snapshot); 623 const Unknown &u = unknownFromIndex(frame.splitIndex); 624 625 // Drop the frame. We don't need it anymore. 626 stack.pop_back(); 627 628 // Now we consider the part of the domain where the unknown `splitIndex` 629 // was negative. 630 assert(u.orientation == Orientation::Row && 631 "The split row should have been returned to row orientation!"); 632 SmallVector<int64_t, 8> splitIneq = 633 getComplementIneq(getSymbolicSampleNumerator(u.pos)); 634 if (moveRowUnknownToColumn(u.pos).failed()) { 635 // The unknown can't be made non-negative; return. 636 --level; 637 continue; 638 } 639 640 // The unknown can be made negative; recurse with the corresponding domain 641 // constraints. 642 domainSimplex.addInequality(splitIneq); 643 domainPoly.addInequality(splitIneq); 644 645 // We are now taking care of the second half of the domain and we don't 646 // need to do anything else here after returning, so it's a tail recurse. 647 continue; 648 } 649 } 650 651 return result; 652 } 653 654 bool LexSimplex::rowIsViolated(unsigned row) const { 655 if (tableau(row, 2) < 0) 656 return true; 657 if (tableau(row, 2) == 0 && tableau(row, 1) < 0) 658 return true; 659 return false; 660 } 661 662 Optional<unsigned> LexSimplex::maybeGetViolatedRow() const { 663 for (unsigned row = 0; row < nRow; ++row) 664 if (rowIsViolated(row)) 665 return row; 666 return {}; 667 } 668 669 /// We simply look for violated rows and keep trying to move them to column 670 /// orientation, which always succeeds unless the constraints have no solution 671 /// in which case we just give up and return. 672 LogicalResult LexSimplex::restoreRationalConsistency() { 673 if (empty) 674 return failure(); 675 while (Optional<unsigned> maybeViolatedRow = maybeGetViolatedRow()) 676 if (moveRowUnknownToColumn(*maybeViolatedRow).failed()) 677 return failure(); 678 return success(); 679 } 680 681 // Move the row unknown to column orientation while preserving lexicopositivity 682 // of the basis transform. The sample value of the row must be negative. 683 // 684 // We only consider pivots where the pivot element is positive. Suppose no such 685 // pivot exists, i.e., some violated row has no positive coefficient for any 686 // basis unknown. The row can be represented as (s + c_1*u_1 + ... + c_n*u_n)/d, 687 // where d is the denominator, s is the sample value and the c_i are the basis 688 // coefficients. Since any feasible assignment of the basis satisfies u_i >= 0 689 // for all i, and we have s < 0 as well as c_i < 0 for all i, any feasible 690 // assignment would violate this row and therefore the constraints have no 691 // solution. 692 // 693 // We can preserve lexicopositivity by picking the pivot column with positive 694 // pivot element that makes the lexicographically smallest change to the sample 695 // point. 696 // 697 // Proof. Let 698 // x = (x_1, ... x_n) be the variables, 699 // z = (z_1, ... z_m) be the constraints, 700 // y = (y_1, ... y_n) be the current basis, and 701 // define w = (x_1, ... x_n, z_1, ... z_m) = B*y + s. 702 // B is basically the simplex tableau of our implementation except that instead 703 // of only describing the transform to get back the non-basis unknowns, it 704 // defines the values of all the unknowns in terms of the basis unknowns. 705 // Similarly, s is the column for the sample value. 706 // 707 // Our goal is to show that each column in B, restricted to the first n 708 // rows, is lexicopositive after the pivot if it is so before. This is 709 // equivalent to saying the columns in the whole matrix are lexicopositive; 710 // there must be some non-zero element in every column in the first n rows since 711 // the n variables cannot be spanned without using all the n basis unknowns. 712 // 713 // Consider a pivot where z_i replaces y_j in the basis. Recall the pivot 714 // transform for the tableau derived for SimplexBase::pivot: 715 // 716 // pivot col other col pivot col other col 717 // pivot row a b -> pivot row 1/a -b/a 718 // other row c d other row c/a d - bc/a 719 // 720 // Similarly, a pivot results in B changing to B' and c to c'; the difference 721 // between the tableau and these matrices B and B' is that there is no special 722 // case for the pivot row, since it continues to represent the same unknown. The 723 // same formula applies for all rows: 724 // 725 // B'.col(j) = B.col(j) / B(i,j) 726 // B'.col(k) = B.col(k) - B(i,k) * B.col(j) / B(i,j) for k != j 727 // and similarly, s' = s - s_i * B.col(j) / B(i,j). 728 // 729 // Since the row is violated, we have s_i < 0, so the change in sample value 730 // when pivoting with column a is lexicographically smaller than that when 731 // pivoting with column b iff B.col(a) / B(i, a) is lexicographically smaller 732 // than B.col(b) / B(i, b). 733 // 734 // Since B(i, j) > 0, column j remains lexicopositive. 735 // 736 // For the other columns, suppose C.col(k) is not lexicopositive. 737 // This means that for some p, for all t < p, 738 // C(t,k) = 0 => B(t,k) = B(t,j) * B(i,k) / B(i,j) and 739 // C(t,k) < 0 => B(p,k) < B(t,j) * B(i,k) / B(i,j), 740 // which is in contradiction to the fact that B.col(j) / B(i,j) must be 741 // lexicographically smaller than B.col(k) / B(i,k), since it lexicographically 742 // minimizes the change in sample value. 743 LogicalResult LexSimplexBase::moveRowUnknownToColumn(unsigned row) { 744 Optional<unsigned> maybeColumn; 745 for (unsigned col = 3 + nSymbol; col < nCol; ++col) { 746 if (tableau(row, col) <= 0) 747 continue; 748 maybeColumn = 749 !maybeColumn ? col : getLexMinPivotColumn(row, *maybeColumn, col); 750 } 751 752 if (!maybeColumn) { 753 markEmpty(); 754 return failure(); 755 } 756 757 pivot(row, *maybeColumn); 758 return success(); 759 } 760 761 unsigned LexSimplexBase::getLexMinPivotColumn(unsigned row, unsigned colA, 762 unsigned colB) const { 763 // First, let's consider the non-symbolic case. 764 // A pivot causes the following change. (in the diagram the matrix elements 765 // are shown as rationals and there is no common denominator used) 766 // 767 // pivot col big M col const col 768 // pivot row a p b 769 // other row c q d 770 // | 771 // v 772 // 773 // pivot col big M col const col 774 // pivot row 1/a -p/a -b/a 775 // other row c/a q - pc/a d - bc/a 776 // 777 // Let the sample value of the pivot row be s = pM + b before the pivot. Since 778 // the pivot row represents a violated constraint we know that s < 0. 779 // 780 // If the variable is a non-pivot column, its sample value is zero before and 781 // after the pivot. 782 // 783 // If the variable is the pivot column, then its sample value goes from 0 to 784 // (-p/a)M + (-b/a), i.e. 0 to -(pM + b)/a. Thus the change in the sample 785 // value is -s/a. 786 // 787 // If the variable is the pivot row, its sample value goes from s to 0, for a 788 // change of -s. 789 // 790 // If the variable is a non-pivot row, its sample value changes from 791 // qM + d to qM + d + (-pc/a)M + (-bc/a). Thus the change in sample value 792 // is -(pM + b)(c/a) = -sc/a. 793 // 794 // Thus the change in sample value is either 0, -s/a, -s, or -sc/a. Here -s is 795 // fixed for all calls to this function since the row and tableau are fixed. 796 // The callee just wants to compare the return values with the return value of 797 // other invocations of the same function. So the -s is common for all 798 // comparisons involved and can be ignored, since -s is strictly positive. 799 // 800 // Thus we take away this common factor and just return 0, 1/a, 1, or c/a as 801 // appropriate. This allows us to run the entire algorithm treating M 802 // symbolically, as the pivot to be performed does not depend on the value 803 // of M, so long as the sample value s is negative. Note that this is not 804 // because of any special feature of M; by the same argument, we ignore the 805 // symbols too. The caller ensure that the sample value s is negative for 806 // all possible values of the symbols. 807 auto getSampleChangeCoeffForVar = [this, row](unsigned col, 808 const Unknown &u) -> Fraction { 809 int64_t a = tableau(row, col); 810 if (u.orientation == Orientation::Column) { 811 // Pivot column case. 812 if (u.pos == col) 813 return {1, a}; 814 815 // Non-pivot column case. 816 return {0, 1}; 817 } 818 819 // Pivot row case. 820 if (u.pos == row) 821 return {1, 1}; 822 823 // Non-pivot row case. 824 int64_t c = tableau(u.pos, col); 825 return {c, a}; 826 }; 827 828 for (const Unknown &u : var) { 829 Fraction changeA = getSampleChangeCoeffForVar(colA, u); 830 Fraction changeB = getSampleChangeCoeffForVar(colB, u); 831 if (changeA < changeB) 832 return colA; 833 if (changeA > changeB) 834 return colB; 835 } 836 837 // If we reached here, both result in exactly the same changes, so it 838 // doesn't matter which we return. 839 return colA; 840 } 841 842 /// Find a pivot to change the sample value of the row in the specified 843 /// direction. The returned pivot row will involve `row` if and only if the 844 /// unknown is unbounded in the specified direction. 845 /// 846 /// To increase (resp. decrease) the value of a row, we need to find a live 847 /// column with a non-zero coefficient. If the coefficient is positive, we need 848 /// to increase (decrease) the value of the column, and if the coefficient is 849 /// negative, we need to decrease (increase) the value of the column. Also, 850 /// we cannot decrease the sample value of restricted columns. 851 /// 852 /// If multiple columns are valid, we break ties by considering a lexicographic 853 /// ordering where we prefer unknowns with lower index. 854 Optional<SimplexBase::Pivot> Simplex::findPivot(int row, 855 Direction direction) const { 856 Optional<unsigned> col; 857 for (unsigned j = 2; j < nCol; ++j) { 858 int64_t elem = tableau(row, j); 859 if (elem == 0) 860 continue; 861 862 if (unknownFromColumn(j).restricted && 863 !signMatchesDirection(elem, direction)) 864 continue; 865 if (!col || colUnknown[j] < colUnknown[*col]) 866 col = j; 867 } 868 869 if (!col) 870 return {}; 871 872 Direction newDirection = 873 tableau(row, *col) < 0 ? flippedDirection(direction) : direction; 874 Optional<unsigned> maybePivotRow = findPivotRow(row, newDirection, *col); 875 return Pivot{maybePivotRow.getValueOr(row), *col}; 876 } 877 878 /// Swap the associated unknowns for the row and the column. 879 /// 880 /// First we swap the index associated with the row and column. Then we update 881 /// the unknowns to reflect their new position and orientation. 882 void SimplexBase::swapRowWithCol(unsigned row, unsigned col) { 883 std::swap(rowUnknown[row], colUnknown[col]); 884 Unknown &uCol = unknownFromColumn(col); 885 Unknown &uRow = unknownFromRow(row); 886 uCol.orientation = Orientation::Column; 887 uRow.orientation = Orientation::Row; 888 uCol.pos = col; 889 uRow.pos = row; 890 } 891 892 void SimplexBase::pivot(Pivot pair) { pivot(pair.row, pair.column); } 893 894 /// Pivot pivotRow and pivotCol. 895 /// 896 /// Let R be the pivot row unknown and let C be the pivot col unknown. 897 /// Since initially R = a*C + sum b_i * X_i 898 /// (where the sum is over the other column's unknowns, x_i) 899 /// C = (R - (sum b_i * X_i))/a 900 /// 901 /// Let u be some other row unknown. 902 /// u = c*C + sum d_i * X_i 903 /// So u = c*(R - sum b_i * X_i)/a + sum d_i * X_i 904 /// 905 /// This results in the following transform: 906 /// pivot col other col pivot col other col 907 /// pivot row a b -> pivot row 1/a -b/a 908 /// other row c d other row c/a d - bc/a 909 /// 910 /// Taking into account the common denominators p and q: 911 /// 912 /// pivot col other col pivot col other col 913 /// pivot row a/p b/p -> pivot row p/a -b/a 914 /// other row c/q d/q other row cp/aq (da - bc)/aq 915 /// 916 /// The pivot row transform is accomplished be swapping a with the pivot row's 917 /// common denominator and negating the pivot row except for the pivot column 918 /// element. 919 void SimplexBase::pivot(unsigned pivotRow, unsigned pivotCol) { 920 assert(pivotCol >= getNumFixedCols() && "Refusing to pivot invalid column"); 921 assert(!unknownFromColumn(pivotCol).isSymbol); 922 923 swapRowWithCol(pivotRow, pivotCol); 924 std::swap(tableau(pivotRow, 0), tableau(pivotRow, pivotCol)); 925 // We need to negate the whole pivot row except for the pivot column. 926 if (tableau(pivotRow, 0) < 0) { 927 // If the denominator is negative, we negate the row by simply negating the 928 // denominator. 929 tableau(pivotRow, 0) = -tableau(pivotRow, 0); 930 tableau(pivotRow, pivotCol) = -tableau(pivotRow, pivotCol); 931 } else { 932 for (unsigned col = 1; col < nCol; ++col) { 933 if (col == pivotCol) 934 continue; 935 tableau(pivotRow, col) = -tableau(pivotRow, col); 936 } 937 } 938 normalizeRow(pivotRow); 939 940 for (unsigned row = 0; row < nRow; ++row) { 941 if (row == pivotRow) 942 continue; 943 if (tableau(row, pivotCol) == 0) // Nothing to do. 944 continue; 945 tableau(row, 0) *= tableau(pivotRow, 0); 946 for (unsigned j = 1; j < nCol; ++j) { 947 if (j == pivotCol) 948 continue; 949 // Add rather than subtract because the pivot row has been negated. 950 tableau(row, j) = tableau(row, j) * tableau(pivotRow, 0) + 951 tableau(row, pivotCol) * tableau(pivotRow, j); 952 } 953 tableau(row, pivotCol) *= tableau(pivotRow, pivotCol); 954 normalizeRow(row); 955 } 956 } 957 958 /// Perform pivots until the unknown has a non-negative sample value or until 959 /// no more upward pivots can be performed. Return success if we were able to 960 /// bring the row to a non-negative sample value, and failure otherwise. 961 LogicalResult Simplex::restoreRow(Unknown &u) { 962 assert(u.orientation == Orientation::Row && 963 "unknown should be in row position"); 964 965 while (tableau(u.pos, 1) < 0) { 966 Optional<Pivot> maybePivot = findPivot(u.pos, Direction::Up); 967 if (!maybePivot) 968 break; 969 970 pivot(*maybePivot); 971 if (u.orientation == Orientation::Column) 972 return success(); // the unknown is unbounded above. 973 } 974 return success(tableau(u.pos, 1) >= 0); 975 } 976 977 /// Find a row that can be used to pivot the column in the specified direction. 978 /// This returns an empty optional if and only if the column is unbounded in the 979 /// specified direction (ignoring skipRow, if skipRow is set). 980 /// 981 /// If skipRow is set, this row is not considered, and (if it is restricted) its 982 /// restriction may be violated by the returned pivot. Usually, skipRow is set 983 /// because we don't want to move it to column position unless it is unbounded, 984 /// and we are either trying to increase the value of skipRow or explicitly 985 /// trying to make skipRow negative, so we are not concerned about this. 986 /// 987 /// If the direction is up (resp. down) and a restricted row has a negative 988 /// (positive) coefficient for the column, then this row imposes a bound on how 989 /// much the sample value of the column can change. Such a row with constant 990 /// term c and coefficient f for the column imposes a bound of c/|f| on the 991 /// change in sample value (in the specified direction). (note that c is 992 /// non-negative here since the row is restricted and the tableau is consistent) 993 /// 994 /// We iterate through the rows and pick the row which imposes the most 995 /// stringent bound, since pivoting with a row changes the row's sample value to 996 /// 0 and hence saturates the bound it imposes. We break ties between rows that 997 /// impose the same bound by considering a lexicographic ordering where we 998 /// prefer unknowns with lower index value. 999 Optional<unsigned> Simplex::findPivotRow(Optional<unsigned> skipRow, 1000 Direction direction, 1001 unsigned col) const { 1002 Optional<unsigned> retRow; 1003 // Initialize these to zero in order to silence a warning about retElem and 1004 // retConst being used uninitialized in the initialization of `diff` below. In 1005 // reality, these are always initialized when that line is reached since these 1006 // are set whenever retRow is set. 1007 int64_t retElem = 0, retConst = 0; 1008 for (unsigned row = nRedundant; row < nRow; ++row) { 1009 if (skipRow && row == *skipRow) 1010 continue; 1011 int64_t elem = tableau(row, col); 1012 if (elem == 0) 1013 continue; 1014 if (!unknownFromRow(row).restricted) 1015 continue; 1016 if (signMatchesDirection(elem, direction)) 1017 continue; 1018 int64_t constTerm = tableau(row, 1); 1019 1020 if (!retRow) { 1021 retRow = row; 1022 retElem = elem; 1023 retConst = constTerm; 1024 continue; 1025 } 1026 1027 int64_t diff = retConst * elem - constTerm * retElem; 1028 if ((diff == 0 && rowUnknown[row] < rowUnknown[*retRow]) || 1029 (diff != 0 && !signMatchesDirection(diff, direction))) { 1030 retRow = row; 1031 retElem = elem; 1032 retConst = constTerm; 1033 } 1034 } 1035 return retRow; 1036 } 1037 1038 bool SimplexBase::isEmpty() const { return empty; } 1039 1040 void SimplexBase::swapRows(unsigned i, unsigned j) { 1041 if (i == j) 1042 return; 1043 tableau.swapRows(i, j); 1044 std::swap(rowUnknown[i], rowUnknown[j]); 1045 unknownFromRow(i).pos = i; 1046 unknownFromRow(j).pos = j; 1047 } 1048 1049 void SimplexBase::swapColumns(unsigned i, unsigned j) { 1050 assert(i < nCol && j < nCol && "Invalid columns provided!"); 1051 if (i == j) 1052 return; 1053 tableau.swapColumns(i, j); 1054 std::swap(colUnknown[i], colUnknown[j]); 1055 unknownFromColumn(i).pos = i; 1056 unknownFromColumn(j).pos = j; 1057 } 1058 1059 /// Mark this tableau empty and push an entry to the undo stack. 1060 void SimplexBase::markEmpty() { 1061 // If the set is already empty, then we shouldn't add another UnmarkEmpty log 1062 // entry, since in that case the Simplex will be erroneously marked as 1063 // non-empty when rolling back past this point. 1064 if (empty) 1065 return; 1066 undoLog.push_back(UndoLogEntry::UnmarkEmpty); 1067 empty = true; 1068 } 1069 1070 /// Add an inequality to the tableau. If coeffs is c_0, c_1, ... c_n, where n 1071 /// is the current number of variables, then the corresponding inequality is 1072 /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} >= 0. 1073 /// 1074 /// We add the inequality and mark it as restricted. We then try to make its 1075 /// sample value non-negative. If this is not possible, the tableau has become 1076 /// empty and we mark it as such. 1077 void Simplex::addInequality(ArrayRef<int64_t> coeffs) { 1078 unsigned conIndex = addRow(coeffs, /*makeRestricted=*/true); 1079 LogicalResult result = restoreRow(con[conIndex]); 1080 if (failed(result)) 1081 markEmpty(); 1082 } 1083 1084 /// Add an equality to the tableau. If coeffs is c_0, c_1, ... c_n, where n 1085 /// is the current number of variables, then the corresponding equality is 1086 /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} == 0. 1087 /// 1088 /// We simply add two opposing inequalities, which force the expression to 1089 /// be zero. 1090 void SimplexBase::addEquality(ArrayRef<int64_t> coeffs) { 1091 addInequality(coeffs); 1092 SmallVector<int64_t, 8> negatedCoeffs; 1093 for (int64_t coeff : coeffs) 1094 negatedCoeffs.emplace_back(-coeff); 1095 addInequality(negatedCoeffs); 1096 } 1097 1098 unsigned SimplexBase::getNumVariables() const { return var.size(); } 1099 unsigned SimplexBase::getNumConstraints() const { return con.size(); } 1100 1101 /// Return a snapshot of the current state. This is just the current size of the 1102 /// undo log. 1103 unsigned SimplexBase::getSnapshot() const { return undoLog.size(); } 1104 1105 unsigned SimplexBase::getSnapshotBasis() { 1106 SmallVector<int, 8> basis; 1107 for (int index : colUnknown) { 1108 if (index != nullIndex) 1109 basis.push_back(index); 1110 } 1111 savedBases.push_back(std::move(basis)); 1112 1113 undoLog.emplace_back(UndoLogEntry::RestoreBasis); 1114 return undoLog.size() - 1; 1115 } 1116 1117 void SimplexBase::removeLastConstraintRowOrientation() { 1118 assert(con.back().orientation == Orientation::Row); 1119 1120 // Move this unknown to the last row and remove the last row from the 1121 // tableau. 1122 swapRows(con.back().pos, nRow - 1); 1123 // It is not strictly necessary to shrink the tableau, but for now we 1124 // maintain the invariant that the tableau has exactly nRow rows. 1125 tableau.resizeVertically(nRow - 1); 1126 nRow--; 1127 rowUnknown.pop_back(); 1128 con.pop_back(); 1129 } 1130 1131 // This doesn't find a pivot row only if the column has zero 1132 // coefficients for every row. 1133 // 1134 // If the unknown is a constraint, this can't happen, since it was added 1135 // initially as a row. Such a row could never have been pivoted to a column. So 1136 // a pivot row will always be found if we have a constraint. 1137 // 1138 // If we have a variable, then the column has zero coefficients for every row 1139 // iff no constraints have been added with a non-zero coefficient for this row. 1140 Optional<unsigned> SimplexBase::findAnyPivotRow(unsigned col) { 1141 for (unsigned row = nRedundant; row < nRow; ++row) 1142 if (tableau(row, col) != 0) 1143 return row; 1144 return {}; 1145 } 1146 1147 // It's not valid to remove the constraint by deleting the column since this 1148 // would result in an invalid basis. 1149 void Simplex::undoLastConstraint() { 1150 if (con.back().orientation == Orientation::Column) { 1151 // We try to find any pivot row for this column that preserves tableau 1152 // consistency (except possibly the column itself, which is going to be 1153 // deallocated anyway). 1154 // 1155 // If no pivot row is found in either direction, then the unknown is 1156 // unbounded in both directions and we are free to perform any pivot at 1157 // all. To do this, we just need to find any row with a non-zero 1158 // coefficient for the column. findAnyPivotRow will always be able to 1159 // find such a row for a constraint. 1160 unsigned column = con.back().pos; 1161 if (Optional<unsigned> maybeRow = findPivotRow({}, Direction::Up, column)) { 1162 pivot(*maybeRow, column); 1163 } else if (Optional<unsigned> maybeRow = 1164 findPivotRow({}, Direction::Down, column)) { 1165 pivot(*maybeRow, column); 1166 } else { 1167 Optional<unsigned> row = findAnyPivotRow(column); 1168 assert(row.hasValue() && "Pivot should always exist for a constraint!"); 1169 pivot(*row, column); 1170 } 1171 } 1172 removeLastConstraintRowOrientation(); 1173 } 1174 1175 // It's not valid to remove the constraint by deleting the column since this 1176 // would result in an invalid basis. 1177 void LexSimplexBase::undoLastConstraint() { 1178 if (con.back().orientation == Orientation::Column) { 1179 // When removing the last constraint during a rollback, we just need to find 1180 // any pivot at all, i.e., any row with non-zero coefficient for the 1181 // column, because when rolling back a lexicographic simplex, we always 1182 // end by restoring the exact basis that was present at the time of the 1183 // snapshot, so what pivots we perform while undoing doesn't matter as 1184 // long as we get the unknown to row orientation and remove it. 1185 unsigned column = con.back().pos; 1186 Optional<unsigned> row = findAnyPivotRow(column); 1187 assert(row.hasValue() && "Pivot should always exist for a constraint!"); 1188 pivot(*row, column); 1189 } 1190 removeLastConstraintRowOrientation(); 1191 } 1192 1193 void SimplexBase::undo(UndoLogEntry entry) { 1194 if (entry == UndoLogEntry::RemoveLastConstraint) { 1195 // Simplex and LexSimplex handle this differently, so we call out to a 1196 // virtual function to handle this. 1197 undoLastConstraint(); 1198 } else if (entry == UndoLogEntry::RemoveLastVariable) { 1199 // Whenever we are rolling back the addition of a variable, it is guaranteed 1200 // that the variable will be in column position. 1201 // 1202 // We can see this as follows: any constraint that depends on this variable 1203 // was added after this variable was added, so the addition of such 1204 // constraints should already have been rolled back by the time we get to 1205 // rolling back the addition of the variable. Therefore, no constraint 1206 // currently has a component along the variable, so the variable itself must 1207 // be part of the basis. 1208 assert(var.back().orientation == Orientation::Column && 1209 "Variable to be removed must be in column orientation!"); 1210 1211 if (var.back().isSymbol) 1212 nSymbol--; 1213 1214 // Move this variable to the last column and remove the column from the 1215 // tableau. 1216 swapColumns(var.back().pos, nCol - 1); 1217 tableau.resizeHorizontally(nCol - 1); 1218 var.pop_back(); 1219 colUnknown.pop_back(); 1220 nCol--; 1221 } else if (entry == UndoLogEntry::UnmarkEmpty) { 1222 empty = false; 1223 } else if (entry == UndoLogEntry::UnmarkLastRedundant) { 1224 nRedundant--; 1225 } else if (entry == UndoLogEntry::RestoreBasis) { 1226 assert(!savedBases.empty() && "No bases saved!"); 1227 1228 SmallVector<int, 8> basis = std::move(savedBases.back()); 1229 savedBases.pop_back(); 1230 1231 for (int index : basis) { 1232 Unknown &u = unknownFromIndex(index); 1233 if (u.orientation == Orientation::Column) 1234 continue; 1235 for (unsigned col = getNumFixedCols(); col < nCol; col++) { 1236 assert(colUnknown[col] != nullIndex && 1237 "Column should not be a fixed column!"); 1238 if (std::find(basis.begin(), basis.end(), colUnknown[col]) != 1239 basis.end()) 1240 continue; 1241 if (tableau(u.pos, col) == 0) 1242 continue; 1243 pivot(u.pos, col); 1244 break; 1245 } 1246 1247 assert(u.orientation == Orientation::Column && "No pivot found!"); 1248 } 1249 } 1250 } 1251 1252 /// Rollback to the specified snapshot. 1253 /// 1254 /// We undo all the log entries until the log size when the snapshot was taken 1255 /// is reached. 1256 void SimplexBase::rollback(unsigned snapshot) { 1257 while (undoLog.size() > snapshot) { 1258 undo(undoLog.back()); 1259 undoLog.pop_back(); 1260 } 1261 } 1262 1263 /// We add the usual floor division constraints: 1264 /// `0 <= coeffs - denom*q <= denom - 1`, where `q` is the new division 1265 /// variable. 1266 /// 1267 /// This constrains the remainder `coeffs - denom*q` to be in the 1268 /// range `[0, denom - 1]`, which fixes the integer value of the quotient `q`. 1269 void SimplexBase::addDivisionVariable(ArrayRef<int64_t> coeffs, int64_t denom) { 1270 assert(denom != 0 && "Cannot divide by zero!\n"); 1271 appendVariable(); 1272 1273 SmallVector<int64_t, 8> ineq(coeffs.begin(), coeffs.end()); 1274 int64_t constTerm = ineq.back(); 1275 ineq.back() = -denom; 1276 ineq.push_back(constTerm); 1277 addInequality(ineq); 1278 1279 for (int64_t &coeff : ineq) 1280 coeff = -coeff; 1281 ineq.back() += denom - 1; 1282 addInequality(ineq); 1283 } 1284 1285 void SimplexBase::appendVariable(unsigned count) { 1286 if (count == 0) 1287 return; 1288 var.reserve(var.size() + count); 1289 colUnknown.reserve(colUnknown.size() + count); 1290 for (unsigned i = 0; i < count; ++i) { 1291 nCol++; 1292 var.emplace_back(Orientation::Column, /*restricted=*/false, 1293 /*pos=*/nCol - 1); 1294 colUnknown.push_back(var.size() - 1); 1295 } 1296 tableau.resizeHorizontally(nCol); 1297 undoLog.insert(undoLog.end(), count, UndoLogEntry::RemoveLastVariable); 1298 } 1299 1300 /// Add all the constraints from the given IntegerRelation. 1301 void SimplexBase::intersectIntegerRelation(const IntegerRelation &rel) { 1302 assert(rel.getNumIds() == getNumVariables() && 1303 "IntegerRelation must have same dimensionality as simplex"); 1304 for (unsigned i = 0, e = rel.getNumInequalities(); i < e; ++i) 1305 addInequality(rel.getInequality(i)); 1306 for (unsigned i = 0, e = rel.getNumEqualities(); i < e; ++i) 1307 addEquality(rel.getEquality(i)); 1308 } 1309 1310 MaybeOptimum<Fraction> Simplex::computeRowOptimum(Direction direction, 1311 unsigned row) { 1312 // Keep trying to find a pivot for the row in the specified direction. 1313 while (Optional<Pivot> maybePivot = findPivot(row, direction)) { 1314 // If findPivot returns a pivot involving the row itself, then the optimum 1315 // is unbounded, so we return None. 1316 if (maybePivot->row == row) 1317 return OptimumKind::Unbounded; 1318 pivot(*maybePivot); 1319 } 1320 1321 // The row has reached its optimal sample value, which we return. 1322 // The sample value is the entry in the constant column divided by the common 1323 // denominator for this row. 1324 return Fraction(tableau(row, 1), tableau(row, 0)); 1325 } 1326 1327 /// Compute the optimum of the specified expression in the specified direction, 1328 /// or None if it is unbounded. 1329 MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction, 1330 ArrayRef<int64_t> coeffs) { 1331 if (empty) 1332 return OptimumKind::Empty; 1333 1334 SimplexRollbackScopeExit scopeExit(*this); 1335 unsigned conIndex = addRow(coeffs); 1336 unsigned row = con[conIndex].pos; 1337 MaybeOptimum<Fraction> optimum = computeRowOptimum(direction, row); 1338 return optimum; 1339 } 1340 1341 MaybeOptimum<Fraction> Simplex::computeOptimum(Direction direction, 1342 Unknown &u) { 1343 if (empty) 1344 return OptimumKind::Empty; 1345 if (u.orientation == Orientation::Column) { 1346 unsigned column = u.pos; 1347 Optional<unsigned> pivotRow = findPivotRow({}, direction, column); 1348 // If no pivot is returned, the constraint is unbounded in the specified 1349 // direction. 1350 if (!pivotRow) 1351 return OptimumKind::Unbounded; 1352 pivot(*pivotRow, column); 1353 } 1354 1355 unsigned row = u.pos; 1356 MaybeOptimum<Fraction> optimum = computeRowOptimum(direction, row); 1357 if (u.restricted && direction == Direction::Down && 1358 (optimum.isUnbounded() || *optimum < Fraction(0, 1))) { 1359 if (failed(restoreRow(u))) 1360 llvm_unreachable("Could not restore row!"); 1361 } 1362 return optimum; 1363 } 1364 1365 bool Simplex::isBoundedAlongConstraint(unsigned constraintIndex) { 1366 assert(!empty && "It is not meaningful to ask whether a direction is bounded " 1367 "in an empty set."); 1368 // The constraint's perpendicular is already bounded below, since it is a 1369 // constraint. If it is also bounded above, we can return true. 1370 return computeOptimum(Direction::Up, con[constraintIndex]).isBounded(); 1371 } 1372 1373 /// Redundant constraints are those that are in row orientation and lie in 1374 /// rows 0 to nRedundant - 1. 1375 bool Simplex::isMarkedRedundant(unsigned constraintIndex) const { 1376 const Unknown &u = con[constraintIndex]; 1377 return u.orientation == Orientation::Row && u.pos < nRedundant; 1378 } 1379 1380 /// Mark the specified row redundant. 1381 /// 1382 /// This is done by moving the unknown to the end of the block of redundant 1383 /// rows (namely, to row nRedundant) and incrementing nRedundant to 1384 /// accomodate the new redundant row. 1385 void Simplex::markRowRedundant(Unknown &u) { 1386 assert(u.orientation == Orientation::Row && 1387 "Unknown should be in row position!"); 1388 assert(u.pos >= nRedundant && "Unknown is already marked redundant!"); 1389 swapRows(u.pos, nRedundant); 1390 ++nRedundant; 1391 undoLog.emplace_back(UndoLogEntry::UnmarkLastRedundant); 1392 } 1393 1394 /// Find a subset of constraints that is redundant and mark them redundant. 1395 void Simplex::detectRedundant() { 1396 // It is not meaningful to talk about redundancy for empty sets. 1397 if (empty) 1398 return; 1399 1400 // Iterate through the constraints and check for each one if it can attain 1401 // negative sample values. If it can, it's not redundant. Otherwise, it is. 1402 // We mark redundant constraints redundant. 1403 // 1404 // Constraints that get marked redundant in one iteration are not respected 1405 // when checking constraints in later iterations. This prevents, for example, 1406 // two identical constraints both being marked redundant since each is 1407 // redundant given the other one. In this example, only the first of the 1408 // constraints that is processed will get marked redundant, as it should be. 1409 for (Unknown &u : con) { 1410 if (u.orientation == Orientation::Column) { 1411 unsigned column = u.pos; 1412 Optional<unsigned> pivotRow = findPivotRow({}, Direction::Down, column); 1413 // If no downward pivot is returned, the constraint is unbounded below 1414 // and hence not redundant. 1415 if (!pivotRow) 1416 continue; 1417 pivot(*pivotRow, column); 1418 } 1419 1420 unsigned row = u.pos; 1421 MaybeOptimum<Fraction> minimum = computeRowOptimum(Direction::Down, row); 1422 if (minimum.isUnbounded() || *minimum < Fraction(0, 1)) { 1423 // Constraint is unbounded below or can attain negative sample values and 1424 // hence is not redundant. 1425 if (failed(restoreRow(u))) 1426 llvm_unreachable("Could not restore non-redundant row!"); 1427 continue; 1428 } 1429 1430 markRowRedundant(u); 1431 } 1432 } 1433 1434 bool Simplex::isUnbounded() { 1435 if (empty) 1436 return false; 1437 1438 SmallVector<int64_t, 8> dir(var.size() + 1); 1439 for (unsigned i = 0; i < var.size(); ++i) { 1440 dir[i] = 1; 1441 1442 if (computeOptimum(Direction::Up, dir).isUnbounded()) 1443 return true; 1444 1445 if (computeOptimum(Direction::Down, dir).isUnbounded()) 1446 return true; 1447 1448 dir[i] = 0; 1449 } 1450 return false; 1451 } 1452 1453 /// Make a tableau to represent a pair of points in the original tableau. 1454 /// 1455 /// The product constraints and variables are stored as: first A's, then B's. 1456 /// 1457 /// The product tableau has row layout: 1458 /// A's redundant rows, B's redundant rows, A's other rows, B's other rows. 1459 /// 1460 /// It has column layout: 1461 /// denominator, constant, A's columns, B's columns. 1462 Simplex Simplex::makeProduct(const Simplex &a, const Simplex &b) { 1463 unsigned numVar = a.getNumVariables() + b.getNumVariables(); 1464 unsigned numCon = a.getNumConstraints() + b.getNumConstraints(); 1465 Simplex result(numVar); 1466 1467 result.tableau.resizeVertically(numCon); 1468 result.empty = a.empty || b.empty; 1469 1470 auto concat = [](ArrayRef<Unknown> v, ArrayRef<Unknown> w) { 1471 SmallVector<Unknown, 8> result; 1472 result.reserve(v.size() + w.size()); 1473 result.insert(result.end(), v.begin(), v.end()); 1474 result.insert(result.end(), w.begin(), w.end()); 1475 return result; 1476 }; 1477 result.con = concat(a.con, b.con); 1478 result.var = concat(a.var, b.var); 1479 1480 auto indexFromBIndex = [&](int index) { 1481 return index >= 0 ? a.getNumVariables() + index 1482 : ~(a.getNumConstraints() + ~index); 1483 }; 1484 1485 result.colUnknown.assign(2, nullIndex); 1486 for (unsigned i = 2; i < a.nCol; ++i) { 1487 result.colUnknown.push_back(a.colUnknown[i]); 1488 result.unknownFromIndex(result.colUnknown.back()).pos = 1489 result.colUnknown.size() - 1; 1490 } 1491 for (unsigned i = 2; i < b.nCol; ++i) { 1492 result.colUnknown.push_back(indexFromBIndex(b.colUnknown[i])); 1493 result.unknownFromIndex(result.colUnknown.back()).pos = 1494 result.colUnknown.size() - 1; 1495 } 1496 1497 auto appendRowFromA = [&](unsigned row) { 1498 for (unsigned col = 0; col < a.nCol; ++col) 1499 result.tableau(result.nRow, col) = a.tableau(row, col); 1500 result.rowUnknown.push_back(a.rowUnknown[row]); 1501 result.unknownFromIndex(result.rowUnknown.back()).pos = 1502 result.rowUnknown.size() - 1; 1503 result.nRow++; 1504 }; 1505 1506 // Also fixes the corresponding entry in rowUnknown and var/con (as the case 1507 // may be). 1508 auto appendRowFromB = [&](unsigned row) { 1509 result.tableau(result.nRow, 0) = b.tableau(row, 0); 1510 result.tableau(result.nRow, 1) = b.tableau(row, 1); 1511 1512 unsigned offset = a.nCol - 2; 1513 for (unsigned col = 2; col < b.nCol; ++col) 1514 result.tableau(result.nRow, offset + col) = b.tableau(row, col); 1515 result.rowUnknown.push_back(indexFromBIndex(b.rowUnknown[row])); 1516 result.unknownFromIndex(result.rowUnknown.back()).pos = 1517 result.rowUnknown.size() - 1; 1518 result.nRow++; 1519 }; 1520 1521 result.nRedundant = a.nRedundant + b.nRedundant; 1522 for (unsigned row = 0; row < a.nRedundant; ++row) 1523 appendRowFromA(row); 1524 for (unsigned row = 0; row < b.nRedundant; ++row) 1525 appendRowFromB(row); 1526 for (unsigned row = a.nRedundant; row < a.nRow; ++row) 1527 appendRowFromA(row); 1528 for (unsigned row = b.nRedundant; row < b.nRow; ++row) 1529 appendRowFromB(row); 1530 1531 return result; 1532 } 1533 1534 Optional<SmallVector<Fraction, 8>> Simplex::getRationalSample() const { 1535 if (empty) 1536 return {}; 1537 1538 SmallVector<Fraction, 8> sample; 1539 sample.reserve(var.size()); 1540 // Push the sample value for each variable into the vector. 1541 for (const Unknown &u : var) { 1542 if (u.orientation == Orientation::Column) { 1543 // If the variable is in column position, its sample value is zero. 1544 sample.emplace_back(0, 1); 1545 } else { 1546 // If the variable is in row position, its sample value is the 1547 // entry in the constant column divided by the denominator. 1548 int64_t denom = tableau(u.pos, 0); 1549 sample.emplace_back(tableau(u.pos, 1), denom); 1550 } 1551 } 1552 return sample; 1553 } 1554 1555 void LexSimplexBase::addInequality(ArrayRef<int64_t> coeffs) { 1556 addRow(coeffs, /*makeRestricted=*/true); 1557 } 1558 1559 MaybeOptimum<SmallVector<Fraction, 8>> LexSimplex::getRationalSample() const { 1560 if (empty) 1561 return OptimumKind::Empty; 1562 1563 SmallVector<Fraction, 8> sample; 1564 sample.reserve(var.size()); 1565 // Push the sample value for each variable into the vector. 1566 for (const Unknown &u : var) { 1567 // When the big M parameter is being used, each variable x is represented 1568 // as M + x, so its sample value is finite if and only if it is of the 1569 // form 1*M + c. If the coefficient of M is not one then the sample value 1570 // is infinite, and we return an empty optional. 1571 1572 if (u.orientation == Orientation::Column) { 1573 // If the variable is in column position, the sample value of M + x is 1574 // zero, so x = -M which is unbounded. 1575 return OptimumKind::Unbounded; 1576 } 1577 1578 // If the variable is in row position, its sample value is the 1579 // entry in the constant column divided by the denominator. 1580 int64_t denom = tableau(u.pos, 0); 1581 if (usingBigM) 1582 if (tableau(u.pos, 2) != denom) 1583 return OptimumKind::Unbounded; 1584 sample.emplace_back(tableau(u.pos, 1), denom); 1585 } 1586 return sample; 1587 } 1588 1589 Optional<SmallVector<int64_t, 8>> Simplex::getSamplePointIfIntegral() const { 1590 // If the tableau is empty, no sample point exists. 1591 if (empty) 1592 return {}; 1593 1594 // The value will always exist since the Simplex is non-empty. 1595 SmallVector<Fraction, 8> rationalSample = *getRationalSample(); 1596 SmallVector<int64_t, 8> integerSample; 1597 integerSample.reserve(var.size()); 1598 for (const Fraction &coord : rationalSample) { 1599 // If the sample is non-integral, return None. 1600 if (coord.num % coord.den != 0) 1601 return {}; 1602 integerSample.push_back(coord.num / coord.den); 1603 } 1604 return integerSample; 1605 } 1606 1607 /// Given a simplex for a polytope, construct a new simplex whose variables are 1608 /// identified with a pair of points (x, y) in the original polytope. Supports 1609 /// some operations needed for generalized basis reduction. In what follows, 1610 /// dotProduct(x, y) = x_1 * y_1 + x_2 * y_2 + ... x_n * y_n where n is the 1611 /// dimension of the original polytope. 1612 /// 1613 /// This supports adding equality constraints dotProduct(dir, x - y) == 0. It 1614 /// also supports rolling back this addition, by maintaining a snapshot stack 1615 /// that contains a snapshot of the Simplex's state for each equality, just 1616 /// before that equality was added. 1617 class presburger::GBRSimplex { 1618 using Orientation = Simplex::Orientation; 1619 1620 public: 1621 GBRSimplex(const Simplex &originalSimplex) 1622 : simplex(Simplex::makeProduct(originalSimplex, originalSimplex)), 1623 simplexConstraintOffset(simplex.getNumConstraints()) {} 1624 1625 /// Add an equality dotProduct(dir, x - y) == 0. 1626 /// First pushes a snapshot for the current simplex state to the stack so 1627 /// that this can be rolled back later. 1628 void addEqualityForDirection(ArrayRef<int64_t> dir) { 1629 assert(llvm::any_of(dir, [](int64_t x) { return x != 0; }) && 1630 "Direction passed is the zero vector!"); 1631 snapshotStack.push_back(simplex.getSnapshot()); 1632 simplex.addEquality(getCoeffsForDirection(dir)); 1633 } 1634 /// Compute max(dotProduct(dir, x - y)). 1635 Fraction computeWidth(ArrayRef<int64_t> dir) { 1636 MaybeOptimum<Fraction> maybeWidth = 1637 simplex.computeOptimum(Direction::Up, getCoeffsForDirection(dir)); 1638 assert(maybeWidth.isBounded() && "Width should be bounded!"); 1639 return *maybeWidth; 1640 } 1641 1642 /// Compute max(dotProduct(dir, x - y)) and save the dual variables for only 1643 /// the direction equalities to `dual`. 1644 Fraction computeWidthAndDuals(ArrayRef<int64_t> dir, 1645 SmallVectorImpl<int64_t> &dual, 1646 int64_t &dualDenom) { 1647 // We can't just call into computeWidth or computeOptimum since we need to 1648 // access the state of the tableau after computing the optimum, and these 1649 // functions rollback the insertion of the objective function into the 1650 // tableau before returning. We instead add a row for the objective function 1651 // ourselves, call into computeOptimum, compute the duals from the tableau 1652 // state, and finally rollback the addition of the row before returning. 1653 SimplexRollbackScopeExit scopeExit(simplex); 1654 unsigned conIndex = simplex.addRow(getCoeffsForDirection(dir)); 1655 unsigned row = simplex.con[conIndex].pos; 1656 MaybeOptimum<Fraction> maybeWidth = 1657 simplex.computeRowOptimum(Simplex::Direction::Up, row); 1658 assert(maybeWidth.isBounded() && "Width should be bounded!"); 1659 dualDenom = simplex.tableau(row, 0); 1660 dual.clear(); 1661 1662 // The increment is i += 2 because equalities are added as two inequalities, 1663 // one positive and one negative. Each iteration processes one equality. 1664 for (unsigned i = simplexConstraintOffset; i < conIndex; i += 2) { 1665 // The dual variable for an inequality in column orientation is the 1666 // negative of its coefficient at the objective row. If the inequality is 1667 // in row orientation, the corresponding dual variable is zero. 1668 // 1669 // We want the dual for the original equality, which corresponds to two 1670 // inequalities: a positive inequality, which has the same coefficients as 1671 // the equality, and a negative equality, which has negated coefficients. 1672 // 1673 // Note that at most one of these inequalities can be in column 1674 // orientation because the column unknowns should form a basis and hence 1675 // must be linearly independent. If the positive inequality is in column 1676 // position, its dual is the dual corresponding to the equality. If the 1677 // negative inequality is in column position, the negation of its dual is 1678 // the dual corresponding to the equality. If neither is in column 1679 // position, then that means that this equality is redundant, and its dual 1680 // is zero. 1681 // 1682 // Note that it is NOT valid to perform pivots during the computation of 1683 // the duals. This entire dual computation must be performed on the same 1684 // tableau configuration. 1685 assert(!(simplex.con[i].orientation == Orientation::Column && 1686 simplex.con[i + 1].orientation == Orientation::Column) && 1687 "Both inequalities for the equality cannot be in column " 1688 "orientation!"); 1689 if (simplex.con[i].orientation == Orientation::Column) 1690 dual.push_back(-simplex.tableau(row, simplex.con[i].pos)); 1691 else if (simplex.con[i + 1].orientation == Orientation::Column) 1692 dual.push_back(simplex.tableau(row, simplex.con[i + 1].pos)); 1693 else 1694 dual.push_back(0); 1695 } 1696 return *maybeWidth; 1697 } 1698 1699 /// Remove the last equality that was added through addEqualityForDirection. 1700 /// 1701 /// We do this by rolling back to the snapshot at the top of the stack, which 1702 /// should be a snapshot taken just before the last equality was added. 1703 void removeLastEquality() { 1704 assert(!snapshotStack.empty() && "Snapshot stack is empty!"); 1705 simplex.rollback(snapshotStack.back()); 1706 snapshotStack.pop_back(); 1707 } 1708 1709 private: 1710 /// Returns coefficients of the expression 'dot_product(dir, x - y)', 1711 /// i.e., dir_1 * x_1 + dir_2 * x_2 + ... + dir_n * x_n 1712 /// - dir_1 * y_1 - dir_2 * y_2 - ... - dir_n * y_n, 1713 /// where n is the dimension of the original polytope. 1714 SmallVector<int64_t, 8> getCoeffsForDirection(ArrayRef<int64_t> dir) { 1715 assert(2 * dir.size() == simplex.getNumVariables() && 1716 "Direction vector has wrong dimensionality"); 1717 SmallVector<int64_t, 8> coeffs(dir.begin(), dir.end()); 1718 coeffs.reserve(2 * dir.size()); 1719 for (int64_t coeff : dir) 1720 coeffs.push_back(-coeff); 1721 coeffs.push_back(0); // constant term 1722 return coeffs; 1723 } 1724 1725 Simplex simplex; 1726 /// The first index of the equality constraints, the index immediately after 1727 /// the last constraint in the initial product simplex. 1728 unsigned simplexConstraintOffset; 1729 /// A stack of snapshots, used for rolling back. 1730 SmallVector<unsigned, 8> snapshotStack; 1731 }; 1732 1733 /// Reduce the basis to try and find a direction in which the polytope is 1734 /// "thin". This only works for bounded polytopes. 1735 /// 1736 /// This is an implementation of the algorithm described in the paper 1737 /// "An Implementation of Generalized Basis Reduction for Integer Programming" 1738 /// by W. Cook, T. Rutherford, H. E. Scarf, D. Shallcross. 1739 /// 1740 /// Let b_{level}, b_{level + 1}, ... b_n be the current basis. 1741 /// Let width_i(v) = max <v, x - y> where x and y are points in the original 1742 /// polytope such that <b_j, x - y> = 0 is satisfied for all level <= j < i. 1743 /// 1744 /// In every iteration, we first replace b_{i+1} with b_{i+1} + u*b_i, where u 1745 /// is the integer such that width_i(b_{i+1} + u*b_i) is minimized. Let dual_i 1746 /// be the dual variable associated with the constraint <b_i, x - y> = 0 when 1747 /// computing width_{i+1}(b_{i+1}). It can be shown that dual_i is the 1748 /// minimizing value of u, if it were allowed to be fractional. Due to 1749 /// convexity, the minimizing integer value is either floor(dual_i) or 1750 /// ceil(dual_i), so we just need to check which of these gives a lower 1751 /// width_{i+1} value. If dual_i turned out to be an integer, then u = dual_i. 1752 /// 1753 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and (the new) 1754 /// b_{i + 1} and decrement i (unless i = level, in which case we stay at the 1755 /// same i). Otherwise, we increment i. 1756 /// 1757 /// We keep f values and duals cached and invalidate them when necessary. 1758 /// Whenever possible, we use them instead of recomputing them. We implement the 1759 /// algorithm as follows. 1760 /// 1761 /// In an iteration at i we need to compute: 1762 /// a) width_i(b_{i + 1}) 1763 /// b) width_i(b_i) 1764 /// c) the integer u that minimizes width_i(b_{i + 1} + u*b_i) 1765 /// 1766 /// If width_i(b_i) is not already cached, we compute it. 1767 /// 1768 /// If the duals are not already cached, we compute width_{i+1}(b_{i+1}) and 1769 /// store the duals from this computation. 1770 /// 1771 /// We call updateBasisWithUAndGetFCandidate, which finds the minimizing value 1772 /// of u as explained before, caches the duals from this computation, sets 1773 /// b_{i+1} to b_{i+1} + u*b_i, and returns the new value of width_i(b_{i+1}). 1774 /// 1775 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and b_{i+1} and 1776 /// decrement i, resulting in the basis 1777 /// ... b_{i - 1}, b_{i + 1} + u*b_i, b_i, b_{i+2}, ... 1778 /// with corresponding f values 1779 /// ... width_{i-1}(b_{i-1}), width_i(b_{i+1} + u*b_i), width_{i+1}(b_i), ... 1780 /// The values up to i - 1 remain unchanged. We have just gotten the middle 1781 /// value from updateBasisWithUAndGetFCandidate, so we can update that in the 1782 /// cache. The value at width_{i+1}(b_i) is unknown, so we evict this value from 1783 /// the cache. The iteration after decrementing needs exactly the duals from the 1784 /// computation of width_i(b_{i + 1} + u*b_i), so we keep these in the cache. 1785 /// 1786 /// When incrementing i, no cached f values get invalidated. However, the cached 1787 /// duals do get invalidated as the duals for the higher levels are different. 1788 void Simplex::reduceBasis(Matrix &basis, unsigned level) { 1789 const Fraction epsilon(3, 4); 1790 1791 if (level == basis.getNumRows() - 1) 1792 return; 1793 1794 GBRSimplex gbrSimplex(*this); 1795 SmallVector<Fraction, 8> width; 1796 SmallVector<int64_t, 8> dual; 1797 int64_t dualDenom; 1798 1799 // Finds the value of u that minimizes width_i(b_{i+1} + u*b_i), caches the 1800 // duals from this computation, sets b_{i+1} to b_{i+1} + u*b_i, and returns 1801 // the new value of width_i(b_{i+1}). 1802 // 1803 // If dual_i is not an integer, the minimizing value must be either 1804 // floor(dual_i) or ceil(dual_i). We compute the expression for both and 1805 // choose the minimizing value. 1806 // 1807 // If dual_i is an integer, we don't need to perform these computations. We 1808 // know that in this case, 1809 // a) u = dual_i. 1810 // b) one can show that dual_j for j < i are the same duals we would have 1811 // gotten from computing width_i(b_{i + 1} + u*b_i), so the correct duals 1812 // are the ones already in the cache. 1813 // c) width_i(b_{i+1} + u*b_i) = min_{alpha} width_i(b_{i+1} + alpha * b_i), 1814 // which 1815 // one can show is equal to width_{i+1}(b_{i+1}). The latter value must 1816 // be in the cache, so we get it from there and return it. 1817 auto updateBasisWithUAndGetFCandidate = [&](unsigned i) -> Fraction { 1818 assert(i < level + dual.size() && "dual_i is not known!"); 1819 1820 int64_t u = floorDiv(dual[i - level], dualDenom); 1821 basis.addToRow(i, i + 1, u); 1822 if (dual[i - level] % dualDenom != 0) { 1823 SmallVector<int64_t, 8> candidateDual[2]; 1824 int64_t candidateDualDenom[2]; 1825 Fraction widthI[2]; 1826 1827 // Initially u is floor(dual) and basis reflects this. 1828 widthI[0] = gbrSimplex.computeWidthAndDuals( 1829 basis.getRow(i + 1), candidateDual[0], candidateDualDenom[0]); 1830 1831 // Now try ceil(dual), i.e. floor(dual) + 1. 1832 ++u; 1833 basis.addToRow(i, i + 1, 1); 1834 widthI[1] = gbrSimplex.computeWidthAndDuals( 1835 basis.getRow(i + 1), candidateDual[1], candidateDualDenom[1]); 1836 1837 unsigned j = widthI[0] < widthI[1] ? 0 : 1; 1838 if (j == 0) 1839 // Subtract 1 to go from u = ceil(dual) back to floor(dual). 1840 basis.addToRow(i, i + 1, -1); 1841 1842 // width_i(b{i+1} + u*b_i) should be minimized at our value of u. 1843 // We assert that this holds by checking that the values of width_i at 1844 // u - 1 and u + 1 are greater than or equal to the value at u. If the 1845 // width is lesser at either of the adjacent values, then our computed 1846 // value of u is clearly not the minimizer. Otherwise by convexity the 1847 // computed value of u is really the minimizer. 1848 1849 // Check the value at u - 1. 1850 assert(gbrSimplex.computeWidth(scaleAndAddForAssert( 1851 basis.getRow(i + 1), -1, basis.getRow(i))) >= widthI[j] && 1852 "Computed u value does not minimize the width!"); 1853 // Check the value at u + 1. 1854 assert(gbrSimplex.computeWidth(scaleAndAddForAssert( 1855 basis.getRow(i + 1), +1, basis.getRow(i))) >= widthI[j] && 1856 "Computed u value does not minimize the width!"); 1857 1858 dual = std::move(candidateDual[j]); 1859 dualDenom = candidateDualDenom[j]; 1860 return widthI[j]; 1861 } 1862 1863 assert(i + 1 - level < width.size() && "width_{i+1} wasn't saved"); 1864 // f_i(b_{i+1} + dual*b_i) == width_{i+1}(b_{i+1}) when `dual` minimizes the 1865 // LHS. (note: the basis has already been updated, so b_{i+1} + dual*b_i in 1866 // the above expression is equal to basis.getRow(i+1) below.) 1867 assert(gbrSimplex.computeWidth(basis.getRow(i + 1)) == 1868 width[i + 1 - level]); 1869 return width[i + 1 - level]; 1870 }; 1871 1872 // In the ith iteration of the loop, gbrSimplex has constraints for directions 1873 // from `level` to i - 1. 1874 unsigned i = level; 1875 while (i < basis.getNumRows() - 1) { 1876 if (i >= level + width.size()) { 1877 // We don't even know the value of f_i(b_i), so let's find that first. 1878 // We have to do this first since later we assume that width already 1879 // contains values up to and including i. 1880 1881 assert((i == 0 || i - 1 < level + width.size()) && 1882 "We are at level i but we don't know the value of width_{i-1}"); 1883 1884 // We don't actually use these duals at all, but it doesn't matter 1885 // because this case should only occur when i is level, and there are no 1886 // duals in that case anyway. 1887 assert(i == level && "This case should only occur when i == level"); 1888 width.push_back( 1889 gbrSimplex.computeWidthAndDuals(basis.getRow(i), dual, dualDenom)); 1890 } 1891 1892 if (i >= level + dual.size()) { 1893 assert(i + 1 >= level + width.size() && 1894 "We don't know dual_i but we know width_{i+1}"); 1895 // We don't know dual for our level, so let's find it. 1896 gbrSimplex.addEqualityForDirection(basis.getRow(i)); 1897 width.push_back(gbrSimplex.computeWidthAndDuals(basis.getRow(i + 1), dual, 1898 dualDenom)); 1899 gbrSimplex.removeLastEquality(); 1900 } 1901 1902 // This variable stores width_i(b_{i+1} + u*b_i). 1903 Fraction widthICandidate = updateBasisWithUAndGetFCandidate(i); 1904 if (widthICandidate < epsilon * width[i - level]) { 1905 basis.swapRows(i, i + 1); 1906 width[i - level] = widthICandidate; 1907 // The values of width_{i+1}(b_{i+1}) and higher may change after the 1908 // swap, so we remove the cached values here. 1909 width.resize(i - level + 1); 1910 if (i == level) { 1911 dual.clear(); 1912 continue; 1913 } 1914 1915 gbrSimplex.removeLastEquality(); 1916 i--; 1917 continue; 1918 } 1919 1920 // Invalidate duals since the higher level needs to recompute its own duals. 1921 dual.clear(); 1922 gbrSimplex.addEqualityForDirection(basis.getRow(i)); 1923 i++; 1924 } 1925 } 1926 1927 /// Search for an integer sample point using a branch and bound algorithm. 1928 /// 1929 /// Each row in the basis matrix is a vector, and the set of basis vectors 1930 /// should span the space. Initially this is the identity matrix, 1931 /// i.e., the basis vectors are just the variables. 1932 /// 1933 /// In every level, a value is assigned to the level-th basis vector, as 1934 /// follows. Compute the minimum and maximum rational values of this direction. 1935 /// If only one integer point lies in this range, constrain the variable to 1936 /// have this value and recurse to the next variable. 1937 /// 1938 /// If the range has multiple values, perform generalized basis reduction via 1939 /// reduceBasis and then compute the bounds again. Now we try constraining 1940 /// this direction in the first value in this range and "recurse" to the next 1941 /// level. If we fail to find a sample, we try assigning the direction the next 1942 /// value in this range, and so on. 1943 /// 1944 /// If no integer sample is found from any of the assignments, or if the range 1945 /// contains no integer value, then of course the polytope is empty for the 1946 /// current assignment of the values in previous levels, so we return to 1947 /// the previous level. 1948 /// 1949 /// If we reach the last level where all the variables have been assigned values 1950 /// already, then we simply return the current sample point if it is integral, 1951 /// and go back to the previous level otherwise. 1952 /// 1953 /// To avoid potentially arbitrarily large recursion depths leading to stack 1954 /// overflows, this algorithm is implemented iteratively. 1955 Optional<SmallVector<int64_t, 8>> Simplex::findIntegerSample() { 1956 if (empty) 1957 return {}; 1958 1959 unsigned nDims = var.size(); 1960 Matrix basis = Matrix::identity(nDims); 1961 1962 unsigned level = 0; 1963 // The snapshot just before constraining a direction to a value at each level. 1964 SmallVector<unsigned, 8> snapshotStack; 1965 // The maximum value in the range of the direction for each level. 1966 SmallVector<int64_t, 8> upperBoundStack; 1967 // The next value to try constraining the basis vector to at each level. 1968 SmallVector<int64_t, 8> nextValueStack; 1969 1970 snapshotStack.reserve(basis.getNumRows()); 1971 upperBoundStack.reserve(basis.getNumRows()); 1972 nextValueStack.reserve(basis.getNumRows()); 1973 while (level != -1u) { 1974 if (level == basis.getNumRows()) { 1975 // We've assigned values to all variables. Return if we have a sample, 1976 // or go back up to the previous level otherwise. 1977 if (auto maybeSample = getSamplePointIfIntegral()) 1978 return maybeSample; 1979 level--; 1980 continue; 1981 } 1982 1983 if (level >= upperBoundStack.size()) { 1984 // We haven't populated the stack values for this level yet, so we have 1985 // just come down a level ("recursed"). Find the lower and upper bounds. 1986 // If there is more than one integer point in the range, perform 1987 // generalized basis reduction. 1988 SmallVector<int64_t, 8> basisCoeffs = 1989 llvm::to_vector<8>(basis.getRow(level)); 1990 basisCoeffs.push_back(0); 1991 1992 MaybeOptimum<int64_t> minRoundedUp, maxRoundedDown; 1993 std::tie(minRoundedUp, maxRoundedDown) = 1994 computeIntegerBounds(basisCoeffs); 1995 1996 // We don't have any integer values in the range. 1997 // Pop the stack and return up a level. 1998 if (minRoundedUp.isEmpty() || maxRoundedDown.isEmpty()) { 1999 assert((minRoundedUp.isEmpty() && maxRoundedDown.isEmpty()) && 2000 "If one bound is empty, both should be."); 2001 snapshotStack.pop_back(); 2002 nextValueStack.pop_back(); 2003 upperBoundStack.pop_back(); 2004 level--; 2005 continue; 2006 } 2007 2008 // We already checked the empty case above. 2009 assert((minRoundedUp.isBounded() && maxRoundedDown.isBounded()) && 2010 "Polyhedron should be bounded!"); 2011 2012 // Heuristic: if the sample point is integral at this point, just return 2013 // it. 2014 if (auto maybeSample = getSamplePointIfIntegral()) 2015 return *maybeSample; 2016 2017 if (*minRoundedUp < *maxRoundedDown) { 2018 reduceBasis(basis, level); 2019 basisCoeffs = llvm::to_vector<8>(basis.getRow(level)); 2020 basisCoeffs.push_back(0); 2021 std::tie(minRoundedUp, maxRoundedDown) = 2022 computeIntegerBounds(basisCoeffs); 2023 } 2024 2025 snapshotStack.push_back(getSnapshot()); 2026 // The smallest value in the range is the next value to try. 2027 // The values in the optionals are guaranteed to exist since we know the 2028 // polytope is bounded. 2029 nextValueStack.push_back(*minRoundedUp); 2030 upperBoundStack.push_back(*maxRoundedDown); 2031 } 2032 2033 assert((snapshotStack.size() - 1 == level && 2034 nextValueStack.size() - 1 == level && 2035 upperBoundStack.size() - 1 == level) && 2036 "Mismatched variable stack sizes!"); 2037 2038 // Whether we "recursed" or "returned" from a lower level, we rollback 2039 // to the snapshot of the starting state at this level. (in the "recursed" 2040 // case this has no effect) 2041 rollback(snapshotStack.back()); 2042 int64_t nextValue = nextValueStack.back(); 2043 nextValueStack.back()++; 2044 if (nextValue > upperBoundStack.back()) { 2045 // We have exhausted the range and found no solution. Pop the stack and 2046 // return up a level. 2047 snapshotStack.pop_back(); 2048 nextValueStack.pop_back(); 2049 upperBoundStack.pop_back(); 2050 level--; 2051 continue; 2052 } 2053 2054 // Try the next value in the range and "recurse" into the next level. 2055 SmallVector<int64_t, 8> basisCoeffs(basis.getRow(level).begin(), 2056 basis.getRow(level).end()); 2057 basisCoeffs.push_back(-nextValue); 2058 addEquality(basisCoeffs); 2059 level++; 2060 } 2061 2062 return {}; 2063 } 2064 2065 /// Compute the minimum and maximum integer values the expression can take. We 2066 /// compute each separately. 2067 std::pair<MaybeOptimum<int64_t>, MaybeOptimum<int64_t>> 2068 Simplex::computeIntegerBounds(ArrayRef<int64_t> coeffs) { 2069 MaybeOptimum<int64_t> minRoundedUp( 2070 computeOptimum(Simplex::Direction::Down, coeffs).map(ceil)); 2071 MaybeOptimum<int64_t> maxRoundedDown( 2072 computeOptimum(Simplex::Direction::Up, coeffs).map(floor)); 2073 return {minRoundedUp, maxRoundedDown}; 2074 } 2075 2076 void SimplexBase::print(raw_ostream &os) const { 2077 os << "rows = " << nRow << ", columns = " << nCol << "\n"; 2078 if (empty) 2079 os << "Simplex marked empty!\n"; 2080 os << "var: "; 2081 for (unsigned i = 0; i < var.size(); ++i) { 2082 if (i > 0) 2083 os << ", "; 2084 var[i].print(os); 2085 } 2086 os << "\ncon: "; 2087 for (unsigned i = 0; i < con.size(); ++i) { 2088 if (i > 0) 2089 os << ", "; 2090 con[i].print(os); 2091 } 2092 os << '\n'; 2093 for (unsigned row = 0; row < nRow; ++row) { 2094 if (row > 0) 2095 os << ", "; 2096 os << "r" << row << ": " << rowUnknown[row]; 2097 } 2098 os << '\n'; 2099 os << "c0: denom, c1: const"; 2100 for (unsigned col = 2; col < nCol; ++col) 2101 os << ", c" << col << ": " << colUnknown[col]; 2102 os << '\n'; 2103 for (unsigned row = 0; row < nRow; ++row) { 2104 for (unsigned col = 0; col < nCol; ++col) 2105 os << tableau(row, col) << '\t'; 2106 os << '\n'; 2107 } 2108 os << '\n'; 2109 } 2110 2111 void SimplexBase::dump() const { print(llvm::errs()); } 2112 2113 bool Simplex::isRationalSubsetOf(const IntegerRelation &rel) { 2114 if (isEmpty()) 2115 return true; 2116 2117 for (unsigned i = 0, e = rel.getNumInequalities(); i < e; ++i) 2118 if (findIneqType(rel.getInequality(i)) != IneqType::Redundant) 2119 return false; 2120 2121 for (unsigned i = 0, e = rel.getNumEqualities(); i < e; ++i) 2122 if (!isRedundantEquality(rel.getEquality(i))) 2123 return false; 2124 2125 return true; 2126 } 2127 2128 /// Returns the type of the inequality with coefficients `coeffs`. 2129 /// Possible types are: 2130 /// Redundant The inequality is satisfied by all points in the polytope 2131 /// Cut The inequality is satisfied by some points, but not by others 2132 /// Separate The inequality is not satisfied by any point 2133 /// 2134 /// Internally, this computes the minimum and the maximum the inequality with 2135 /// coefficients `coeffs` can take. If the minimum is >= 0, the inequality holds 2136 /// for all points in the polytope, so it is redundant. If the minimum is <= 0 2137 /// and the maximum is >= 0, the points in between the minimum and the 2138 /// inequality do not satisfy it, the points in between the inequality and the 2139 /// maximum satisfy it. Hence, it is a cut inequality. If both are < 0, no 2140 /// points of the polytope satisfy the inequality, which means it is a separate 2141 /// inequality. 2142 Simplex::IneqType Simplex::findIneqType(ArrayRef<int64_t> coeffs) { 2143 MaybeOptimum<Fraction> minimum = computeOptimum(Direction::Down, coeffs); 2144 if (minimum.isBounded() && *minimum >= Fraction(0, 1)) { 2145 return IneqType::Redundant; 2146 } 2147 MaybeOptimum<Fraction> maximum = computeOptimum(Direction::Up, coeffs); 2148 if ((!minimum.isBounded() || *minimum <= Fraction(0, 1)) && 2149 (!maximum.isBounded() || *maximum >= Fraction(0, 1))) { 2150 return IneqType::Cut; 2151 } 2152 return IneqType::Separate; 2153 } 2154 2155 /// Checks whether the type of the inequality with coefficients `coeffs` 2156 /// is Redundant. 2157 bool Simplex::isRedundantInequality(ArrayRef<int64_t> coeffs) { 2158 assert(!empty && 2159 "It is not meaningful to ask about redundancy in an empty set!"); 2160 return findIneqType(coeffs) == IneqType::Redundant; 2161 } 2162 2163 /// Check whether the equality given by `coeffs == 0` is redundant given 2164 /// the existing constraints. This is redundant when `coeffs` is already 2165 /// always zero under the existing constraints. `coeffs` is always zero 2166 /// when the minimum and maximum value that `coeffs` can take are both zero. 2167 bool Simplex::isRedundantEquality(ArrayRef<int64_t> coeffs) { 2168 assert(!empty && 2169 "It is not meaningful to ask about redundancy in an empty set!"); 2170 MaybeOptimum<Fraction> minimum = computeOptimum(Direction::Down, coeffs); 2171 MaybeOptimum<Fraction> maximum = computeOptimum(Direction::Up, coeffs); 2172 assert((!minimum.isEmpty() && !maximum.isEmpty()) && 2173 "Optima should be non-empty for a non-empty set"); 2174 return minimum.isBounded() && maximum.isBounded() && 2175 *maximum == Fraction(0, 1) && *minimum == Fraction(0, 1); 2176 } 2177