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