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