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 namespace mlir {
15 using Direction = Simplex::Direction;
16 
17 const int nullIndex = std::numeric_limits<int>::max();
18 
19 /// Construct a Simplex object with `nVar` variables.
20 Simplex::Simplex(unsigned nVar)
21     : nRow(0), nCol(2), nRedundant(0), tableau(0, 2 + nVar), empty(false) {
22   colUnknown.push_back(nullIndex);
23   colUnknown.push_back(nullIndex);
24   for (unsigned i = 0; i < nVar; ++i) {
25     var.emplace_back(Orientation::Column, /*restricted=*/false, /*pos=*/nCol);
26     colUnknown.push_back(i);
27     nCol++;
28   }
29 }
30 
31 Simplex::Simplex(const FlatAffineConstraints &constraints)
32     : Simplex(constraints.getNumIds()) {
33   for (unsigned i = 0, numIneqs = constraints.getNumInequalities();
34        i < numIneqs; ++i)
35     addInequality(constraints.getInequality(i));
36   for (unsigned i = 0, numEqs = constraints.getNumEqualities(); i < numEqs; ++i)
37     addEquality(constraints.getEquality(i));
38 }
39 
40 const Simplex::Unknown &Simplex::unknownFromIndex(int index) const {
41   assert(index != nullIndex && "nullIndex passed to unknownFromIndex");
42   return index >= 0 ? var[index] : con[~index];
43 }
44 
45 const Simplex::Unknown &Simplex::unknownFromColumn(unsigned col) const {
46   assert(col < nCol && "Invalid column");
47   return unknownFromIndex(colUnknown[col]);
48 }
49 
50 const Simplex::Unknown &Simplex::unknownFromRow(unsigned row) const {
51   assert(row < nRow && "Invalid row");
52   return unknownFromIndex(rowUnknown[row]);
53 }
54 
55 Simplex::Unknown &Simplex::unknownFromIndex(int index) {
56   assert(index != nullIndex && "nullIndex passed to unknownFromIndex");
57   return index >= 0 ? var[index] : con[~index];
58 }
59 
60 Simplex::Unknown &Simplex::unknownFromColumn(unsigned col) {
61   assert(col < nCol && "Invalid column");
62   return unknownFromIndex(colUnknown[col]);
63 }
64 
65 Simplex::Unknown &Simplex::unknownFromRow(unsigned row) {
66   assert(row < nRow && "Invalid row");
67   return unknownFromIndex(rowUnknown[row]);
68 }
69 
70 /// Add a new row to the tableau corresponding to the given constant term and
71 /// list of coefficients. The coefficients are specified as a vector of
72 /// (variable index, coefficient) pairs.
73 unsigned Simplex::addRow(ArrayRef<int64_t> coeffs) {
74   assert(coeffs.size() == 1 + var.size() &&
75          "Incorrect number of coefficients!");
76 
77   ++nRow;
78   // If the tableau is not big enough to accomodate the extra row, we extend it.
79   if (nRow >= tableau.getNumRows())
80     tableau.resizeVertically(nRow);
81   rowUnknown.push_back(~con.size());
82   con.emplace_back(Orientation::Row, false, nRow - 1);
83 
84   tableau(nRow - 1, 0) = 1;
85   tableau(nRow - 1, 1) = coeffs.back();
86   for (unsigned col = 2; col < nCol; ++col)
87     tableau(nRow - 1, col) = 0;
88 
89   // Process each given variable coefficient.
90   for (unsigned i = 0; i < var.size(); ++i) {
91     unsigned pos = var[i].pos;
92     if (coeffs[i] == 0)
93       continue;
94 
95     if (var[i].orientation == Orientation::Column) {
96       // If a variable is in column position at column col, then we just add the
97       // coefficient for that variable (scaled by the common row denominator) to
98       // the corresponding entry in the new row.
99       tableau(nRow - 1, pos) += coeffs[i] * tableau(nRow - 1, 0);
100       continue;
101     }
102 
103     // If the variable is in row position, we need to add that row to the new
104     // row, scaled by the coefficient for the variable, accounting for the two
105     // rows potentially having different denominators. The new denominator is
106     // the lcm of the two.
107     int64_t lcm = mlir::lcm(tableau(nRow - 1, 0), tableau(pos, 0));
108     int64_t nRowCoeff = lcm / tableau(nRow - 1, 0);
109     int64_t idxRowCoeff = coeffs[i] * (lcm / tableau(pos, 0));
110     tableau(nRow - 1, 0) = lcm;
111     for (unsigned col = 1; col < nCol; ++col)
112       tableau(nRow - 1, col) =
113           nRowCoeff * tableau(nRow - 1, col) + idxRowCoeff * tableau(pos, col);
114   }
115 
116   normalizeRow(nRow - 1);
117   // Push to undo log along with the index of the new constraint.
118   undoLog.push_back(UndoLogEntry::RemoveLastConstraint);
119   return con.size() - 1;
120 }
121 
122 /// Normalize the row by removing factors that are common between the
123 /// denominator and all the numerator coefficients.
124 void Simplex::normalizeRow(unsigned row) {
125   int64_t gcd = 0;
126   for (unsigned col = 0; col < nCol; ++col) {
127     if (gcd == 1)
128       break;
129     gcd = llvm::greatestCommonDivisor(gcd, std::abs(tableau(row, col)));
130   }
131   for (unsigned col = 0; col < nCol; ++col)
132     tableau(row, col) /= gcd;
133 }
134 
135 namespace {
136 bool signMatchesDirection(int64_t elem, Direction direction) {
137   assert(elem != 0 && "elem should not be 0");
138   return direction == Direction::Up ? elem > 0 : elem < 0;
139 }
140 
141 Direction flippedDirection(Direction direction) {
142   return direction == Direction::Up ? Direction::Down : Simplex::Direction::Up;
143 }
144 } // namespace
145 
146 /// Find a pivot to change the sample value of the row in the specified
147 /// direction. The returned pivot row will involve `row` if and only if the
148 /// unknown is unbounded in the specified direction.
149 ///
150 /// To increase (resp. decrease) the value of a row, we need to find a live
151 /// column with a non-zero coefficient. If the coefficient is positive, we need
152 /// to increase (decrease) the value of the column, and if the coefficient is
153 /// negative, we need to decrease (increase) the value of the column. Also,
154 /// we cannot decrease the sample value of restricted columns.
155 ///
156 /// If multiple columns are valid, we break ties by considering a lexicographic
157 /// ordering where we prefer unknowns with lower index.
158 Optional<Simplex::Pivot> Simplex::findPivot(int row,
159                                             Direction direction) const {
160   Optional<unsigned> col;
161   for (unsigned j = 2; j < nCol; ++j) {
162     int64_t elem = tableau(row, j);
163     if (elem == 0)
164       continue;
165 
166     if (unknownFromColumn(j).restricted &&
167         !signMatchesDirection(elem, direction))
168       continue;
169     if (!col || colUnknown[j] < colUnknown[*col])
170       col = j;
171   }
172 
173   if (!col)
174     return {};
175 
176   Direction newDirection =
177       tableau(row, *col) < 0 ? flippedDirection(direction) : direction;
178   Optional<unsigned> maybePivotRow = findPivotRow(row, newDirection, *col);
179   return Pivot{maybePivotRow.getValueOr(row), *col};
180 }
181 
182 /// Swap the associated unknowns for the row and the column.
183 ///
184 /// First we swap the index associated with the row and column. Then we update
185 /// the unknowns to reflect their new position and orientation.
186 void Simplex::swapRowWithCol(unsigned row, unsigned col) {
187   std::swap(rowUnknown[row], colUnknown[col]);
188   Unknown &uCol = unknownFromColumn(col);
189   Unknown &uRow = unknownFromRow(row);
190   uCol.orientation = Orientation::Column;
191   uRow.orientation = Orientation::Row;
192   uCol.pos = col;
193   uRow.pos = row;
194 }
195 
196 void Simplex::pivot(Pivot pair) { pivot(pair.row, pair.column); }
197 
198 /// Pivot pivotRow and pivotCol.
199 ///
200 /// Let R be the pivot row unknown and let C be the pivot col unknown.
201 /// Since initially R = a*C + sum b_i * X_i
202 /// (where the sum is over the other column's unknowns, x_i)
203 /// C = (R - (sum b_i * X_i))/a
204 ///
205 /// Let u be some other row unknown.
206 /// u = c*C + sum d_i * X_i
207 /// So u = c*(R - sum b_i * X_i)/a + sum d_i * X_i
208 ///
209 /// This results in the following transform:
210 ///            pivot col    other col                   pivot col    other col
211 /// pivot row     a             b       ->   pivot row     1/a         -b/a
212 /// other row     c             d            other row     c/a        d - bc/a
213 ///
214 /// Taking into account the common denominators p and q:
215 ///
216 ///            pivot col    other col                    pivot col   other col
217 /// pivot row     a/p          b/p     ->   pivot row      p/a         -b/a
218 /// other row     c/q          d/q          other row     cp/aq    (da - bc)/aq
219 ///
220 /// The pivot row transform is accomplished be swapping a with the pivot row's
221 /// common denominator and negating the pivot row except for the pivot column
222 /// element.
223 void Simplex::pivot(unsigned pivotRow, unsigned pivotCol) {
224   assert(pivotCol >= 2 && "Refusing to pivot invalid column");
225 
226   swapRowWithCol(pivotRow, pivotCol);
227   std::swap(tableau(pivotRow, 0), tableau(pivotRow, pivotCol));
228   // We need to negate the whole pivot row except for the pivot column.
229   if (tableau(pivotRow, 0) < 0) {
230     // If the denominator is negative, we negate the row by simply negating the
231     // denominator.
232     tableau(pivotRow, 0) = -tableau(pivotRow, 0);
233     tableau(pivotRow, pivotCol) = -tableau(pivotRow, pivotCol);
234   } else {
235     for (unsigned col = 1; col < nCol; ++col) {
236       if (col == pivotCol)
237         continue;
238       tableau(pivotRow, col) = -tableau(pivotRow, col);
239     }
240   }
241   normalizeRow(pivotRow);
242 
243   for (unsigned row = 0; row < nRow; ++row) {
244     if (row == pivotRow)
245       continue;
246     if (tableau(row, pivotCol) == 0) // Nothing to do.
247       continue;
248     tableau(row, 0) *= tableau(pivotRow, 0);
249     for (unsigned j = 1; j < nCol; ++j) {
250       if (j == pivotCol)
251         continue;
252       // Add rather than subtract because the pivot row has been negated.
253       tableau(row, j) = tableau(row, j) * tableau(pivotRow, 0) +
254                         tableau(row, pivotCol) * tableau(pivotRow, j);
255     }
256     tableau(row, pivotCol) *= tableau(pivotRow, pivotCol);
257     normalizeRow(row);
258   }
259 }
260 
261 /// Perform pivots until the unknown has a non-negative sample value or until
262 /// no more upward pivots can be performed. Return success if we were able to
263 /// bring the row to a non-negative sample value, and failure otherwise.
264 LogicalResult Simplex::restoreRow(Unknown &u) {
265   assert(u.orientation == Orientation::Row &&
266          "unknown should be in row position");
267 
268   while (tableau(u.pos, 1) < 0) {
269     Optional<Pivot> maybePivot = findPivot(u.pos, Direction::Up);
270     if (!maybePivot)
271       break;
272 
273     pivot(*maybePivot);
274     if (u.orientation == Orientation::Column)
275       return success(); // the unknown is unbounded above.
276   }
277   return success(tableau(u.pos, 1) >= 0);
278 }
279 
280 /// Find a row that can be used to pivot the column in the specified direction.
281 /// This returns an empty optional if and only if the column is unbounded in the
282 /// specified direction (ignoring skipRow, if skipRow is set).
283 ///
284 /// If skipRow is set, this row is not considered, and (if it is restricted) its
285 /// restriction may be violated by the returned pivot. Usually, skipRow is set
286 /// because we don't want to move it to column position unless it is unbounded,
287 /// and we are either trying to increase the value of skipRow or explicitly
288 /// trying to make skipRow negative, so we are not concerned about this.
289 ///
290 /// If the direction is up (resp. down) and a restricted row has a negative
291 /// (positive) coefficient for the column, then this row imposes a bound on how
292 /// much the sample value of the column can change. Such a row with constant
293 /// term c and coefficient f for the column imposes a bound of c/|f| on the
294 /// change in sample value (in the specified direction). (note that c is
295 /// non-negative here since the row is restricted and the tableau is consistent)
296 ///
297 /// We iterate through the rows and pick the row which imposes the most
298 /// stringent bound, since pivoting with a row changes the row's sample value to
299 /// 0 and hence saturates the bound it imposes. We break ties between rows that
300 /// impose the same bound by considering a lexicographic ordering where we
301 /// prefer unknowns with lower index value.
302 Optional<unsigned> Simplex::findPivotRow(Optional<unsigned> skipRow,
303                                          Direction direction,
304                                          unsigned col) const {
305   Optional<unsigned> retRow;
306   int64_t retElem, retConst;
307   for (unsigned row = nRedundant; row < nRow; ++row) {
308     if (skipRow && row == *skipRow)
309       continue;
310     int64_t elem = tableau(row, col);
311     if (elem == 0)
312       continue;
313     if (!unknownFromRow(row).restricted)
314       continue;
315     if (signMatchesDirection(elem, direction))
316       continue;
317     int64_t constTerm = tableau(row, 1);
318 
319     if (!retRow) {
320       retRow = row;
321       retElem = elem;
322       retConst = constTerm;
323       continue;
324     }
325 
326     int64_t diff = retConst * elem - constTerm * retElem;
327     if ((diff == 0 && rowUnknown[row] < rowUnknown[*retRow]) ||
328         (diff != 0 && !signMatchesDirection(diff, direction))) {
329       retRow = row;
330       retElem = elem;
331       retConst = constTerm;
332     }
333   }
334   return retRow;
335 }
336 
337 bool Simplex::isEmpty() const { return empty; }
338 
339 void Simplex::swapRows(unsigned i, unsigned j) {
340   if (i == j)
341     return;
342   tableau.swapRows(i, j);
343   std::swap(rowUnknown[i], rowUnknown[j]);
344   unknownFromRow(i).pos = i;
345   unknownFromRow(j).pos = j;
346 }
347 
348 void Simplex::swapColumns(unsigned i, unsigned j) {
349   assert(i < nCol && j < nCol && "Invalid columns provided!");
350   if (i == j)
351     return;
352   tableau.swapColumns(i, j);
353   std::swap(colUnknown[i], colUnknown[j]);
354   unknownFromColumn(i).pos = i;
355   unknownFromColumn(j).pos = j;
356 }
357 
358 /// Mark this tableau empty and push an entry to the undo stack.
359 void Simplex::markEmpty() {
360   // If the set is already empty, then we shouldn't add another UnmarkEmpty log
361   // entry, since in that case the Simplex will be erroneously marked as
362   // non-empty when rolling back past this point.
363   if (empty)
364     return;
365   undoLog.push_back(UndoLogEntry::UnmarkEmpty);
366   empty = true;
367 }
368 
369 /// Add an inequality to the tableau. If coeffs is c_0, c_1, ... c_n, where n
370 /// is the current number of variables, then the corresponding inequality is
371 /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} >= 0.
372 ///
373 /// We add the inequality and mark it as restricted. We then try to make its
374 /// sample value non-negative. If this is not possible, the tableau has become
375 /// empty and we mark it as such.
376 void Simplex::addInequality(ArrayRef<int64_t> coeffs) {
377   unsigned conIndex = addRow(coeffs);
378   Unknown &u = con[conIndex];
379   u.restricted = true;
380   LogicalResult result = restoreRow(u);
381   if (failed(result))
382     markEmpty();
383 }
384 
385 /// Add an equality to the tableau. If coeffs is c_0, c_1, ... c_n, where n
386 /// is the current number of variables, then the corresponding equality is
387 /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} == 0.
388 ///
389 /// We simply add two opposing inequalities, which force the expression to
390 /// be zero.
391 void Simplex::addEquality(ArrayRef<int64_t> coeffs) {
392   addInequality(coeffs);
393   SmallVector<int64_t, 8> negatedCoeffs;
394   for (int64_t coeff : coeffs)
395     negatedCoeffs.emplace_back(-coeff);
396   addInequality(negatedCoeffs);
397 }
398 
399 unsigned Simplex::getNumVariables() const { return var.size(); }
400 unsigned Simplex::getNumConstraints() const { return con.size(); }
401 
402 /// Return a snapshot of the current state. This is just the current size of the
403 /// undo log.
404 unsigned Simplex::getSnapshot() const { return undoLog.size(); }
405 
406 void Simplex::undo(UndoLogEntry entry) {
407   if (entry == UndoLogEntry::RemoveLastConstraint) {
408     Unknown &constraint = con.back();
409     if (constraint.orientation == Orientation::Column) {
410       unsigned column = constraint.pos;
411       Optional<unsigned> row;
412 
413       // Try to find any pivot row for this column that preserves tableau
414       // consistency (except possibly the column itself, which is going to be
415       // deallocated anyway).
416       //
417       // If no pivot row is found in either direction, then the unknown is
418       // unbounded in both directions and we are free to
419       // perform any pivot at all. To do this, we just need to find any row with
420       // a non-zero coefficient for the column.
421       if (Optional<unsigned> maybeRow =
422               findPivotRow({}, Direction::Up, column)) {
423         row = *maybeRow;
424       } else if (Optional<unsigned> maybeRow =
425                      findPivotRow({}, Direction::Down, column)) {
426         row = *maybeRow;
427       } else {
428         // The loop doesn't find a pivot row only if the column has zero
429         // coefficients for every row. But the unknown is a constraint,
430         // so it was added initially as a row. Such a row could never have been
431         // pivoted to a column. So a pivot row will always be found.
432         for (unsigned i = nRedundant; i < nRow; ++i) {
433           if (tableau(i, column) != 0) {
434             row = i;
435             break;
436           }
437         }
438       }
439       assert(row.hasValue() && "No pivot row found!");
440       pivot(*row, column);
441     }
442 
443     // Move this unknown to the last row and remove the last row from the
444     // tableau.
445     swapRows(constraint.pos, nRow - 1);
446     // It is not strictly necessary to shrink the tableau, but for now we
447     // maintain the invariant that the tableau has exactly nRow rows.
448     tableau.resizeVertically(nRow - 1);
449     nRow--;
450     rowUnknown.pop_back();
451     con.pop_back();
452   } else if (entry == UndoLogEntry::RemoveLastVariable) {
453     // Whenever we are rolling back the addition of a variable, it is guaranteed
454     // that the variable will be in column position.
455     //
456     // We can see this as follows: any constraint that depends on this variable
457     // was added after this variable was added, so the addition of such
458     // constraints should already have been rolled back by the time we get to
459     // rolling back the addition of the variable. Therefore, no constraint
460     // currently has a component along the variable, so the variable itself must
461     // be part of the basis.
462     assert(var.back().orientation == Orientation::Column &&
463            "Variable to be removed must be in column orientation!");
464 
465     // Move this variable to the last column and remove the column from the
466     // tableau.
467     swapColumns(var.back().pos, nCol - 1);
468     tableau.resizeHorizontally(nCol - 1);
469     var.pop_back();
470     colUnknown.pop_back();
471     nCol--;
472   } else if (entry == UndoLogEntry::UnmarkEmpty) {
473     empty = false;
474   } else if (entry == UndoLogEntry::UnmarkLastRedundant) {
475     nRedundant--;
476   }
477 }
478 
479 /// Rollback to the specified snapshot.
480 ///
481 /// We undo all the log entries until the log size when the snapshot was taken
482 /// is reached.
483 void Simplex::rollback(unsigned snapshot) {
484   while (undoLog.size() > snapshot) {
485     undo(undoLog.back());
486     undoLog.pop_back();
487   }
488 }
489 
490 void Simplex::appendVariable(unsigned count) {
491   if (count == 0)
492     return;
493   var.reserve(var.size() + count);
494   colUnknown.reserve(colUnknown.size() + count);
495   for (unsigned i = 0; i < count; ++i) {
496     nCol++;
497     var.emplace_back(Orientation::Column, /*restricted=*/false,
498                      /*pos=*/nCol - 1);
499     colUnknown.push_back(var.size() - 1);
500   }
501   tableau.resizeHorizontally(nCol);
502   undoLog.insert(undoLog.end(), count, UndoLogEntry::RemoveLastVariable);
503 }
504 
505 /// Add all the constraints from the given FlatAffineConstraints.
506 void Simplex::intersectFlatAffineConstraints(const FlatAffineConstraints &fac) {
507   assert(fac.getNumIds() == getNumVariables() &&
508          "FlatAffineConstraints must have same dimensionality as simplex");
509   for (unsigned i = 0, e = fac.getNumInequalities(); i < e; ++i)
510     addInequality(fac.getInequality(i));
511   for (unsigned i = 0, e = fac.getNumEqualities(); i < e; ++i)
512     addEquality(fac.getEquality(i));
513 }
514 
515 Optional<Fraction> Simplex::computeRowOptimum(Direction direction,
516                                               unsigned row) {
517   // Keep trying to find a pivot for the row in the specified direction.
518   while (Optional<Pivot> maybePivot = findPivot(row, direction)) {
519     // If findPivot returns a pivot involving the row itself, then the optimum
520     // is unbounded, so we return None.
521     if (maybePivot->row == row)
522       return {};
523     pivot(*maybePivot);
524   }
525 
526   // The row has reached its optimal sample value, which we return.
527   // The sample value is the entry in the constant column divided by the common
528   // denominator for this row.
529   return Fraction(tableau(row, 1), tableau(row, 0));
530 }
531 
532 /// Compute the optimum of the specified expression in the specified direction,
533 /// or None if it is unbounded.
534 Optional<Fraction> Simplex::computeOptimum(Direction direction,
535                                            ArrayRef<int64_t> coeffs) {
536   assert(!empty && "Simplex should not be empty");
537 
538   unsigned snapshot = getSnapshot();
539   unsigned conIndex = addRow(coeffs);
540   unsigned row = con[conIndex].pos;
541   Optional<Fraction> optimum = computeRowOptimum(direction, row);
542   rollback(snapshot);
543   return optimum;
544 }
545 
546 Optional<Fraction> Simplex::computeOptimum(Direction direction, Unknown &u) {
547   assert(!empty && "Simplex should not be empty!");
548   if (u.orientation == Orientation::Column) {
549     unsigned column = u.pos;
550     Optional<unsigned> pivotRow = findPivotRow({}, direction, column);
551     // If no pivot is returned, the constraint is unbounded in the specified
552     // direction.
553     if (!pivotRow)
554       return {};
555     pivot(*pivotRow, column);
556   }
557 
558   unsigned row = u.pos;
559   Optional<Fraction> optimum = computeRowOptimum(direction, row);
560   if (u.restricted && direction == Direction::Down &&
561       (!optimum || *optimum < Fraction(0, 1)))
562     (void)restoreRow(u);
563   return optimum;
564 }
565 
566 bool Simplex::isBoundedAlongConstraint(unsigned constraintIndex) {
567   assert(!empty && "It is not meaningful to ask whether a direction is bounded "
568                    "in an empty set.");
569   // The constraint's perpendicular is already bounded below, since it is a
570   // constraint. If it is also bounded above, we can return true.
571   return computeOptimum(Direction::Up, con[constraintIndex]).hasValue();
572 }
573 
574 /// Redundant constraints are those that are in row orientation and lie in
575 /// rows 0 to nRedundant - 1.
576 bool Simplex::isMarkedRedundant(unsigned constraintIndex) const {
577   const Unknown &u = con[constraintIndex];
578   return u.orientation == Orientation::Row && u.pos < nRedundant;
579 }
580 
581 /// Mark the specified row redundant.
582 ///
583 /// This is done by moving the unknown to the end of the block of redundant
584 /// rows (namely, to row nRedundant) and incrementing nRedundant to
585 /// accomodate the new redundant row.
586 void Simplex::markRowRedundant(Unknown &u) {
587   assert(u.orientation == Orientation::Row &&
588          "Unknown should be in row position!");
589   assert(u.pos >= nRedundant && "Unknown is already marked redundant!");
590   swapRows(u.pos, nRedundant);
591   ++nRedundant;
592   undoLog.emplace_back(UndoLogEntry::UnmarkLastRedundant);
593 }
594 
595 /// Find a subset of constraints that is redundant and mark them redundant.
596 void Simplex::detectRedundant() {
597   // It is not meaningful to talk about redundancy for empty sets.
598   if (empty)
599     return;
600 
601   // Iterate through the constraints and check for each one if it can attain
602   // negative sample values. If it can, it's not redundant. Otherwise, it is.
603   // We mark redundant constraints redundant.
604   //
605   // Constraints that get marked redundant in one iteration are not respected
606   // when checking constraints in later iterations. This prevents, for example,
607   // two identical constraints both being marked redundant since each is
608   // redundant given the other one. In this example, only the first of the
609   // constraints that is processed will get marked redundant, as it should be.
610   for (Unknown &u : con) {
611     if (u.orientation == Orientation::Column) {
612       unsigned column = u.pos;
613       Optional<unsigned> pivotRow = findPivotRow({}, Direction::Down, column);
614       // If no downward pivot is returned, the constraint is unbounded below
615       // and hence not redundant.
616       if (!pivotRow)
617         continue;
618       pivot(*pivotRow, column);
619     }
620 
621     unsigned row = u.pos;
622     Optional<Fraction> minimum = computeRowOptimum(Direction::Down, row);
623     if (!minimum || *minimum < Fraction(0, 1)) {
624       // Constraint is unbounded below or can attain negative sample values and
625       // hence is not redundant.
626       (void)restoreRow(u);
627       continue;
628     }
629 
630     markRowRedundant(u);
631   }
632 }
633 
634 bool Simplex::isUnbounded() {
635   if (empty)
636     return false;
637 
638   SmallVector<int64_t, 8> dir(var.size() + 1);
639   for (unsigned i = 0; i < var.size(); ++i) {
640     dir[i] = 1;
641 
642     Optional<Fraction> maybeMax = computeOptimum(Direction::Up, dir);
643     if (!maybeMax)
644       return true;
645 
646     Optional<Fraction> maybeMin = computeOptimum(Direction::Down, dir);
647     if (!maybeMin)
648       return true;
649 
650     dir[i] = 0;
651   }
652   return false;
653 }
654 
655 /// Make a tableau to represent a pair of points in the original tableau.
656 ///
657 /// The product constraints and variables are stored as: first A's, then B's.
658 ///
659 /// The product tableau has row layout:
660 ///   A's redundant rows, B's redundant rows, A's other rows, B's other rows.
661 ///
662 /// It has column layout:
663 ///   denominator, constant, A's columns, B's columns.
664 Simplex Simplex::makeProduct(const Simplex &a, const Simplex &b) {
665   unsigned numVar = a.getNumVariables() + b.getNumVariables();
666   unsigned numCon = a.getNumConstraints() + b.getNumConstraints();
667   Simplex result(numVar);
668 
669   result.tableau.resizeVertically(numCon);
670   result.empty = a.empty || b.empty;
671 
672   auto concat = [](ArrayRef<Unknown> v, ArrayRef<Unknown> w) {
673     SmallVector<Unknown, 8> result;
674     result.reserve(v.size() + w.size());
675     result.insert(result.end(), v.begin(), v.end());
676     result.insert(result.end(), w.begin(), w.end());
677     return result;
678   };
679   result.con = concat(a.con, b.con);
680   result.var = concat(a.var, b.var);
681 
682   auto indexFromBIndex = [&](int index) {
683     return index >= 0 ? a.getNumVariables() + index
684                       : ~(a.getNumConstraints() + ~index);
685   };
686 
687   result.colUnknown.assign(2, nullIndex);
688   for (unsigned i = 2; i < a.nCol; ++i) {
689     result.colUnknown.push_back(a.colUnknown[i]);
690     result.unknownFromIndex(result.colUnknown.back()).pos =
691         result.colUnknown.size() - 1;
692   }
693   for (unsigned i = 2; i < b.nCol; ++i) {
694     result.colUnknown.push_back(indexFromBIndex(b.colUnknown[i]));
695     result.unknownFromIndex(result.colUnknown.back()).pos =
696         result.colUnknown.size() - 1;
697   }
698 
699   auto appendRowFromA = [&](unsigned row) {
700     for (unsigned col = 0; col < a.nCol; ++col)
701       result.tableau(result.nRow, col) = a.tableau(row, col);
702     result.rowUnknown.push_back(a.rowUnknown[row]);
703     result.unknownFromIndex(result.rowUnknown.back()).pos =
704         result.rowUnknown.size() - 1;
705     result.nRow++;
706   };
707 
708   // Also fixes the corresponding entry in rowUnknown and var/con (as the case
709   // may be).
710   auto appendRowFromB = [&](unsigned row) {
711     result.tableau(result.nRow, 0) = b.tableau(row, 0);
712     result.tableau(result.nRow, 1) = b.tableau(row, 1);
713 
714     unsigned offset = a.nCol - 2;
715     for (unsigned col = 2; col < b.nCol; ++col)
716       result.tableau(result.nRow, offset + col) = b.tableau(row, col);
717     result.rowUnknown.push_back(indexFromBIndex(b.rowUnknown[row]));
718     result.unknownFromIndex(result.rowUnknown.back()).pos =
719         result.rowUnknown.size() - 1;
720     result.nRow++;
721   };
722 
723   result.nRedundant = a.nRedundant + b.nRedundant;
724   for (unsigned row = 0; row < a.nRedundant; ++row)
725     appendRowFromA(row);
726   for (unsigned row = 0; row < b.nRedundant; ++row)
727     appendRowFromB(row);
728   for (unsigned row = a.nRedundant; row < a.nRow; ++row)
729     appendRowFromA(row);
730   for (unsigned row = b.nRedundant; row < b.nRow; ++row)
731     appendRowFromB(row);
732 
733   return result;
734 }
735 
736 SmallVector<Fraction, 8> Simplex::getRationalSample() const {
737   assert(!empty && "This should not be called when Simplex is empty.");
738 
739   SmallVector<Fraction, 8> sample;
740   sample.reserve(var.size());
741   // Push the sample value for each variable into the vector.
742   for (const Unknown &u : var) {
743     if (u.orientation == Orientation::Column) {
744       // If the variable is in column position, its sample value is zero.
745       sample.emplace_back(0, 1);
746     } else {
747       // If the variable is in row position, its sample value is the entry in
748       // the constant column divided by the entry in the common denominator
749       // column.
750       sample.emplace_back(tableau(u.pos, 1), tableau(u.pos, 0));
751     }
752   }
753   return sample;
754 }
755 
756 Optional<SmallVector<int64_t, 8>> Simplex::getSamplePointIfIntegral() const {
757   // If the tableau is empty, no sample point exists.
758   if (empty)
759     return {};
760   SmallVector<Fraction, 8> rationalSample = getRationalSample();
761   SmallVector<int64_t, 8> integerSample;
762   integerSample.reserve(var.size());
763   for (const Fraction &coord : rationalSample) {
764     // If the sample is non-integral, return None.
765     if (coord.num % coord.den != 0)
766       return {};
767     integerSample.push_back(coord.num / coord.den);
768   }
769   return integerSample;
770 }
771 
772 /// Given a simplex for a polytope, construct a new simplex whose variables are
773 /// identified with a pair of points (x, y) in the original polytope. Supports
774 /// some operations needed for generalized basis reduction. In what follows,
775 /// dotProduct(x, y) = x_1 * y_1 + x_2 * y_2 + ... x_n * y_n where n is the
776 /// dimension of the original polytope.
777 ///
778 /// This supports adding equality constraints dotProduct(dir, x - y) == 0. It
779 /// also supports rolling back this addition, by maintaining a snapshot stack
780 /// that contains a snapshot of the Simplex's state for each equality, just
781 /// before that equality was added.
782 class GBRSimplex {
783   using Orientation = Simplex::Orientation;
784 
785 public:
786   GBRSimplex(const Simplex &originalSimplex)
787       : simplex(Simplex::makeProduct(originalSimplex, originalSimplex)),
788         simplexConstraintOffset(simplex.getNumConstraints()) {}
789 
790   /// Add an equality dotProduct(dir, x - y) == 0.
791   /// First pushes a snapshot for the current simplex state to the stack so
792   /// that this can be rolled back later.
793   void addEqualityForDirection(ArrayRef<int64_t> dir) {
794     assert(
795         std::any_of(dir.begin(), dir.end(), [](int64_t x) { return x != 0; }) &&
796         "Direction passed is the zero vector!");
797     snapshotStack.push_back(simplex.getSnapshot());
798     simplex.addEquality(getCoeffsForDirection(dir));
799   }
800   /// Compute max(dotProduct(dir, x - y)).
801   Fraction computeWidth(ArrayRef<int64_t> dir) {
802     Optional<Fraction> maybeWidth =
803         simplex.computeOptimum(Direction::Up, getCoeffsForDirection(dir));
804     assert(maybeWidth.hasValue() && "Width should not be unbounded!");
805     return *maybeWidth;
806   }
807 
808   /// Compute max(dotProduct(dir, x - y)) and save the dual variables for only
809   /// the direction equalities to `dual`.
810   Fraction computeWidthAndDuals(ArrayRef<int64_t> dir,
811                                 SmallVectorImpl<int64_t> &dual,
812                                 int64_t &dualDenom) {
813     // We can't just call into computeWidth or computeOptimum since we need to
814     // access the state of the tableau after computing the optimum, and these
815     // functions rollback the insertion of the objective function into the
816     // tableau before returning. We instead add a row for the objective function
817     // ourselves, call into computeOptimum, compute the duals from the tableau
818     // state, and finally rollback the addition of the row before returning.
819     unsigned snap = simplex.getSnapshot();
820     unsigned conIndex = simplex.addRow(getCoeffsForDirection(dir));
821     unsigned row = simplex.con[conIndex].pos;
822     Optional<Fraction> maybeWidth =
823         simplex.computeRowOptimum(Simplex::Direction::Up, row);
824     assert(maybeWidth.hasValue() && "Width should not be unbounded!");
825     dualDenom = simplex.tableau(row, 0);
826     dual.clear();
827 
828     // The increment is i += 2 because equalities are added as two inequalities,
829     // one positive and one negative. Each iteration processes one equality.
830     for (unsigned i = simplexConstraintOffset; i < conIndex; i += 2) {
831       // The dual variable for an inequality in column orientation is the
832       // negative of its coefficient at the objective row. If the inequality is
833       // in row orientation, the corresponding dual variable is zero.
834       //
835       // We want the dual for the original equality, which corresponds to two
836       // inequalities: a positive inequality, which has the same coefficients as
837       // the equality, and a negative equality, which has negated coefficients.
838       //
839       // Note that at most one of these inequalities can be in column
840       // orientation because the column unknowns should form a basis and hence
841       // must be linearly independent. If the positive inequality is in column
842       // position, its dual is the dual corresponding to the equality. If the
843       // negative inequality is in column position, the negation of its dual is
844       // the dual corresponding to the equality. If neither is in column
845       // position, then that means that this equality is redundant, and its dual
846       // is zero.
847       //
848       // Note that it is NOT valid to perform pivots during the computation of
849       // the duals. This entire dual computation must be performed on the same
850       // tableau configuration.
851       assert(!(simplex.con[i].orientation == Orientation::Column &&
852                simplex.con[i + 1].orientation == Orientation::Column) &&
853              "Both inequalities for the equality cannot be in column "
854              "orientation!");
855       if (simplex.con[i].orientation == Orientation::Column)
856         dual.push_back(-simplex.tableau(row, simplex.con[i].pos));
857       else if (simplex.con[i + 1].orientation == Orientation::Column)
858         dual.push_back(simplex.tableau(row, simplex.con[i + 1].pos));
859       else
860         dual.push_back(0);
861     }
862     simplex.rollback(snap);
863     return *maybeWidth;
864   }
865 
866   /// Remove the last equality that was added through addEqualityForDirection.
867   ///
868   /// We do this by rolling back to the snapshot at the top of the stack, which
869   /// should be a snapshot taken just before the last equality was added.
870   void removeLastEquality() {
871     assert(!snapshotStack.empty() && "Snapshot stack is empty!");
872     simplex.rollback(snapshotStack.back());
873     snapshotStack.pop_back();
874   }
875 
876 private:
877   /// Returns coefficients of the expression 'dot_product(dir, x - y)',
878   /// i.e.,   dir_1 * x_1 + dir_2 * x_2 + ... + dir_n * x_n
879   ///       - dir_1 * y_1 - dir_2 * y_2 - ... - dir_n * y_n,
880   /// where n is the dimension of the original polytope.
881   SmallVector<int64_t, 8> getCoeffsForDirection(ArrayRef<int64_t> dir) {
882     assert(2 * dir.size() == simplex.getNumVariables() &&
883            "Direction vector has wrong dimensionality");
884     SmallVector<int64_t, 8> coeffs(dir.begin(), dir.end());
885     coeffs.reserve(2 * dir.size());
886     for (int64_t coeff : dir)
887       coeffs.push_back(-coeff);
888     coeffs.push_back(0); // constant term
889     return coeffs;
890   }
891 
892   Simplex simplex;
893   /// The first index of the equality constraints, the index immediately after
894   /// the last constraint in the initial product simplex.
895   unsigned simplexConstraintOffset;
896   /// A stack of snapshots, used for rolling back.
897   SmallVector<unsigned, 8> snapshotStack;
898 };
899 
900 // Return a + scale*b;
901 static SmallVector<int64_t, 8> scaleAndAdd(ArrayRef<int64_t> a, int64_t scale,
902                                            ArrayRef<int64_t> b) {
903   assert(a.size() == b.size());
904   SmallVector<int64_t, 8> res;
905   res.reserve(a.size());
906   for (unsigned i = 0, e = a.size(); i < e; ++i)
907     res.push_back(a[i] + scale * b[i]);
908   return res;
909 }
910 
911 /// Reduce the basis to try and find a direction in which the polytope is
912 /// "thin". This only works for bounded polytopes.
913 ///
914 /// This is an implementation of the algorithm described in the paper
915 /// "An Implementation of Generalized Basis Reduction for Integer Programming"
916 /// by W. Cook, T. Rutherford, H. E. Scarf, D. Shallcross.
917 ///
918 /// Let b_{level}, b_{level + 1}, ... b_n be the current basis.
919 /// Let width_i(v) = max <v, x - y> where x and y are points in the original
920 /// polytope such that <b_j, x - y> = 0 is satisfied for all level <= j < i.
921 ///
922 /// In every iteration, we first replace b_{i+1} with b_{i+1} + u*b_i, where u
923 /// is the integer such that width_i(b_{i+1} + u*b_i) is minimized. Let dual_i
924 /// be the dual variable associated with the constraint <b_i, x - y> = 0 when
925 /// computing width_{i+1}(b_{i+1}). It can be shown that dual_i is the
926 /// minimizing value of u, if it were allowed to be fractional. Due to
927 /// convexity, the minimizing integer value is either floor(dual_i) or
928 /// ceil(dual_i), so we just need to check which of these gives a lower
929 /// width_{i+1} value. If dual_i turned out to be an integer, then u = dual_i.
930 ///
931 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and (the new)
932 /// b_{i + 1} and decrement i (unless i = level, in which case we stay at the
933 /// same i). Otherwise, we increment i.
934 ///
935 /// We keep f values and duals cached and invalidate them when necessary.
936 /// Whenever possible, we use them instead of recomputing them. We implement the
937 /// algorithm as follows.
938 ///
939 /// In an iteration at i we need to compute:
940 ///   a) width_i(b_{i + 1})
941 ///   b) width_i(b_i)
942 ///   c) the integer u that minimizes width_i(b_{i + 1} + u*b_i)
943 ///
944 /// If width_i(b_i) is not already cached, we compute it.
945 ///
946 /// If the duals are not already cached, we compute width_{i+1}(b_{i+1}) and
947 /// store the duals from this computation.
948 ///
949 /// We call updateBasisWithUAndGetFCandidate, which finds the minimizing value
950 /// of u as explained before, caches the duals from this computation, sets
951 /// b_{i+1} to b_{i+1} + u*b_i, and returns the new value of width_i(b_{i+1}).
952 ///
953 /// Now if width_i(b_{i+1}) < 0.75 * width_i(b_i), we swap b_i and b_{i+1} and
954 /// decrement i, resulting in the basis
955 /// ... b_{i - 1}, b_{i + 1} + u*b_i, b_i, b_{i+2}, ...
956 /// with corresponding f values
957 /// ... width_{i-1}(b_{i-1}), width_i(b_{i+1} + u*b_i), width_{i+1}(b_i), ...
958 /// The values up to i - 1 remain unchanged. We have just gotten the middle
959 /// value from updateBasisWithUAndGetFCandidate, so we can update that in the
960 /// cache. The value at width_{i+1}(b_i) is unknown, so we evict this value from
961 /// the cache. The iteration after decrementing needs exactly the duals from the
962 /// computation of width_i(b_{i + 1} + u*b_i), so we keep these in the cache.
963 ///
964 /// When incrementing i, no cached f values get invalidated. However, the cached
965 /// duals do get invalidated as the duals for the higher levels are different.
966 void Simplex::reduceBasis(Matrix &basis, unsigned level) {
967   const Fraction epsilon(3, 4);
968 
969   if (level == basis.getNumRows() - 1)
970     return;
971 
972   GBRSimplex gbrSimplex(*this);
973   SmallVector<Fraction, 8> width;
974   SmallVector<int64_t, 8> dual;
975   int64_t dualDenom;
976 
977   // Finds the value of u that minimizes width_i(b_{i+1} + u*b_i), caches the
978   // duals from this computation, sets b_{i+1} to b_{i+1} + u*b_i, and returns
979   // the new value of width_i(b_{i+1}).
980   //
981   // If dual_i is not an integer, the minimizing value must be either
982   // floor(dual_i) or ceil(dual_i). We compute the expression for both and
983   // choose the minimizing value.
984   //
985   // If dual_i is an integer, we don't need to perform these computations. We
986   // know that in this case,
987   //   a) u = dual_i.
988   //   b) one can show that dual_j for j < i are the same duals we would have
989   //      gotten from computing width_i(b_{i + 1} + u*b_i), so the correct duals
990   //      are the ones already in the cache.
991   //   c) width_i(b_{i+1} + u*b_i) = min_{alpha} width_i(b_{i+1} + alpha * b_i),
992   //   which
993   //      one can show is equal to width_{i+1}(b_{i+1}). The latter value must
994   //      be in the cache, so we get it from there and return it.
995   auto updateBasisWithUAndGetFCandidate = [&](unsigned i) -> Fraction {
996     assert(i < level + dual.size() && "dual_i is not known!");
997 
998     int64_t u = floorDiv(dual[i - level], dualDenom);
999     basis.addToRow(i, i + 1, u);
1000     if (dual[i - level] % dualDenom != 0) {
1001       SmallVector<int64_t, 8> candidateDual[2];
1002       int64_t candidateDualDenom[2];
1003       Fraction widthI[2];
1004 
1005       // Initially u is floor(dual) and basis reflects this.
1006       widthI[0] = gbrSimplex.computeWidthAndDuals(
1007           basis.getRow(i + 1), candidateDual[0], candidateDualDenom[0]);
1008 
1009       // Now try ceil(dual), i.e. floor(dual) + 1.
1010       ++u;
1011       basis.addToRow(i, i + 1, 1);
1012       widthI[1] = gbrSimplex.computeWidthAndDuals(
1013           basis.getRow(i + 1), candidateDual[1], candidateDualDenom[1]);
1014 
1015       unsigned j = widthI[0] < widthI[1] ? 0 : 1;
1016       if (j == 0)
1017         // Subtract 1 to go from u = ceil(dual) back to floor(dual).
1018         basis.addToRow(i, i + 1, -1);
1019 
1020       // width_i(b{i+1} + u*b_i) should be minimized at our value of u.
1021       // We assert that this holds by checking that the values of width_i at
1022       // u - 1 and u + 1 are greater than or equal to the value at u. If the
1023       // width is lesser at either of the adjacent values, then our computed
1024       // value of u is clearly not the minimizer. Otherwise by convexity the
1025       // computed value of u is really the minimizer.
1026 
1027       // Check the value at u - 1.
1028       assert(gbrSimplex.computeWidth(scaleAndAdd(
1029                  basis.getRow(i + 1), -1, basis.getRow(i))) >= widthI[j] &&
1030              "Computed u value does not minimize the width!");
1031       // Check the value at u + 1.
1032       assert(gbrSimplex.computeWidth(scaleAndAdd(
1033                  basis.getRow(i + 1), +1, basis.getRow(i))) >= widthI[j] &&
1034              "Computed u value does not minimize the width!");
1035 
1036       dual = std::move(candidateDual[j]);
1037       dualDenom = candidateDualDenom[j];
1038       return widthI[j];
1039     }
1040 
1041     assert(i + 1 - level < width.size() && "width_{i+1} wasn't saved");
1042     // f_i(b_{i+1} + dual*b_i) == width_{i+1}(b_{i+1}) when `dual` minimizes the
1043     // LHS. (note: the basis has already been updated, so b_{i+1} + dual*b_i in
1044     // the above expression is equal to basis.getRow(i+1) below.)
1045     assert(gbrSimplex.computeWidth(basis.getRow(i + 1)) ==
1046            width[i + 1 - level]);
1047     return width[i + 1 - level];
1048   };
1049 
1050   // In the ith iteration of the loop, gbrSimplex has constraints for directions
1051   // from `level` to i - 1.
1052   unsigned i = level;
1053   while (i < basis.getNumRows() - 1) {
1054     if (i >= level + width.size()) {
1055       // We don't even know the value of f_i(b_i), so let's find that first.
1056       // We have to do this first since later we assume that width already
1057       // contains values up to and including i.
1058 
1059       assert((i == 0 || i - 1 < level + width.size()) &&
1060              "We are at level i but we don't know the value of width_{i-1}");
1061 
1062       // We don't actually use these duals at all, but it doesn't matter
1063       // because this case should only occur when i is level, and there are no
1064       // duals in that case anyway.
1065       assert(i == level && "This case should only occur when i == level");
1066       width.push_back(
1067           gbrSimplex.computeWidthAndDuals(basis.getRow(i), dual, dualDenom));
1068     }
1069 
1070     if (i >= level + dual.size()) {
1071       assert(i + 1 >= level + width.size() &&
1072              "We don't know dual_i but we know width_{i+1}");
1073       // We don't know dual for our level, so let's find it.
1074       gbrSimplex.addEqualityForDirection(basis.getRow(i));
1075       width.push_back(gbrSimplex.computeWidthAndDuals(basis.getRow(i + 1), dual,
1076                                                       dualDenom));
1077       gbrSimplex.removeLastEquality();
1078     }
1079 
1080     // This variable stores width_i(b_{i+1} + u*b_i).
1081     Fraction widthICandidate = updateBasisWithUAndGetFCandidate(i);
1082     if (widthICandidate < epsilon * width[i - level]) {
1083       basis.swapRows(i, i + 1);
1084       width[i - level] = widthICandidate;
1085       // The values of width_{i+1}(b_{i+1}) and higher may change after the
1086       // swap, so we remove the cached values here.
1087       width.resize(i - level + 1);
1088       if (i == level) {
1089         dual.clear();
1090         continue;
1091       }
1092 
1093       gbrSimplex.removeLastEquality();
1094       i--;
1095       continue;
1096     }
1097 
1098     // Invalidate duals since the higher level needs to recompute its own duals.
1099     dual.clear();
1100     gbrSimplex.addEqualityForDirection(basis.getRow(i));
1101     i++;
1102   }
1103 }
1104 
1105 /// Search for an integer sample point using a branch and bound algorithm.
1106 ///
1107 /// Each row in the basis matrix is a vector, and the set of basis vectors
1108 /// should span the space. Initially this is the identity matrix,
1109 /// i.e., the basis vectors are just the variables.
1110 ///
1111 /// In every level, a value is assigned to the level-th basis vector, as
1112 /// follows. Compute the minimum and maximum rational values of this direction.
1113 /// If only one integer point lies in this range, constrain the variable to
1114 /// have this value and recurse to the next variable.
1115 ///
1116 /// If the range has multiple values, perform generalized basis reduction via
1117 /// reduceBasis and then compute the bounds again. Now we try constraining
1118 /// this direction in the first value in this range and "recurse" to the next
1119 /// level. If we fail to find a sample, we try assigning the direction the next
1120 /// value in this range, and so on.
1121 ///
1122 /// If no integer sample is found from any of the assignments, or if the range
1123 /// contains no integer value, then of course the polytope is empty for the
1124 /// current assignment of the values in previous levels, so we return to
1125 /// the previous level.
1126 ///
1127 /// If we reach the last level where all the variables have been assigned values
1128 /// already, then we simply return the current sample point if it is integral,
1129 /// and go back to the previous level otherwise.
1130 ///
1131 /// To avoid potentially arbitrarily large recursion depths leading to stack
1132 /// overflows, this algorithm is implemented iteratively.
1133 Optional<SmallVector<int64_t, 8>> Simplex::findIntegerSample() {
1134   if (empty)
1135     return {};
1136 
1137   unsigned nDims = var.size();
1138   Matrix basis = Matrix::identity(nDims);
1139 
1140   unsigned level = 0;
1141   // The snapshot just before constraining a direction to a value at each level.
1142   SmallVector<unsigned, 8> snapshotStack;
1143   // The maximum value in the range of the direction for each level.
1144   SmallVector<int64_t, 8> upperBoundStack;
1145   // The next value to try constraining the basis vector to at each level.
1146   SmallVector<int64_t, 8> nextValueStack;
1147 
1148   snapshotStack.reserve(basis.getNumRows());
1149   upperBoundStack.reserve(basis.getNumRows());
1150   nextValueStack.reserve(basis.getNumRows());
1151   while (level != -1u) {
1152     if (level == basis.getNumRows()) {
1153       // We've assigned values to all variables. Return if we have a sample,
1154       // or go back up to the previous level otherwise.
1155       if (auto maybeSample = getSamplePointIfIntegral())
1156         return maybeSample;
1157       level--;
1158       continue;
1159     }
1160 
1161     if (level >= upperBoundStack.size()) {
1162       // We haven't populated the stack values for this level yet, so we have
1163       // just come down a level ("recursed"). Find the lower and upper bounds.
1164       // If there is more than one integer point in the range, perform
1165       // generalized basis reduction.
1166       SmallVector<int64_t, 8> basisCoeffs =
1167           llvm::to_vector<8>(basis.getRow(level));
1168       basisCoeffs.push_back(0);
1169 
1170       int64_t minRoundedUp, maxRoundedDown;
1171       std::tie(minRoundedUp, maxRoundedDown) =
1172           computeIntegerBounds(basisCoeffs);
1173 
1174       // Heuristic: if the sample point is integral at this point, just return
1175       // it.
1176       if (auto maybeSample = getSamplePointIfIntegral())
1177         return *maybeSample;
1178 
1179       if (minRoundedUp < maxRoundedDown) {
1180         reduceBasis(basis, level);
1181         basisCoeffs = llvm::to_vector<8>(basis.getRow(level));
1182         basisCoeffs.push_back(0);
1183         std::tie(minRoundedUp, maxRoundedDown) =
1184             computeIntegerBounds(basisCoeffs);
1185       }
1186 
1187       snapshotStack.push_back(getSnapshot());
1188       // The smallest value in the range is the next value to try.
1189       nextValueStack.push_back(minRoundedUp);
1190       upperBoundStack.push_back(maxRoundedDown);
1191     }
1192 
1193     assert((snapshotStack.size() - 1 == level &&
1194             nextValueStack.size() - 1 == level &&
1195             upperBoundStack.size() - 1 == level) &&
1196            "Mismatched variable stack sizes!");
1197 
1198     // Whether we "recursed" or "returned" from a lower level, we rollback
1199     // to the snapshot of the starting state at this level. (in the "recursed"
1200     // case this has no effect)
1201     rollback(snapshotStack.back());
1202     int64_t nextValue = nextValueStack.back();
1203     nextValueStack.back()++;
1204     if (nextValue > upperBoundStack.back()) {
1205       // We have exhausted the range and found no solution. Pop the stack and
1206       // return up a level.
1207       snapshotStack.pop_back();
1208       nextValueStack.pop_back();
1209       upperBoundStack.pop_back();
1210       level--;
1211       continue;
1212     }
1213 
1214     // Try the next value in the range and "recurse" into the next level.
1215     SmallVector<int64_t, 8> basisCoeffs(basis.getRow(level).begin(),
1216                                         basis.getRow(level).end());
1217     basisCoeffs.push_back(-nextValue);
1218     addEquality(basisCoeffs);
1219     level++;
1220   }
1221 
1222   return {};
1223 }
1224 
1225 /// Compute the minimum and maximum integer values the expression can take. We
1226 /// compute each separately.
1227 std::pair<int64_t, int64_t>
1228 Simplex::computeIntegerBounds(ArrayRef<int64_t> coeffs) {
1229   int64_t minRoundedUp;
1230   if (Optional<Fraction> maybeMin =
1231           computeOptimum(Simplex::Direction::Down, coeffs))
1232     minRoundedUp = ceil(*maybeMin);
1233   else
1234     llvm_unreachable("Tableau should not be unbounded");
1235 
1236   int64_t maxRoundedDown;
1237   if (Optional<Fraction> maybeMax =
1238           computeOptimum(Simplex::Direction::Up, coeffs))
1239     maxRoundedDown = floor(*maybeMax);
1240   else
1241     llvm_unreachable("Tableau should not be unbounded");
1242 
1243   return {minRoundedUp, maxRoundedDown};
1244 }
1245 
1246 void Simplex::print(raw_ostream &os) const {
1247   os << "rows = " << nRow << ", columns = " << nCol << "\n";
1248   if (empty)
1249     os << "Simplex marked empty!\n";
1250   os << "var: ";
1251   for (unsigned i = 0; i < var.size(); ++i) {
1252     if (i > 0)
1253       os << ", ";
1254     var[i].print(os);
1255   }
1256   os << "\ncon: ";
1257   for (unsigned i = 0; i < con.size(); ++i) {
1258     if (i > 0)
1259       os << ", ";
1260     con[i].print(os);
1261   }
1262   os << '\n';
1263   for (unsigned row = 0; row < nRow; ++row) {
1264     if (row > 0)
1265       os << ", ";
1266     os << "r" << row << ": " << rowUnknown[row];
1267   }
1268   os << '\n';
1269   os << "c0: denom, c1: const";
1270   for (unsigned col = 2; col < nCol; ++col)
1271     os << ", c" << col << ": " << colUnknown[col];
1272   os << '\n';
1273   for (unsigned row = 0; row < nRow; ++row) {
1274     for (unsigned col = 0; col < nCol; ++col)
1275       os << tableau(row, col) << '\t';
1276     os << '\n';
1277   }
1278   os << '\n';
1279 }
1280 
1281 void Simplex::dump() const { print(llvm::errs()); }
1282 
1283 bool Simplex::isRationalSubsetOf(const FlatAffineConstraints &fac) {
1284   if (isEmpty())
1285     return true;
1286 
1287   for (unsigned i = 0, e = fac.getNumInequalities(); i < e; ++i)
1288     if (!isRedundantInequality(fac.getInequality(i)))
1289       return false;
1290 
1291   for (unsigned i = 0, e = fac.getNumEqualities(); i < e; ++i)
1292     if (!isRedundantEquality(fac.getEquality(i)))
1293       return false;
1294 
1295   return true;
1296 }
1297 
1298 /// Computes the minimum value `coeffs` can take. If the value is greater than
1299 /// or equal to zero, the polytope entirely lies in the half-space defined by
1300 /// `coeffs >= 0`.
1301 bool Simplex::isRedundantInequality(ArrayRef<int64_t> coeffs) {
1302   Optional<Fraction> minimum = computeOptimum(Direction::Down, coeffs);
1303   return minimum && *minimum >= Fraction(0, 1);
1304 }
1305 
1306 /// Check whether the equality given by `coeffs == 0` is redundant given
1307 /// the existing constraints. This is redundant when `coeffs` is already
1308 /// always zero under the existing constraints. `coeffs` is always zero
1309 /// when the minimum and maximum value that `coeffs` can take are both zero.
1310 bool Simplex::isRedundantEquality(ArrayRef<int64_t> coeffs) {
1311   Optional<Fraction> minimum = computeOptimum(Direction::Down, coeffs);
1312   Optional<Fraction> maximum = computeOptimum(Direction::Up, coeffs);
1313   return minimum && maximum && *maximum == Fraction(0, 1) &&
1314          *minimum == Fraction(0, 1);
1315 }
1316 
1317 } // namespace mlir
1318