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