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