1 //===- IntegerRelation.cpp - MLIR IntegerRelation 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 // A class to represent an relation over integer tuples. A relation is
10 // represented as a constraint system over a space of tuples of integer valued
11 // varaiables supporting symbolic identifiers and existential quantification.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "mlir/Analysis/Presburger/IntegerRelation.h"
16 #include "mlir/Analysis/Presburger/LinearTransform.h"
17 #include "mlir/Analysis/Presburger/PWMAFunction.h"
18 #include "mlir/Analysis/Presburger/PresburgerRelation.h"
19 #include "mlir/Analysis/Presburger/Simplex.h"
20 #include "mlir/Analysis/Presburger/Utils.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/Support/Debug.h"
24 
25 #define DEBUG_TYPE "presburger"
26 
27 using namespace mlir;
28 using namespace presburger;
29 
30 using llvm::SmallDenseMap;
31 using llvm::SmallDenseSet;
32 
33 std::unique_ptr<IntegerRelation> IntegerRelation::clone() const {
34   return std::make_unique<IntegerRelation>(*this);
35 }
36 
37 std::unique_ptr<IntegerPolyhedron> IntegerPolyhedron::clone() const {
38   return std::make_unique<IntegerPolyhedron>(*this);
39 }
40 
41 void IntegerRelation::append(const IntegerRelation &other) {
42   assert(space.isEqual(other.getSpace()) && "Spaces must be equal.");
43 
44   inequalities.reserveRows(inequalities.getNumRows() +
45                            other.getNumInequalities());
46   equalities.reserveRows(equalities.getNumRows() + other.getNumEqualities());
47 
48   for (unsigned r = 0, e = other.getNumInequalities(); r < e; r++) {
49     addInequality(other.getInequality(r));
50   }
51   for (unsigned r = 0, e = other.getNumEqualities(); r < e; r++) {
52     addEquality(other.getEquality(r));
53   }
54 }
55 
56 IntegerRelation IntegerRelation::intersect(IntegerRelation other) const {
57   IntegerRelation result = *this;
58   result.mergeLocalIds(other);
59   result.append(other);
60   return result;
61 }
62 
63 bool IntegerRelation::isEqual(const IntegerRelation &other) const {
64   assert(space.isCompatible(other.getSpace()) && "Spaces must be compatible.");
65   return PresburgerRelation(*this).isEqual(PresburgerRelation(other));
66 }
67 
68 bool IntegerRelation::isSubsetOf(const IntegerRelation &other) const {
69   assert(space.isCompatible(other.getSpace()) && "Spaces must be compatible.");
70   return PresburgerRelation(*this).isSubsetOf(PresburgerRelation(other));
71 }
72 
73 MaybeOptimum<SmallVector<Fraction, 8>>
74 IntegerRelation::findRationalLexMin() const {
75   assert(getNumSymbolIds() == 0 && "Symbols are not supported!");
76   MaybeOptimum<SmallVector<Fraction, 8>> maybeLexMin =
77       LexSimplex(*this).findRationalLexMin();
78 
79   if (!maybeLexMin.isBounded())
80     return maybeLexMin;
81 
82   // The Simplex returns the lexmin over all the variables including locals. But
83   // locals are not actually part of the space and should not be returned in the
84   // result. Since the locals are placed last in the list of identifiers, they
85   // will be minimized last in the lexmin. So simply truncating out the locals
86   // from the end of the answer gives the desired lexmin over the dimensions.
87   assert(maybeLexMin->size() == getNumIds() &&
88          "Incorrect number of vars in lexMin!");
89   maybeLexMin->resize(getNumDimAndSymbolIds());
90   return maybeLexMin;
91 }
92 
93 MaybeOptimum<SmallVector<int64_t, 8>>
94 IntegerRelation::findIntegerLexMin() const {
95   assert(getNumSymbolIds() == 0 && "Symbols are not supported!");
96   MaybeOptimum<SmallVector<int64_t, 8>> maybeLexMin =
97       LexSimplex(*this).findIntegerLexMin();
98 
99   if (!maybeLexMin.isBounded())
100     return maybeLexMin.getKind();
101 
102   // The Simplex returns the lexmin over all the variables including locals. But
103   // locals are not actually part of the space and should not be returned in the
104   // result. Since the locals are placed last in the list of identifiers, they
105   // will be minimized last in the lexmin. So simply truncating out the locals
106   // from the end of the answer gives the desired lexmin over the dimensions.
107   assert(maybeLexMin->size() == getNumIds() &&
108          "Incorrect number of vars in lexMin!");
109   maybeLexMin->resize(getNumDimAndSymbolIds());
110   return maybeLexMin;
111 }
112 
113 static bool rangeIsZero(ArrayRef<int64_t> range) {
114   return llvm::all_of(range, [](int64_t x) { return x == 0; });
115 }
116 
117 void removeConstraintsInvolvingIdRange(IntegerRelation &poly, unsigned begin,
118                                        unsigned count) {
119   // We loop until i > 0 and index into i - 1 to avoid sign issues.
120   //
121   // We iterate backwards so that whether we remove constraint i - 1 or not, the
122   // next constraint to be tested is always i - 2.
123   for (unsigned i = poly.getNumEqualities(); i > 0; i--)
124     if (!rangeIsZero(poly.getEquality(i - 1).slice(begin, count)))
125       poly.removeEquality(i - 1);
126   for (unsigned i = poly.getNumInequalities(); i > 0; i--)
127     if (!rangeIsZero(poly.getInequality(i - 1).slice(begin, count)))
128       poly.removeInequality(i - 1);
129 }
130 
131 IntegerRelation::CountsSnapshot IntegerRelation::getCounts() const {
132   return {getSpace(), getNumInequalities(), getNumEqualities()};
133 }
134 
135 void IntegerRelation::truncateIdKind(IdKind kind, unsigned num) {
136   unsigned curNum = getNumIdKind(kind);
137   assert(num <= curNum && "Can't truncate to more ids!");
138   removeIdRange(kind, num, curNum);
139 }
140 
141 void IntegerRelation::truncateIdKind(IdKind kind,
142                                      const CountsSnapshot &counts) {
143   truncateIdKind(kind, counts.getSpace().getNumIdKind(kind));
144 }
145 
146 void IntegerRelation::truncate(const CountsSnapshot &counts) {
147   truncateIdKind(IdKind::Domain, counts);
148   truncateIdKind(IdKind::Range, counts);
149   truncateIdKind(IdKind::Symbol, counts);
150   truncateIdKind(IdKind::Local, counts);
151   removeInequalityRange(counts.getNumIneqs(), getNumInequalities());
152   removeEqualityRange(counts.getNumEqs(), getNumEqualities());
153 }
154 
155 SymbolicLexMin IntegerPolyhedron::findSymbolicIntegerLexMin() const {
156   // Compute the symbolic lexmin of the dims and locals, with the symbols being
157   // the actual symbols of this set.
158   SymbolicLexMin result =
159       SymbolicLexSimplex(*this, IntegerPolyhedron(PresburgerSpace::getSetSpace(
160                                     /*numDims=*/getNumSymbolIds())))
161           .computeSymbolicIntegerLexMin();
162 
163   // We want to return only the lexmin over the dims, so strip the locals from
164   // the computed lexmin.
165   result.lexmin.truncateOutput(result.lexmin.getNumOutputs() -
166                                getNumLocalIds());
167   return result;
168 }
169 
170 unsigned IntegerRelation::insertId(IdKind kind, unsigned pos, unsigned num) {
171   assert(pos <= getNumIdKind(kind));
172 
173   unsigned insertPos = space.insertId(kind, pos, num);
174   inequalities.insertColumns(insertPos, num);
175   equalities.insertColumns(insertPos, num);
176   return insertPos;
177 }
178 
179 unsigned IntegerRelation::appendId(IdKind kind, unsigned num) {
180   unsigned pos = getNumIdKind(kind);
181   return insertId(kind, pos, num);
182 }
183 
184 void IntegerRelation::addEquality(ArrayRef<int64_t> eq) {
185   assert(eq.size() == getNumCols());
186   unsigned row = equalities.appendExtraRow();
187   for (unsigned i = 0, e = eq.size(); i < e; ++i)
188     equalities(row, i) = eq[i];
189 }
190 
191 void IntegerRelation::addInequality(ArrayRef<int64_t> inEq) {
192   assert(inEq.size() == getNumCols());
193   unsigned row = inequalities.appendExtraRow();
194   for (unsigned i = 0, e = inEq.size(); i < e; ++i)
195     inequalities(row, i) = inEq[i];
196 }
197 
198 void IntegerRelation::removeId(IdKind kind, unsigned pos) {
199   removeIdRange(kind, pos, pos + 1);
200 }
201 
202 void IntegerRelation::removeId(unsigned pos) { removeIdRange(pos, pos + 1); }
203 
204 void IntegerRelation::removeIdRange(IdKind kind, unsigned idStart,
205                                     unsigned idLimit) {
206   assert(idLimit <= getNumIdKind(kind));
207 
208   if (idStart >= idLimit)
209     return;
210 
211   // Remove eliminated identifiers from the constraints.
212   unsigned offset = getIdKindOffset(kind);
213   equalities.removeColumns(offset + idStart, idLimit - idStart);
214   inequalities.removeColumns(offset + idStart, idLimit - idStart);
215 
216   // Remove eliminated identifiers from the space.
217   space.removeIdRange(kind, idStart, idLimit);
218 }
219 
220 void IntegerRelation::removeIdRange(unsigned idStart, unsigned idLimit) {
221   assert(idLimit <= getNumIds());
222 
223   if (idStart >= idLimit)
224     return;
225 
226   // Helper function to remove ids of the specified kind in the given range
227   // [start, limit), The range is absolute (i.e. it is not relative to the kind
228   // of identifier). Also updates `limit` to reflect the deleted identifiers.
229   auto removeIdKindInRange = [this](IdKind kind, unsigned &start,
230                                     unsigned &limit) {
231     if (start >= limit)
232       return;
233 
234     unsigned offset = getIdKindOffset(kind);
235     unsigned num = getNumIdKind(kind);
236 
237     // Get `start`, `limit` relative to the specified kind.
238     unsigned relativeStart =
239         start <= offset ? 0 : std::min(num, start - offset);
240     unsigned relativeLimit =
241         limit <= offset ? 0 : std::min(num, limit - offset);
242 
243     // Remove ids of the specified kind in the relative range.
244     removeIdRange(kind, relativeStart, relativeLimit);
245 
246     // Update `limit` to reflect deleted identifiers.
247     // `start` does not need to be updated because any identifiers that are
248     // deleted are after position `start`.
249     limit -= relativeLimit - relativeStart;
250   };
251 
252   removeIdKindInRange(IdKind::Domain, idStart, idLimit);
253   removeIdKindInRange(IdKind::Range, idStart, idLimit);
254   removeIdKindInRange(IdKind::Symbol, idStart, idLimit);
255   removeIdKindInRange(IdKind::Local, idStart, idLimit);
256 }
257 
258 void IntegerRelation::removeEquality(unsigned pos) {
259   equalities.removeRow(pos);
260 }
261 
262 void IntegerRelation::removeInequality(unsigned pos) {
263   inequalities.removeRow(pos);
264 }
265 
266 void IntegerRelation::removeEqualityRange(unsigned start, unsigned end) {
267   if (start >= end)
268     return;
269   equalities.removeRows(start, end - start);
270 }
271 
272 void IntegerRelation::removeInequalityRange(unsigned start, unsigned end) {
273   if (start >= end)
274     return;
275   inequalities.removeRows(start, end - start);
276 }
277 
278 void IntegerRelation::swapId(unsigned posA, unsigned posB) {
279   assert(posA < getNumIds() && "invalid position A");
280   assert(posB < getNumIds() && "invalid position B");
281 
282   if (posA == posB)
283     return;
284 
285   inequalities.swapColumns(posA, posB);
286   equalities.swapColumns(posA, posB);
287 }
288 
289 void IntegerRelation::clearConstraints() {
290   equalities.resizeVertically(0);
291   inequalities.resizeVertically(0);
292 }
293 
294 /// Gather all lower and upper bounds of the identifier at `pos`, and
295 /// optionally any equalities on it. In addition, the bounds are to be
296 /// independent of identifiers in position range [`offset`, `offset` + `num`).
297 void IntegerRelation::getLowerAndUpperBoundIndices(
298     unsigned pos, SmallVectorImpl<unsigned> *lbIndices,
299     SmallVectorImpl<unsigned> *ubIndices, SmallVectorImpl<unsigned> *eqIndices,
300     unsigned offset, unsigned num) const {
301   assert(pos < getNumIds() && "invalid position");
302   assert(offset + num < getNumCols() && "invalid range");
303 
304   // Checks for a constraint that has a non-zero coeff for the identifiers in
305   // the position range [offset, offset + num) while ignoring `pos`.
306   auto containsConstraintDependentOnRange = [&](unsigned r, bool isEq) {
307     unsigned c, f;
308     auto cst = isEq ? getEquality(r) : getInequality(r);
309     for (c = offset, f = offset + num; c < f; ++c) {
310       if (c == pos)
311         continue;
312       if (cst[c] != 0)
313         break;
314     }
315     return c < f;
316   };
317 
318   // Gather all lower bounds and upper bounds of the variable. Since the
319   // canonical form c_1*x_1 + c_2*x_2 + ... + c_0 >= 0, a constraint is a lower
320   // bound for x_i if c_i >= 1, and an upper bound if c_i <= -1.
321   for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
322     // The bounds are to be independent of [offset, offset + num) columns.
323     if (containsConstraintDependentOnRange(r, /*isEq=*/false))
324       continue;
325     if (atIneq(r, pos) >= 1) {
326       // Lower bound.
327       lbIndices->push_back(r);
328     } else if (atIneq(r, pos) <= -1) {
329       // Upper bound.
330       ubIndices->push_back(r);
331     }
332   }
333 
334   // An equality is both a lower and upper bound. Record any equalities
335   // involving the pos^th identifier.
336   if (!eqIndices)
337     return;
338 
339   for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
340     if (atEq(r, pos) == 0)
341       continue;
342     if (containsConstraintDependentOnRange(r, /*isEq=*/true))
343       continue;
344     eqIndices->push_back(r);
345   }
346 }
347 
348 bool IntegerRelation::hasConsistentState() const {
349   if (!inequalities.hasConsistentState())
350     return false;
351   if (!equalities.hasConsistentState())
352     return false;
353   return true;
354 }
355 
356 void IntegerRelation::setAndEliminate(unsigned pos, ArrayRef<int64_t> values) {
357   if (values.empty())
358     return;
359   assert(pos + values.size() <= getNumIds() &&
360          "invalid position or too many values");
361   // Setting x_j = p in sum_i a_i x_i + c is equivalent to adding p*a_j to the
362   // constant term and removing the id x_j. We do this for all the ids
363   // pos, pos + 1, ... pos + values.size() - 1.
364   unsigned constantColPos = getNumCols() - 1;
365   for (unsigned i = 0, numVals = values.size(); i < numVals; ++i)
366     inequalities.addToColumn(i + pos, constantColPos, values[i]);
367   for (unsigned i = 0, numVals = values.size(); i < numVals; ++i)
368     equalities.addToColumn(i + pos, constantColPos, values[i]);
369   removeIdRange(pos, pos + values.size());
370 }
371 
372 void IntegerRelation::clearAndCopyFrom(const IntegerRelation &other) {
373   *this = other;
374 }
375 
376 // Searches for a constraint with a non-zero coefficient at `colIdx` in
377 // equality (isEq=true) or inequality (isEq=false) constraints.
378 // Returns true and sets row found in search in `rowIdx`, false otherwise.
379 bool IntegerRelation::findConstraintWithNonZeroAt(unsigned colIdx, bool isEq,
380                                                   unsigned *rowIdx) const {
381   assert(colIdx < getNumCols() && "position out of bounds");
382   auto at = [&](unsigned rowIdx) -> int64_t {
383     return isEq ? atEq(rowIdx, colIdx) : atIneq(rowIdx, colIdx);
384   };
385   unsigned e = isEq ? getNumEqualities() : getNumInequalities();
386   for (*rowIdx = 0; *rowIdx < e; ++(*rowIdx)) {
387     if (at(*rowIdx) != 0) {
388       return true;
389     }
390   }
391   return false;
392 }
393 
394 void IntegerRelation::normalizeConstraintsByGCD() {
395   for (unsigned i = 0, e = getNumEqualities(); i < e; ++i)
396     equalities.normalizeRow(i);
397   for (unsigned i = 0, e = getNumInequalities(); i < e; ++i)
398     inequalities.normalizeRow(i);
399 }
400 
401 bool IntegerRelation::hasInvalidConstraint() const {
402   assert(hasConsistentState());
403   auto check = [&](bool isEq) -> bool {
404     unsigned numCols = getNumCols();
405     unsigned numRows = isEq ? getNumEqualities() : getNumInequalities();
406     for (unsigned i = 0, e = numRows; i < e; ++i) {
407       unsigned j;
408       for (j = 0; j < numCols - 1; ++j) {
409         int64_t v = isEq ? atEq(i, j) : atIneq(i, j);
410         // Skip rows with non-zero variable coefficients.
411         if (v != 0)
412           break;
413       }
414       if (j < numCols - 1) {
415         continue;
416       }
417       // Check validity of constant term at 'numCols - 1' w.r.t 'isEq'.
418       // Example invalid constraints include: '1 == 0' or '-1 >= 0'
419       int64_t v = isEq ? atEq(i, numCols - 1) : atIneq(i, numCols - 1);
420       if ((isEq && v != 0) || (!isEq && v < 0)) {
421         return true;
422       }
423     }
424     return false;
425   };
426   if (check(/*isEq=*/true))
427     return true;
428   return check(/*isEq=*/false);
429 }
430 
431 /// Eliminate identifier from constraint at `rowIdx` based on coefficient at
432 /// pivotRow, pivotCol. Columns in range [elimColStart, pivotCol) will not be
433 /// updated as they have already been eliminated.
434 static void eliminateFromConstraint(IntegerRelation *constraints,
435                                     unsigned rowIdx, unsigned pivotRow,
436                                     unsigned pivotCol, unsigned elimColStart,
437                                     bool isEq) {
438   // Skip if equality 'rowIdx' if same as 'pivotRow'.
439   if (isEq && rowIdx == pivotRow)
440     return;
441   auto at = [&](unsigned i, unsigned j) -> int64_t {
442     return isEq ? constraints->atEq(i, j) : constraints->atIneq(i, j);
443   };
444   int64_t leadCoeff = at(rowIdx, pivotCol);
445   // Skip if leading coefficient at 'rowIdx' is already zero.
446   if (leadCoeff == 0)
447     return;
448   int64_t pivotCoeff = constraints->atEq(pivotRow, pivotCol);
449   int64_t sign = (leadCoeff * pivotCoeff > 0) ? -1 : 1;
450   int64_t lcm = mlir::lcm(pivotCoeff, leadCoeff);
451   int64_t pivotMultiplier = sign * (lcm / std::abs(pivotCoeff));
452   int64_t rowMultiplier = lcm / std::abs(leadCoeff);
453 
454   unsigned numCols = constraints->getNumCols();
455   for (unsigned j = 0; j < numCols; ++j) {
456     // Skip updating column 'j' if it was just eliminated.
457     if (j >= elimColStart && j < pivotCol)
458       continue;
459     int64_t v = pivotMultiplier * constraints->atEq(pivotRow, j) +
460                 rowMultiplier * at(rowIdx, j);
461     isEq ? constraints->atEq(rowIdx, j) = v
462          : constraints->atIneq(rowIdx, j) = v;
463   }
464 }
465 
466 /// Returns the position of the identifier that has the minimum <number of lower
467 /// bounds> times <number of upper bounds> from the specified range of
468 /// identifiers [start, end). It is often best to eliminate in the increasing
469 /// order of these counts when doing Fourier-Motzkin elimination since FM adds
470 /// that many new constraints.
471 static unsigned getBestIdToEliminate(const IntegerRelation &cst, unsigned start,
472                                      unsigned end) {
473   assert(start < cst.getNumIds() && end < cst.getNumIds() + 1);
474 
475   auto getProductOfNumLowerUpperBounds = [&](unsigned pos) {
476     unsigned numLb = 0;
477     unsigned numUb = 0;
478     for (unsigned r = 0, e = cst.getNumInequalities(); r < e; r++) {
479       if (cst.atIneq(r, pos) > 0) {
480         ++numLb;
481       } else if (cst.atIneq(r, pos) < 0) {
482         ++numUb;
483       }
484     }
485     return numLb * numUb;
486   };
487 
488   unsigned minLoc = start;
489   unsigned min = getProductOfNumLowerUpperBounds(start);
490   for (unsigned c = start + 1; c < end; c++) {
491     unsigned numLbUbProduct = getProductOfNumLowerUpperBounds(c);
492     if (numLbUbProduct < min) {
493       min = numLbUbProduct;
494       minLoc = c;
495     }
496   }
497   return minLoc;
498 }
499 
500 // Checks for emptiness of the set by eliminating identifiers successively and
501 // using the GCD test (on all equality constraints) and checking for trivially
502 // invalid constraints. Returns 'true' if the constraint system is found to be
503 // empty; false otherwise.
504 bool IntegerRelation::isEmpty() const {
505   if (isEmptyByGCDTest() || hasInvalidConstraint())
506     return true;
507 
508   IntegerRelation tmpCst(*this);
509 
510   // First, eliminate as many local variables as possible using equalities.
511   tmpCst.removeRedundantLocalVars();
512   if (tmpCst.isEmptyByGCDTest() || tmpCst.hasInvalidConstraint())
513     return true;
514 
515   // Eliminate as many identifiers as possible using Gaussian elimination.
516   unsigned currentPos = 0;
517   while (currentPos < tmpCst.getNumIds()) {
518     tmpCst.gaussianEliminateIds(currentPos, tmpCst.getNumIds());
519     ++currentPos;
520     // We check emptiness through trivial checks after eliminating each ID to
521     // detect emptiness early. Since the checks isEmptyByGCDTest() and
522     // hasInvalidConstraint() are linear time and single sweep on the constraint
523     // buffer, this appears reasonable - but can optimize in the future.
524     if (tmpCst.hasInvalidConstraint() || tmpCst.isEmptyByGCDTest())
525       return true;
526   }
527 
528   // Eliminate the remaining using FM.
529   for (unsigned i = 0, e = tmpCst.getNumIds(); i < e; i++) {
530     tmpCst.fourierMotzkinEliminate(
531         getBestIdToEliminate(tmpCst, 0, tmpCst.getNumIds()));
532     // Check for a constraint explosion. This rarely happens in practice, but
533     // this check exists as a safeguard against improperly constructed
534     // constraint systems or artificially created arbitrarily complex systems
535     // that aren't the intended use case for IntegerRelation. This is
536     // needed since FM has a worst case exponential complexity in theory.
537     if (tmpCst.getNumConstraints() >= kExplosionFactor * getNumIds()) {
538       LLVM_DEBUG(llvm::dbgs() << "FM constraint explosion detected\n");
539       return false;
540     }
541 
542     // FM wouldn't have modified the equalities in any way. So no need to again
543     // run GCD test. Check for trivial invalid constraints.
544     if (tmpCst.hasInvalidConstraint())
545       return true;
546   }
547   return false;
548 }
549 
550 // Runs the GCD test on all equality constraints. Returns 'true' if this test
551 // fails on any equality. Returns 'false' otherwise.
552 // This test can be used to disprove the existence of a solution. If it returns
553 // true, no integer solution to the equality constraints can exist.
554 //
555 // GCD test definition:
556 //
557 // The equality constraint:
558 //
559 //  c_1*x_1 + c_2*x_2 + ... + c_n*x_n = c_0
560 //
561 // has an integer solution iff:
562 //
563 //  GCD of c_1, c_2, ..., c_n divides c_0.
564 //
565 bool IntegerRelation::isEmptyByGCDTest() const {
566   assert(hasConsistentState());
567   unsigned numCols = getNumCols();
568   for (unsigned i = 0, e = getNumEqualities(); i < e; ++i) {
569     uint64_t gcd = std::abs(atEq(i, 0));
570     for (unsigned j = 1; j < numCols - 1; ++j) {
571       gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(atEq(i, j)));
572     }
573     int64_t v = std::abs(atEq(i, numCols - 1));
574     if (gcd > 0 && (v % gcd != 0)) {
575       return true;
576     }
577   }
578   return false;
579 }
580 
581 // Returns a matrix where each row is a vector along which the polytope is
582 // bounded. The span of the returned vectors is guaranteed to contain all
583 // such vectors. The returned vectors are NOT guaranteed to be linearly
584 // independent. This function should not be called on empty sets.
585 //
586 // It is sufficient to check the perpendiculars of the constraints, as the set
587 // of perpendiculars which are bounded must span all bounded directions.
588 Matrix IntegerRelation::getBoundedDirections() const {
589   // Note that it is necessary to add the equalities too (which the constructor
590   // does) even though we don't need to check if they are bounded; whether an
591   // inequality is bounded or not depends on what other constraints, including
592   // equalities, are present.
593   Simplex simplex(*this);
594 
595   assert(!simplex.isEmpty() && "It is not meaningful to ask whether a "
596                                "direction is bounded in an empty set.");
597 
598   SmallVector<unsigned, 8> boundedIneqs;
599   // The constructor adds the inequalities to the simplex first, so this
600   // processes all the inequalities.
601   for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
602     if (simplex.isBoundedAlongConstraint(i))
603       boundedIneqs.push_back(i);
604   }
605 
606   // The direction vector is given by the coefficients and does not include the
607   // constant term, so the matrix has one fewer column.
608   unsigned dirsNumCols = getNumCols() - 1;
609   Matrix dirs(boundedIneqs.size() + getNumEqualities(), dirsNumCols);
610 
611   // Copy the bounded inequalities.
612   unsigned row = 0;
613   for (unsigned i : boundedIneqs) {
614     for (unsigned col = 0; col < dirsNumCols; ++col)
615       dirs(row, col) = atIneq(i, col);
616     ++row;
617   }
618 
619   // Copy the equalities. All the equalities' perpendiculars are bounded.
620   for (unsigned i = 0, e = getNumEqualities(); i < e; ++i) {
621     for (unsigned col = 0; col < dirsNumCols; ++col)
622       dirs(row, col) = atEq(i, col);
623     ++row;
624   }
625 
626   return dirs;
627 }
628 
629 bool IntegerRelation::isIntegerEmpty() const { return !findIntegerSample(); }
630 
631 /// Let this set be S. If S is bounded then we directly call into the GBR
632 /// sampling algorithm. Otherwise, there are some unbounded directions, i.e.,
633 /// vectors v such that S extends to infinity along v or -v. In this case we
634 /// use an algorithm described in the integer set library (isl) manual and used
635 /// by the isl_set_sample function in that library. The algorithm is:
636 ///
637 /// 1) Apply a unimodular transform T to S to obtain S*T, such that all
638 /// dimensions in which S*T is bounded lie in the linear span of a prefix of the
639 /// dimensions.
640 ///
641 /// 2) Construct a set B by removing all constraints that involve
642 /// the unbounded dimensions and then deleting the unbounded dimensions. Note
643 /// that B is a Bounded set.
644 ///
645 /// 3) Try to obtain a sample from B using the GBR sampling
646 /// algorithm. If no sample is found, return that S is empty.
647 ///
648 /// 4) Otherwise, substitute the obtained sample into S*T to obtain a set
649 /// C. C is a full-dimensional Cone and always contains a sample.
650 ///
651 /// 5) Obtain an integer sample from C.
652 ///
653 /// 6) Return T*v, where v is the concatenation of the samples from B and C.
654 ///
655 /// The following is a sketch of a proof that
656 /// a) If the algorithm returns empty, then S is empty.
657 /// b) If the algorithm returns a sample, it is a valid sample in S.
658 ///
659 /// The algorithm returns empty only if B is empty, in which case S*T is
660 /// certainly empty since B was obtained by removing constraints and then
661 /// deleting unconstrained dimensions from S*T. Since T is unimodular, a vector
662 /// v is in S*T iff T*v is in S. So in this case, since
663 /// S*T is empty, S is empty too.
664 ///
665 /// Otherwise, the algorithm substitutes the sample from B into S*T. All the
666 /// constraints of S*T that did not involve unbounded dimensions are satisfied
667 /// by this substitution. All dimensions in the linear span of the dimensions
668 /// outside the prefix are unbounded in S*T (step 1). Substituting values for
669 /// the bounded dimensions cannot make these dimensions bounded, and these are
670 /// the only remaining dimensions in C, so C is unbounded along every vector (in
671 /// the positive or negative direction, or both). C is hence a full-dimensional
672 /// cone and therefore always contains an integer point.
673 ///
674 /// Concatenating the samples from B and C gives a sample v in S*T, so the
675 /// returned sample T*v is a sample in S.
676 Optional<SmallVector<int64_t, 8>> IntegerRelation::findIntegerSample() const {
677   // First, try the GCD test heuristic.
678   if (isEmptyByGCDTest())
679     return {};
680 
681   Simplex simplex(*this);
682   if (simplex.isEmpty())
683     return {};
684 
685   // For a bounded set, we directly call into the GBR sampling algorithm.
686   if (!simplex.isUnbounded())
687     return simplex.findIntegerSample();
688 
689   // The set is unbounded. We cannot directly use the GBR algorithm.
690   //
691   // m is a matrix containing, in each row, a vector in which S is
692   // bounded, such that the linear span of all these dimensions contains all
693   // bounded dimensions in S.
694   Matrix m = getBoundedDirections();
695   // In column echelon form, each row of m occupies only the first rank(m)
696   // columns and has zeros on the other columns. The transform T that brings S
697   // to column echelon form is unimodular as well, so this is a suitable
698   // transform to use in step 1 of the algorithm.
699   std::pair<unsigned, LinearTransform> result =
700       LinearTransform::makeTransformToColumnEchelon(std::move(m));
701   const LinearTransform &transform = result.second;
702   // 1) Apply T to S to obtain S*T.
703   IntegerRelation transformedSet = transform.applyTo(*this);
704 
705   // 2) Remove the unbounded dimensions and constraints involving them to
706   // obtain a bounded set.
707   IntegerRelation boundedSet(transformedSet);
708   unsigned numBoundedDims = result.first;
709   unsigned numUnboundedDims = getNumIds() - numBoundedDims;
710   removeConstraintsInvolvingIdRange(boundedSet, numBoundedDims,
711                                     numUnboundedDims);
712   boundedSet.removeIdRange(numBoundedDims, boundedSet.getNumIds());
713 
714   // 3) Try to obtain a sample from the bounded set.
715   Optional<SmallVector<int64_t, 8>> boundedSample =
716       Simplex(boundedSet).findIntegerSample();
717   if (!boundedSample)
718     return {};
719   assert(boundedSet.containsPoint(*boundedSample) &&
720          "Simplex returned an invalid sample!");
721 
722   // 4) Substitute the values of the bounded dimensions into S*T to obtain a
723   // full-dimensional cone, which necessarily contains an integer sample.
724   transformedSet.setAndEliminate(0, *boundedSample);
725   IntegerRelation &cone = transformedSet;
726 
727   // 5) Obtain an integer sample from the cone.
728   //
729   // We shrink the cone such that for any rational point in the shrunken cone,
730   // rounding up each of the point's coordinates produces a point that still
731   // lies in the original cone.
732   //
733   // Rounding up a point x adds a number e_i in [0, 1) to each coordinate x_i.
734   // For each inequality sum_i a_i x_i + c >= 0 in the original cone, the
735   // shrunken cone will have the inequality tightened by some amount s, such
736   // that if x satisfies the shrunken cone's tightened inequality, then x + e
737   // satisfies the original inequality, i.e.,
738   //
739   // sum_i a_i x_i + c + s >= 0 implies sum_i a_i (x_i + e_i) + c >= 0
740   //
741   // for any e_i values in [0, 1). In fact, we will handle the slightly more
742   // general case where e_i can be in [0, 1]. For example, consider the
743   // inequality 2x_1 - 3x_2 - 7x_3 - 6 >= 0, and let x = (3, 0, 0). How low
744   // could the LHS go if we added a number in [0, 1] to each coordinate? The LHS
745   // is minimized when we add 1 to the x_i with negative coefficient a_i and
746   // keep the other x_i the same. In the example, we would get x = (3, 1, 1),
747   // changing the value of the LHS by -3 + -7 = -10.
748   //
749   // In general, the value of the LHS can change by at most the sum of the
750   // negative a_i, so we accomodate this by shifting the inequality by this
751   // amount for the shrunken cone.
752   for (unsigned i = 0, e = cone.getNumInequalities(); i < e; ++i) {
753     for (unsigned j = 0; j < cone.getNumIds(); ++j) {
754       int64_t coeff = cone.atIneq(i, j);
755       if (coeff < 0)
756         cone.atIneq(i, cone.getNumIds()) += coeff;
757     }
758   }
759 
760   // Obtain an integer sample in the cone by rounding up a rational point from
761   // the shrunken cone. Shrinking the cone amounts to shifting its apex
762   // "inwards" without changing its "shape"; the shrunken cone is still a
763   // full-dimensional cone and is hence non-empty.
764   Simplex shrunkenConeSimplex(cone);
765   assert(!shrunkenConeSimplex.isEmpty() && "Shrunken cone cannot be empty!");
766 
767   // The sample will always exist since the shrunken cone is non-empty.
768   SmallVector<Fraction, 8> shrunkenConeSample =
769       *shrunkenConeSimplex.getRationalSample();
770 
771   SmallVector<int64_t, 8> coneSample(llvm::map_range(shrunkenConeSample, ceil));
772 
773   // 6) Return transform * concat(boundedSample, coneSample).
774   SmallVector<int64_t, 8> &sample = *boundedSample;
775   sample.append(coneSample.begin(), coneSample.end());
776   return transform.postMultiplyWithColumn(sample);
777 }
778 
779 /// Helper to evaluate an affine expression at a point.
780 /// The expression is a list of coefficients for the dimensions followed by the
781 /// constant term.
782 static int64_t valueAt(ArrayRef<int64_t> expr, ArrayRef<int64_t> point) {
783   assert(expr.size() == 1 + point.size() &&
784          "Dimensionalities of point and expression don't match!");
785   int64_t value = expr.back();
786   for (unsigned i = 0; i < point.size(); ++i)
787     value += expr[i] * point[i];
788   return value;
789 }
790 
791 /// A point satisfies an equality iff the value of the equality at the
792 /// expression is zero, and it satisfies an inequality iff the value of the
793 /// inequality at that point is non-negative.
794 bool IntegerRelation::containsPoint(ArrayRef<int64_t> point) const {
795   for (unsigned i = 0, e = getNumEqualities(); i < e; ++i) {
796     if (valueAt(getEquality(i), point) != 0)
797       return false;
798   }
799   for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
800     if (valueAt(getInequality(i), point) < 0)
801       return false;
802   }
803   return true;
804 }
805 
806 /// Just substitute the values given and check if an integer sample exists for
807 /// the local ids.
808 ///
809 /// TODO: this could be made more efficient by handling divisions separately.
810 /// Instead of finding an integer sample over all the locals, we can first
811 /// compute the values of the locals that have division representations and
812 /// only use the integer emptiness check for the locals that don't have this.
813 /// Handling this correctly requires ordering the divs, though.
814 Optional<SmallVector<int64_t, 8>>
815 IntegerRelation::containsPointNoLocal(ArrayRef<int64_t> point) const {
816   assert(point.size() == getNumIds() - getNumLocalIds() &&
817          "Point should contain all ids except locals!");
818   assert(getIdKindOffset(IdKind::Local) == getNumIds() - getNumLocalIds() &&
819          "This function depends on locals being stored last!");
820   IntegerRelation copy = *this;
821   copy.setAndEliminate(0, point);
822   return copy.findIntegerSample();
823 }
824 
825 void IntegerRelation::getLocalReprs(std::vector<MaybeLocalRepr> &repr) const {
826   std::vector<SmallVector<int64_t, 8>> dividends(getNumLocalIds());
827   SmallVector<unsigned, 4> denominators(getNumLocalIds());
828   getLocalReprs(dividends, denominators, repr);
829 }
830 
831 void IntegerRelation::getLocalReprs(
832     std::vector<SmallVector<int64_t, 8>> &dividends,
833     SmallVector<unsigned, 4> &denominators) const {
834   std::vector<MaybeLocalRepr> repr(getNumLocalIds());
835   getLocalReprs(dividends, denominators, repr);
836 }
837 
838 void IntegerRelation::getLocalReprs(
839     std::vector<SmallVector<int64_t, 8>> &dividends,
840     SmallVector<unsigned, 4> &denominators,
841     std::vector<MaybeLocalRepr> &repr) const {
842 
843   repr.resize(getNumLocalIds());
844   dividends.resize(getNumLocalIds());
845   denominators.resize(getNumLocalIds());
846 
847   SmallVector<bool, 8> foundRepr(getNumIds(), false);
848   for (unsigned i = 0, e = getNumDimAndSymbolIds(); i < e; ++i)
849     foundRepr[i] = true;
850 
851   unsigned divOffset = getNumDimAndSymbolIds();
852   bool changed;
853   do {
854     // Each time changed is true, at end of this iteration, one or more local
855     // vars have been detected as floor divs.
856     changed = false;
857     for (unsigned i = 0, e = getNumLocalIds(); i < e; ++i) {
858       if (!foundRepr[i + divOffset]) {
859         MaybeLocalRepr res = computeSingleVarRepr(
860             *this, foundRepr, divOffset + i, dividends[i], denominators[i]);
861         if (!res)
862           continue;
863         foundRepr[i + divOffset] = true;
864         repr[i] = res;
865         changed = true;
866       }
867     }
868   } while (changed);
869 
870   // Set 0 denominator for identifiers for which no division representation
871   // could be found.
872   for (unsigned i = 0, e = repr.size(); i < e; ++i)
873     if (!repr[i])
874       denominators[i] = 0;
875 }
876 
877 /// Tightens inequalities given that we are dealing with integer spaces. This is
878 /// analogous to the GCD test but applied to inequalities. The constant term can
879 /// be reduced to the preceding multiple of the GCD of the coefficients, i.e.,
880 ///  64*i - 100 >= 0  =>  64*i - 128 >= 0 (since 'i' is an integer). This is a
881 /// fast method - linear in the number of coefficients.
882 // Example on how this affects practical cases: consider the scenario:
883 // 64*i >= 100, j = 64*i; without a tightening, elimination of i would yield
884 // j >= 100 instead of the tighter (exact) j >= 128.
885 void IntegerRelation::gcdTightenInequalities() {
886   unsigned numCols = getNumCols();
887   for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
888     // Normalize the constraint and tighten the constant term by the GCD.
889     int64_t gcd = inequalities.normalizeRow(i, getNumCols() - 1);
890     if (gcd > 1)
891       atIneq(i, numCols - 1) = mlir::floorDiv(atIneq(i, numCols - 1), gcd);
892   }
893 }
894 
895 // Eliminates all identifier variables in column range [posStart, posLimit).
896 // Returns the number of variables eliminated.
897 unsigned IntegerRelation::gaussianEliminateIds(unsigned posStart,
898                                                unsigned posLimit) {
899   // Return if identifier positions to eliminate are out of range.
900   assert(posLimit <= getNumIds());
901   assert(hasConsistentState());
902 
903   if (posStart >= posLimit)
904     return 0;
905 
906   gcdTightenInequalities();
907 
908   unsigned pivotCol = 0;
909   for (pivotCol = posStart; pivotCol < posLimit; ++pivotCol) {
910     // Find a row which has a non-zero coefficient in column 'j'.
911     unsigned pivotRow;
912     if (!findConstraintWithNonZeroAt(pivotCol, /*isEq=*/true, &pivotRow)) {
913       // No pivot row in equalities with non-zero at 'pivotCol'.
914       if (!findConstraintWithNonZeroAt(pivotCol, /*isEq=*/false, &pivotRow)) {
915         // If inequalities are also non-zero in 'pivotCol', it can be
916         // eliminated.
917         continue;
918       }
919       break;
920     }
921 
922     // Eliminate identifier at 'pivotCol' from each equality row.
923     for (unsigned i = 0, e = getNumEqualities(); i < e; ++i) {
924       eliminateFromConstraint(this, i, pivotRow, pivotCol, posStart,
925                               /*isEq=*/true);
926       equalities.normalizeRow(i);
927     }
928 
929     // Eliminate identifier at 'pivotCol' from each inequality row.
930     for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
931       eliminateFromConstraint(this, i, pivotRow, pivotCol, posStart,
932                               /*isEq=*/false);
933       inequalities.normalizeRow(i);
934     }
935     removeEquality(pivotRow);
936     gcdTightenInequalities();
937   }
938   // Update position limit based on number eliminated.
939   posLimit = pivotCol;
940   // Remove eliminated columns from all constraints.
941   removeIdRange(posStart, posLimit);
942   return posLimit - posStart;
943 }
944 
945 // A more complex check to eliminate redundant inequalities. Uses FourierMotzkin
946 // to check if a constraint is redundant.
947 void IntegerRelation::removeRedundantInequalities() {
948   SmallVector<bool, 32> redun(getNumInequalities(), false);
949   // To check if an inequality is redundant, we replace the inequality by its
950   // complement (for eg., i - 1 >= 0 by i <= 0), and check if the resulting
951   // system is empty. If it is, the inequality is redundant.
952   IntegerRelation tmpCst(*this);
953   for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
954     // Change the inequality to its complement.
955     tmpCst.inequalities.negateRow(r);
956     --tmpCst.atIneq(r, tmpCst.getNumCols() - 1);
957     if (tmpCst.isEmpty()) {
958       redun[r] = true;
959       // Zero fill the redundant inequality.
960       inequalities.fillRow(r, /*value=*/0);
961       tmpCst.inequalities.fillRow(r, /*value=*/0);
962     } else {
963       // Reverse the change (to avoid recreating tmpCst each time).
964       ++tmpCst.atIneq(r, tmpCst.getNumCols() - 1);
965       tmpCst.inequalities.negateRow(r);
966     }
967   }
968 
969   unsigned pos = 0;
970   for (unsigned r = 0, e = getNumInequalities(); r < e; ++r) {
971     if (!redun[r])
972       inequalities.copyRow(r, pos++);
973   }
974   inequalities.resizeVertically(pos);
975 }
976 
977 // A more complex check to eliminate redundant inequalities and equalities. Uses
978 // Simplex to check if a constraint is redundant.
979 void IntegerRelation::removeRedundantConstraints() {
980   // First, we run gcdTightenInequalities. This allows us to catch some
981   // constraints which are not redundant when considering rational solutions
982   // but are redundant in terms of integer solutions.
983   gcdTightenInequalities();
984   Simplex simplex(*this);
985   simplex.detectRedundant();
986 
987   unsigned pos = 0;
988   unsigned numIneqs = getNumInequalities();
989   // Scan to get rid of all inequalities marked redundant, in-place. In Simplex,
990   // the first constraints added are the inequalities.
991   for (unsigned r = 0; r < numIneqs; r++) {
992     if (!simplex.isMarkedRedundant(r))
993       inequalities.copyRow(r, pos++);
994   }
995   inequalities.resizeVertically(pos);
996 
997   // Scan to get rid of all equalities marked redundant, in-place. In Simplex,
998   // after the inequalities, a pair of constraints for each equality is added.
999   // An equality is redundant if both the inequalities in its pair are
1000   // redundant.
1001   pos = 0;
1002   for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
1003     if (!(simplex.isMarkedRedundant(numIneqs + 2 * r) &&
1004           simplex.isMarkedRedundant(numIneqs + 2 * r + 1)))
1005       equalities.copyRow(r, pos++);
1006   }
1007   equalities.resizeVertically(pos);
1008 }
1009 
1010 Optional<uint64_t> IntegerRelation::computeVolume() const {
1011   assert(getNumSymbolIds() == 0 && "Symbols are not yet supported!");
1012 
1013   Simplex simplex(*this);
1014   // If the polytope is rationally empty, there are certainly no integer
1015   // points.
1016   if (simplex.isEmpty())
1017     return 0;
1018 
1019   // Just find the maximum and minimum integer value of each non-local id
1020   // separately, thus finding the number of integer values each such id can
1021   // take. Multiplying these together gives a valid overapproximation of the
1022   // number of integer points in the relation. The result this gives is
1023   // equivalent to projecting (rationally) the relation onto its non-local ids
1024   // and returning the number of integer points in a minimal axis-parallel
1025   // hyperrectangular overapproximation of that.
1026   //
1027   // We also handle the special case where one dimension is unbounded and
1028   // another dimension can take no integer values. In this case, the volume is
1029   // zero.
1030   //
1031   // If there is no such empty dimension, if any dimension is unbounded we
1032   // just return the result as unbounded.
1033   uint64_t count = 1;
1034   SmallVector<int64_t, 8> dim(getNumIds() + 1);
1035   bool hasUnboundedId = false;
1036   for (unsigned i = 0, e = getNumDimAndSymbolIds(); i < e; ++i) {
1037     dim[i] = 1;
1038     MaybeOptimum<int64_t> min, max;
1039     std::tie(min, max) = simplex.computeIntegerBounds(dim);
1040     dim[i] = 0;
1041 
1042     assert((!min.isEmpty() && !max.isEmpty()) &&
1043            "Polytope should be rationally non-empty!");
1044 
1045     // One of the dimensions is unbounded. Note this fact. We will return
1046     // unbounded if none of the other dimensions makes the volume zero.
1047     if (min.isUnbounded() || max.isUnbounded()) {
1048       hasUnboundedId = true;
1049       continue;
1050     }
1051 
1052     // In this case there are no valid integer points and the volume is
1053     // definitely zero.
1054     if (min.getBoundedOptimum() > max.getBoundedOptimum())
1055       return 0;
1056 
1057     count *= (*max - *min + 1);
1058   }
1059 
1060   if (count == 0)
1061     return 0;
1062   if (hasUnboundedId)
1063     return {};
1064   return count;
1065 }
1066 
1067 void IntegerRelation::eliminateRedundantLocalId(unsigned posA, unsigned posB) {
1068   assert(posA < getNumLocalIds() && "Invalid local id position");
1069   assert(posB < getNumLocalIds() && "Invalid local id position");
1070 
1071   unsigned localOffset = getIdKindOffset(IdKind::Local);
1072   posA += localOffset;
1073   posB += localOffset;
1074   inequalities.addToColumn(posB, posA, 1);
1075   equalities.addToColumn(posB, posA, 1);
1076   removeId(posB);
1077 }
1078 
1079 /// Adds additional local ids to the sets such that they both have the union
1080 /// of the local ids in each set, without changing the set of points that
1081 /// lie in `this` and `other`.
1082 ///
1083 /// To detect local ids that always take the same value, each local id is
1084 /// represented as a floordiv with constant denominator in terms of other ids.
1085 /// After extracting these divisions, local ids in `other` with the same
1086 /// division representation as some other local id in any set are considered
1087 /// duplicate and are merged.
1088 ///
1089 /// It is possible that division representation for some local id cannot be
1090 /// obtained, and thus these local ids are not considered for detecting
1091 /// duplicates.
1092 unsigned IntegerRelation::mergeLocalIds(IntegerRelation &other) {
1093   IntegerRelation &relA = *this;
1094   IntegerRelation &relB = other;
1095 
1096   unsigned oldALocals = relA.getNumLocalIds();
1097 
1098   // Merge function that merges the local variables in both sets by treating
1099   // them as the same identifier.
1100   auto merge = [&relA, &relB, oldALocals](unsigned i, unsigned j) -> bool {
1101     // We only merge from local at pos j to local at pos i, where j > i.
1102     if (i >= j)
1103       return false;
1104 
1105     // If i < oldALocals, we are trying to merge duplicate divs. Since we do not
1106     // want to merge duplicates in A, we ignore this call.
1107     if (j < oldALocals)
1108       return false;
1109 
1110     // Merge local at pos j into local at position i.
1111     relA.eliminateRedundantLocalId(i, j);
1112     relB.eliminateRedundantLocalId(i, j);
1113     return true;
1114   };
1115 
1116   presburger::mergeLocalIds(*this, other, merge);
1117 
1118   // Since we do not remove duplicate divisions in relA, this is guranteed to be
1119   // non-negative.
1120   return relA.getNumLocalIds() - oldALocals;
1121 }
1122 
1123 void IntegerRelation::removeDuplicateDivs() {
1124   std::vector<SmallVector<int64_t, 8>> divs;
1125   SmallVector<unsigned, 4> denoms;
1126 
1127   getLocalReprs(divs, denoms);
1128   auto merge = [this](unsigned i, unsigned j) -> bool {
1129     eliminateRedundantLocalId(i, j);
1130     return true;
1131   };
1132   presburger::removeDuplicateDivs(divs, denoms, getIdKindOffset(IdKind::Local),
1133                                   merge);
1134 }
1135 
1136 /// Removes local variables using equalities. Each equality is checked if it
1137 /// can be reduced to the form: `e = affine-expr`, where `e` is a local
1138 /// variable and `affine-expr` is an affine expression not containing `e`.
1139 /// If an equality satisfies this form, the local variable is replaced in
1140 /// each constraint and then removed. The equality used to replace this local
1141 /// variable is also removed.
1142 void IntegerRelation::removeRedundantLocalVars() {
1143   // Normalize the equality constraints to reduce coefficients of local
1144   // variables to 1 wherever possible.
1145   for (unsigned i = 0, e = getNumEqualities(); i < e; ++i)
1146     equalities.normalizeRow(i);
1147 
1148   while (true) {
1149     unsigned i, e, j, f;
1150     for (i = 0, e = getNumEqualities(); i < e; ++i) {
1151       // Find a local variable to eliminate using ith equality.
1152       for (j = getNumDimAndSymbolIds(), f = getNumIds(); j < f; ++j)
1153         if (std::abs(atEq(i, j)) == 1)
1154           break;
1155 
1156       // Local variable can be eliminated using ith equality.
1157       if (j < f)
1158         break;
1159     }
1160 
1161     // No equality can be used to eliminate a local variable.
1162     if (i == e)
1163       break;
1164 
1165     // Use the ith equality to simplify other equalities. If any changes
1166     // are made to an equality constraint, it is normalized by GCD.
1167     for (unsigned k = 0, t = getNumEqualities(); k < t; ++k) {
1168       if (atEq(k, j) != 0) {
1169         eliminateFromConstraint(this, k, i, j, j, /*isEq=*/true);
1170         equalities.normalizeRow(k);
1171       }
1172     }
1173 
1174     // Use the ith equality to simplify inequalities.
1175     for (unsigned k = 0, t = getNumInequalities(); k < t; ++k)
1176       eliminateFromConstraint(this, k, i, j, j, /*isEq=*/false);
1177 
1178     // Remove the ith equality and the found local variable.
1179     removeId(j);
1180     removeEquality(i);
1181   }
1182 }
1183 
1184 void IntegerRelation::convertIdKind(IdKind srcKind, unsigned idStart,
1185                                     unsigned idLimit, IdKind dstKind,
1186                                     unsigned pos) {
1187   assert(idLimit <= getNumIdKind(srcKind) && "Invalid id range");
1188 
1189   if (idStart >= idLimit)
1190     return;
1191 
1192   // Append new local variables corresponding to the dimensions to be converted.
1193   unsigned convertCount = idLimit - idStart;
1194   unsigned newIdsBegin = insertId(dstKind, pos, convertCount);
1195 
1196   // Swap the new local variables with dimensions.
1197   //
1198   // Essentially, this moves the information corresponding to the specified ids
1199   // of kind `srcKind` to the `convertCount` newly created ids of kind
1200   // `dstKind`. In particular, this moves the columns in the constraint
1201   // matrices, and zeros out the initially occupied columns (because the newly
1202   // created ids we're swapping with were zero-initialized).
1203   unsigned offset = getIdKindOffset(srcKind);
1204   for (unsigned i = 0; i < convertCount; ++i)
1205     swapId(offset + idStart + i, newIdsBegin + i);
1206 
1207   // Complete the move by deleting the initially occupied columns.
1208   removeIdRange(srcKind, idStart, idLimit);
1209 }
1210 
1211 void IntegerRelation::addBound(BoundType type, unsigned pos, int64_t value) {
1212   assert(pos < getNumCols());
1213   if (type == BoundType::EQ) {
1214     unsigned row = equalities.appendExtraRow();
1215     equalities(row, pos) = 1;
1216     equalities(row, getNumCols() - 1) = -value;
1217   } else {
1218     unsigned row = inequalities.appendExtraRow();
1219     inequalities(row, pos) = type == BoundType::LB ? 1 : -1;
1220     inequalities(row, getNumCols() - 1) =
1221         type == BoundType::LB ? -value : value;
1222   }
1223 }
1224 
1225 void IntegerRelation::addBound(BoundType type, ArrayRef<int64_t> expr,
1226                                int64_t value) {
1227   assert(type != BoundType::EQ && "EQ not implemented");
1228   assert(expr.size() == getNumCols());
1229   unsigned row = inequalities.appendExtraRow();
1230   for (unsigned i = 0, e = expr.size(); i < e; ++i)
1231     inequalities(row, i) = type == BoundType::LB ? expr[i] : -expr[i];
1232   inequalities(inequalities.getNumRows() - 1, getNumCols() - 1) +=
1233       type == BoundType::LB ? -value : value;
1234 }
1235 
1236 /// Adds a new local identifier as the floordiv of an affine function of other
1237 /// identifiers, the coefficients of which are provided in 'dividend' and with
1238 /// respect to a positive constant 'divisor'. Two constraints are added to the
1239 /// system to capture equivalence with the floordiv.
1240 ///      q = expr floordiv c    <=>   c*q <= expr <= c*q + c - 1.
1241 void IntegerRelation::addLocalFloorDiv(ArrayRef<int64_t> dividend,
1242                                        int64_t divisor) {
1243   assert(dividend.size() == getNumCols() && "incorrect dividend size");
1244   assert(divisor > 0 && "positive divisor expected");
1245 
1246   appendId(IdKind::Local);
1247 
1248   // Add two constraints for this new identifier 'q'.
1249   SmallVector<int64_t, 8> bound(dividend.size() + 1);
1250 
1251   // dividend - q * divisor >= 0
1252   std::copy(dividend.begin(), dividend.begin() + dividend.size() - 1,
1253             bound.begin());
1254   bound.back() = dividend.back();
1255   bound[getNumIds() - 1] = -divisor;
1256   addInequality(bound);
1257 
1258   // -dividend +qdivisor * q + divisor - 1 >= 0
1259   std::transform(bound.begin(), bound.end(), bound.begin(),
1260                  std::negate<int64_t>());
1261   bound[bound.size() - 1] += divisor - 1;
1262   addInequality(bound);
1263 }
1264 
1265 /// Finds an equality that equates the specified identifier to a constant.
1266 /// Returns the position of the equality row. If 'symbolic' is set to true,
1267 /// symbols are also treated like a constant, i.e., an affine function of the
1268 /// symbols is also treated like a constant. Returns -1 if such an equality
1269 /// could not be found.
1270 static int findEqualityToConstant(const IntegerRelation &cst, unsigned pos,
1271                                   bool symbolic = false) {
1272   assert(pos < cst.getNumIds() && "invalid position");
1273   for (unsigned r = 0, e = cst.getNumEqualities(); r < e; r++) {
1274     int64_t v = cst.atEq(r, pos);
1275     if (v * v != 1)
1276       continue;
1277     unsigned c;
1278     unsigned f = symbolic ? cst.getNumDimIds() : cst.getNumIds();
1279     // This checks for zeros in all positions other than 'pos' in [0, f)
1280     for (c = 0; c < f; c++) {
1281       if (c == pos)
1282         continue;
1283       if (cst.atEq(r, c) != 0) {
1284         // Dependent on another identifier.
1285         break;
1286       }
1287     }
1288     if (c == f)
1289       // Equality is free of other identifiers.
1290       return r;
1291   }
1292   return -1;
1293 }
1294 
1295 LogicalResult IntegerRelation::constantFoldId(unsigned pos) {
1296   assert(pos < getNumIds() && "invalid position");
1297   int rowIdx;
1298   if ((rowIdx = findEqualityToConstant(*this, pos)) == -1)
1299     return failure();
1300 
1301   // atEq(rowIdx, pos) is either -1 or 1.
1302   assert(atEq(rowIdx, pos) * atEq(rowIdx, pos) == 1);
1303   int64_t constVal = -atEq(rowIdx, getNumCols() - 1) / atEq(rowIdx, pos);
1304   setAndEliminate(pos, constVal);
1305   return success();
1306 }
1307 
1308 void IntegerRelation::constantFoldIdRange(unsigned pos, unsigned num) {
1309   for (unsigned s = pos, t = pos, e = pos + num; s < e; s++) {
1310     if (failed(constantFoldId(t)))
1311       t++;
1312   }
1313 }
1314 
1315 /// Returns a non-negative constant bound on the extent (upper bound - lower
1316 /// bound) of the specified identifier if it is found to be a constant; returns
1317 /// None if it's not a constant. This methods treats symbolic identifiers
1318 /// specially, i.e., it looks for constant differences between affine
1319 /// expressions involving only the symbolic identifiers. See comments at
1320 /// function definition for example. 'lb', if provided, is set to the lower
1321 /// bound associated with the constant difference. Note that 'lb' is purely
1322 /// symbolic and thus will contain the coefficients of the symbolic identifiers
1323 /// and the constant coefficient.
1324 //  Egs: 0 <= i <= 15, return 16.
1325 //       s0 + 2 <= i <= s0 + 17, returns 16. (s0 has to be a symbol)
1326 //       s0 + s1 + 16 <= d0 <= s0 + s1 + 31, returns 16.
1327 //       s0 - 7 <= 8*j <= s0 returns 1 with lb = s0, lbDivisor = 8 (since lb =
1328 //       ceil(s0 - 7 / 8) = floor(s0 / 8)).
1329 Optional<int64_t> IntegerRelation::getConstantBoundOnDimSize(
1330     unsigned pos, SmallVectorImpl<int64_t> *lb, int64_t *boundFloorDivisor,
1331     SmallVectorImpl<int64_t> *ub, unsigned *minLbPos,
1332     unsigned *minUbPos) const {
1333   assert(pos < getNumDimIds() && "Invalid identifier position");
1334 
1335   // Find an equality for 'pos'^th identifier that equates it to some function
1336   // of the symbolic identifiers (+ constant).
1337   int eqPos = findEqualityToConstant(*this, pos, /*symbolic=*/true);
1338   if (eqPos != -1) {
1339     auto eq = getEquality(eqPos);
1340     // If the equality involves a local var, punt for now.
1341     // TODO: this can be handled in the future by using the explicit
1342     // representation of the local vars.
1343     if (!std::all_of(eq.begin() + getNumDimAndSymbolIds(), eq.end() - 1,
1344                      [](int64_t coeff) { return coeff == 0; }))
1345       return None;
1346 
1347     // This identifier can only take a single value.
1348     if (lb) {
1349       // Set lb to that symbolic value.
1350       lb->resize(getNumSymbolIds() + 1);
1351       if (ub)
1352         ub->resize(getNumSymbolIds() + 1);
1353       for (unsigned c = 0, f = getNumSymbolIds() + 1; c < f; c++) {
1354         int64_t v = atEq(eqPos, pos);
1355         // atEq(eqRow, pos) is either -1 or 1.
1356         assert(v * v == 1);
1357         (*lb)[c] = v < 0 ? atEq(eqPos, getNumDimIds() + c) / -v
1358                          : -atEq(eqPos, getNumDimIds() + c) / v;
1359         // Since this is an equality, ub = lb.
1360         if (ub)
1361           (*ub)[c] = (*lb)[c];
1362       }
1363       assert(boundFloorDivisor &&
1364              "both lb and divisor or none should be provided");
1365       *boundFloorDivisor = 1;
1366     }
1367     if (minLbPos)
1368       *minLbPos = eqPos;
1369     if (minUbPos)
1370       *minUbPos = eqPos;
1371     return 1;
1372   }
1373 
1374   // Check if the identifier appears at all in any of the inequalities.
1375   unsigned r, e;
1376   for (r = 0, e = getNumInequalities(); r < e; r++) {
1377     if (atIneq(r, pos) != 0)
1378       break;
1379   }
1380   if (r == e)
1381     // If it doesn't, there isn't a bound on it.
1382     return None;
1383 
1384   // Positions of constraints that are lower/upper bounds on the variable.
1385   SmallVector<unsigned, 4> lbIndices, ubIndices;
1386 
1387   // Gather all symbolic lower bounds and upper bounds of the variable, i.e.,
1388   // the bounds can only involve symbolic (and local) identifiers. Since the
1389   // canonical form c_1*x_1 + c_2*x_2 + ... + c_0 >= 0, a constraint is a lower
1390   // bound for x_i if c_i >= 1, and an upper bound if c_i <= -1.
1391   getLowerAndUpperBoundIndices(pos, &lbIndices, &ubIndices,
1392                                /*eqIndices=*/nullptr, /*offset=*/0,
1393                                /*num=*/getNumDimIds());
1394 
1395   Optional<int64_t> minDiff = None;
1396   unsigned minLbPosition = 0, minUbPosition = 0;
1397   for (auto ubPos : ubIndices) {
1398     for (auto lbPos : lbIndices) {
1399       // Look for a lower bound and an upper bound that only differ by a
1400       // constant, i.e., pairs of the form  0 <= c_pos - f(c_i's) <= diffConst.
1401       // For example, if ii is the pos^th variable, we are looking for
1402       // constraints like ii >= i, ii <= ii + 50, 50 being the difference. The
1403       // minimum among all such constant differences is kept since that's the
1404       // constant bounding the extent of the pos^th variable.
1405       unsigned j, e;
1406       for (j = 0, e = getNumCols() - 1; j < e; j++)
1407         if (atIneq(ubPos, j) != -atIneq(lbPos, j)) {
1408           break;
1409         }
1410       if (j < getNumCols() - 1)
1411         continue;
1412       int64_t diff = ceilDiv(atIneq(ubPos, getNumCols() - 1) +
1413                                  atIneq(lbPos, getNumCols() - 1) + 1,
1414                              atIneq(lbPos, pos));
1415       // This bound is non-negative by definition.
1416       diff = std::max<int64_t>(diff, 0);
1417       if (minDiff == None || diff < minDiff) {
1418         minDiff = diff;
1419         minLbPosition = lbPos;
1420         minUbPosition = ubPos;
1421       }
1422     }
1423   }
1424   if (lb && minDiff) {
1425     // Set lb to the symbolic lower bound.
1426     lb->resize(getNumSymbolIds() + 1);
1427     if (ub)
1428       ub->resize(getNumSymbolIds() + 1);
1429     // The lower bound is the ceildiv of the lb constraint over the coefficient
1430     // of the variable at 'pos'. We express the ceildiv equivalently as a floor
1431     // for uniformity. For eg., if the lower bound constraint was: 32*d0 - N +
1432     // 31 >= 0, the lower bound for d0 is ceil(N - 31, 32), i.e., floor(N, 32).
1433     *boundFloorDivisor = atIneq(minLbPosition, pos);
1434     assert(*boundFloorDivisor == -atIneq(minUbPosition, pos));
1435     for (unsigned c = 0, e = getNumSymbolIds() + 1; c < e; c++) {
1436       (*lb)[c] = -atIneq(minLbPosition, getNumDimIds() + c);
1437     }
1438     if (ub) {
1439       for (unsigned c = 0, e = getNumSymbolIds() + 1; c < e; c++)
1440         (*ub)[c] = atIneq(minUbPosition, getNumDimIds() + c);
1441     }
1442     // The lower bound leads to a ceildiv while the upper bound is a floordiv
1443     // whenever the coefficient at pos != 1. ceildiv (val / d) = floordiv (val +
1444     // d - 1 / d); hence, the addition of 'atIneq(minLbPosition, pos) - 1' to
1445     // the constant term for the lower bound.
1446     (*lb)[getNumSymbolIds()] += atIneq(minLbPosition, pos) - 1;
1447   }
1448   if (minLbPos)
1449     *minLbPos = minLbPosition;
1450   if (minUbPos)
1451     *minUbPos = minUbPosition;
1452   return minDiff;
1453 }
1454 
1455 template <bool isLower>
1456 Optional<int64_t>
1457 IntegerRelation::computeConstantLowerOrUpperBound(unsigned pos) {
1458   assert(pos < getNumIds() && "invalid position");
1459   // Project to 'pos'.
1460   projectOut(0, pos);
1461   projectOut(1, getNumIds() - 1);
1462   // Check if there's an equality equating the '0'^th identifier to a constant.
1463   int eqRowIdx = findEqualityToConstant(*this, 0, /*symbolic=*/false);
1464   if (eqRowIdx != -1)
1465     // atEq(rowIdx, 0) is either -1 or 1.
1466     return -atEq(eqRowIdx, getNumCols() - 1) / atEq(eqRowIdx, 0);
1467 
1468   // Check if the identifier appears at all in any of the inequalities.
1469   unsigned r, e;
1470   for (r = 0, e = getNumInequalities(); r < e; r++) {
1471     if (atIneq(r, 0) != 0)
1472       break;
1473   }
1474   if (r == e)
1475     // If it doesn't, there isn't a bound on it.
1476     return None;
1477 
1478   Optional<int64_t> minOrMaxConst = None;
1479 
1480   // Take the max across all const lower bounds (or min across all constant
1481   // upper bounds).
1482   for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
1483     if (isLower) {
1484       if (atIneq(r, 0) <= 0)
1485         // Not a lower bound.
1486         continue;
1487     } else if (atIneq(r, 0) >= 0) {
1488       // Not an upper bound.
1489       continue;
1490     }
1491     unsigned c, f;
1492     for (c = 0, f = getNumCols() - 1; c < f; c++)
1493       if (c != 0 && atIneq(r, c) != 0)
1494         break;
1495     if (c < getNumCols() - 1)
1496       // Not a constant bound.
1497       continue;
1498 
1499     int64_t boundConst =
1500         isLower ? mlir::ceilDiv(-atIneq(r, getNumCols() - 1), atIneq(r, 0))
1501                 : mlir::floorDiv(atIneq(r, getNumCols() - 1), -atIneq(r, 0));
1502     if (isLower) {
1503       if (minOrMaxConst == None || boundConst > minOrMaxConst)
1504         minOrMaxConst = boundConst;
1505     } else {
1506       if (minOrMaxConst == None || boundConst < minOrMaxConst)
1507         minOrMaxConst = boundConst;
1508     }
1509   }
1510   return minOrMaxConst;
1511 }
1512 
1513 Optional<int64_t> IntegerRelation::getConstantBound(BoundType type,
1514                                                     unsigned pos) const {
1515   if (type == BoundType::LB)
1516     return IntegerRelation(*this)
1517         .computeConstantLowerOrUpperBound</*isLower=*/true>(pos);
1518   if (type == BoundType::UB)
1519     return IntegerRelation(*this)
1520         .computeConstantLowerOrUpperBound</*isLower=*/false>(pos);
1521 
1522   assert(type == BoundType::EQ && "expected EQ");
1523   Optional<int64_t> lb =
1524       IntegerRelation(*this).computeConstantLowerOrUpperBound</*isLower=*/true>(
1525           pos);
1526   Optional<int64_t> ub =
1527       IntegerRelation(*this)
1528           .computeConstantLowerOrUpperBound</*isLower=*/false>(pos);
1529   return (lb && ub && *lb == *ub) ? Optional<int64_t>(*ub) : None;
1530 }
1531 
1532 // A simple (naive and conservative) check for hyper-rectangularity.
1533 bool IntegerRelation::isHyperRectangular(unsigned pos, unsigned num) const {
1534   assert(pos < getNumCols() - 1);
1535   // Check for two non-zero coefficients in the range [pos, pos + sum).
1536   for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
1537     unsigned sum = 0;
1538     for (unsigned c = pos; c < pos + num; c++) {
1539       if (atIneq(r, c) != 0)
1540         sum++;
1541     }
1542     if (sum > 1)
1543       return false;
1544   }
1545   for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
1546     unsigned sum = 0;
1547     for (unsigned c = pos; c < pos + num; c++) {
1548       if (atEq(r, c) != 0)
1549         sum++;
1550     }
1551     if (sum > 1)
1552       return false;
1553   }
1554   return true;
1555 }
1556 
1557 /// Removes duplicate constraints, trivially true constraints, and constraints
1558 /// that can be detected as redundant as a result of differing only in their
1559 /// constant term part. A constraint of the form <non-negative constant> >= 0 is
1560 /// considered trivially true.
1561 //  Uses a DenseSet to hash and detect duplicates followed by a linear scan to
1562 //  remove duplicates in place.
1563 void IntegerRelation::removeTrivialRedundancy() {
1564   gcdTightenInequalities();
1565   normalizeConstraintsByGCD();
1566 
1567   // A map used to detect redundancy stemming from constraints that only differ
1568   // in their constant term. The value stored is <row position, const term>
1569   // for a given row.
1570   SmallDenseMap<ArrayRef<int64_t>, std::pair<unsigned, int64_t>>
1571       rowsWithoutConstTerm;
1572   // To unique rows.
1573   SmallDenseSet<ArrayRef<int64_t>, 8> rowSet;
1574 
1575   // Check if constraint is of the form <non-negative-constant> >= 0.
1576   auto isTriviallyValid = [&](unsigned r) -> bool {
1577     for (unsigned c = 0, e = getNumCols() - 1; c < e; c++) {
1578       if (atIneq(r, c) != 0)
1579         return false;
1580     }
1581     return atIneq(r, getNumCols() - 1) >= 0;
1582   };
1583 
1584   // Detect and mark redundant constraints.
1585   SmallVector<bool, 256> redunIneq(getNumInequalities(), false);
1586   for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
1587     int64_t *rowStart = &inequalities(r, 0);
1588     auto row = ArrayRef<int64_t>(rowStart, getNumCols());
1589     if (isTriviallyValid(r) || !rowSet.insert(row).second) {
1590       redunIneq[r] = true;
1591       continue;
1592     }
1593 
1594     // Among constraints that only differ in the constant term part, mark
1595     // everything other than the one with the smallest constant term redundant.
1596     // (eg: among i - 16j - 5 >= 0, i - 16j - 1 >=0, i - 16j - 7 >= 0, the
1597     // former two are redundant).
1598     int64_t constTerm = atIneq(r, getNumCols() - 1);
1599     auto rowWithoutConstTerm = ArrayRef<int64_t>(rowStart, getNumCols() - 1);
1600     const auto &ret =
1601         rowsWithoutConstTerm.insert({rowWithoutConstTerm, {r, constTerm}});
1602     if (!ret.second) {
1603       // Check if the other constraint has a higher constant term.
1604       auto &val = ret.first->second;
1605       if (val.second > constTerm) {
1606         // The stored row is redundant. Mark it so, and update with this one.
1607         redunIneq[val.first] = true;
1608         val = {r, constTerm};
1609       } else {
1610         // The one stored makes this one redundant.
1611         redunIneq[r] = true;
1612       }
1613     }
1614   }
1615 
1616   // Scan to get rid of all rows marked redundant, in-place.
1617   unsigned pos = 0;
1618   for (unsigned r = 0, e = getNumInequalities(); r < e; r++)
1619     if (!redunIneq[r])
1620       inequalities.copyRow(r, pos++);
1621 
1622   inequalities.resizeVertically(pos);
1623 
1624   // TODO: consider doing this for equalities as well, but probably not worth
1625   // the savings.
1626 }
1627 
1628 #undef DEBUG_TYPE
1629 #define DEBUG_TYPE "fm"
1630 
1631 /// Eliminates identifier at the specified position using Fourier-Motzkin
1632 /// variable elimination. This technique is exact for rational spaces but
1633 /// conservative (in "rare" cases) for integer spaces. The operation corresponds
1634 /// to a projection operation yielding the (convex) set of integer points
1635 /// contained in the rational shadow of the set. An emptiness test that relies
1636 /// on this method will guarantee emptiness, i.e., it disproves the existence of
1637 /// a solution if it says it's empty.
1638 /// If a non-null isResultIntegerExact is passed, it is set to true if the
1639 /// result is also integer exact. If it's set to false, the obtained solution
1640 /// *may* not be exact, i.e., it may contain integer points that do not have an
1641 /// integer pre-image in the original set.
1642 ///
1643 /// Eg:
1644 /// j >= 0, j <= i + 1
1645 /// i >= 0, i <= N + 1
1646 /// Eliminating i yields,
1647 ///   j >= 0, 0 <= N + 1, j - 1 <= N + 1
1648 ///
1649 /// If darkShadow = true, this method computes the dark shadow on elimination;
1650 /// the dark shadow is a convex integer subset of the exact integer shadow. A
1651 /// non-empty dark shadow proves the existence of an integer solution. The
1652 /// elimination in such a case could however be an under-approximation, and thus
1653 /// should not be used for scanning sets or used by itself for dependence
1654 /// checking.
1655 ///
1656 /// Eg: 2-d set, * represents grid points, 'o' represents a point in the set.
1657 ///            ^
1658 ///            |
1659 ///            | * * * * o o
1660 ///         i  | * * o o o o
1661 ///            | o * * * * *
1662 ///            --------------->
1663 ///                 j ->
1664 ///
1665 /// Eliminating i from this system (projecting on the j dimension):
1666 /// rational shadow / integer light shadow:  1 <= j <= 6
1667 /// dark shadow:                             3 <= j <= 6
1668 /// exact integer shadow:                    j = 1 \union  3 <= j <= 6
1669 /// holes/splinters:                         j = 2
1670 ///
1671 /// darkShadow = false, isResultIntegerExact = nullptr are default values.
1672 // TODO: a slight modification to yield dark shadow version of FM (tightened),
1673 // which can prove the existence of a solution if there is one.
1674 void IntegerRelation::fourierMotzkinEliminate(unsigned pos, bool darkShadow,
1675                                               bool *isResultIntegerExact) {
1676   LLVM_DEBUG(llvm::dbgs() << "FM input (eliminate pos " << pos << "):\n");
1677   LLVM_DEBUG(dump());
1678   assert(pos < getNumIds() && "invalid position");
1679   assert(hasConsistentState());
1680 
1681   // Check if this identifier can be eliminated through a substitution.
1682   for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
1683     if (atEq(r, pos) != 0) {
1684       // Use Gaussian elimination here (since we have an equality).
1685       LogicalResult ret = gaussianEliminateId(pos);
1686       (void)ret;
1687       assert(succeeded(ret) && "Gaussian elimination guaranteed to succeed");
1688       LLVM_DEBUG(llvm::dbgs() << "FM output (through Gaussian elimination):\n");
1689       LLVM_DEBUG(dump());
1690       return;
1691     }
1692   }
1693 
1694   // A fast linear time tightening.
1695   gcdTightenInequalities();
1696 
1697   // Check if the identifier appears at all in any of the inequalities.
1698   if (isColZero(pos)) {
1699     // If it doesn't appear, just remove the column and return.
1700     // TODO: refactor removeColumns to use it from here.
1701     removeId(pos);
1702     LLVM_DEBUG(llvm::dbgs() << "FM output:\n");
1703     LLVM_DEBUG(dump());
1704     return;
1705   }
1706 
1707   // Positions of constraints that are lower bounds on the variable.
1708   SmallVector<unsigned, 4> lbIndices;
1709   // Positions of constraints that are lower bounds on the variable.
1710   SmallVector<unsigned, 4> ubIndices;
1711   // Positions of constraints that do not involve the variable.
1712   std::vector<unsigned> nbIndices;
1713   nbIndices.reserve(getNumInequalities());
1714 
1715   // Gather all lower bounds and upper bounds of the variable. Since the
1716   // canonical form c_1*x_1 + c_2*x_2 + ... + c_0 >= 0, a constraint is a lower
1717   // bound for x_i if c_i >= 1, and an upper bound if c_i <= -1.
1718   for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
1719     if (atIneq(r, pos) == 0) {
1720       // Id does not appear in bound.
1721       nbIndices.push_back(r);
1722     } else if (atIneq(r, pos) >= 1) {
1723       // Lower bound.
1724       lbIndices.push_back(r);
1725     } else {
1726       // Upper bound.
1727       ubIndices.push_back(r);
1728     }
1729   }
1730 
1731   PresburgerSpace newSpace = getSpace();
1732   IdKind idKindRemove = newSpace.getIdKindAt(pos);
1733   unsigned relativePos = pos - newSpace.getIdKindOffset(idKindRemove);
1734   newSpace.removeIdRange(idKindRemove, relativePos, relativePos + 1);
1735 
1736   /// Create the new system which has one identifier less.
1737   IntegerRelation newRel(lbIndices.size() * ubIndices.size() + nbIndices.size(),
1738                          getNumEqualities(), getNumCols() - 1, newSpace);
1739 
1740   // This will be used to check if the elimination was integer exact.
1741   unsigned lcmProducts = 1;
1742 
1743   // Let x be the variable we are eliminating.
1744   // For each lower bound, lb <= c_l*x, and each upper bound c_u*x <= ub, (note
1745   // that c_l, c_u >= 1) we have:
1746   // lb*lcm(c_l, c_u)/c_l <= lcm(c_l, c_u)*x <= ub*lcm(c_l, c_u)/c_u
1747   // We thus generate a constraint:
1748   // lcm(c_l, c_u)/c_l*lb <= lcm(c_l, c_u)/c_u*ub.
1749   // Note if c_l = c_u = 1, all integer points captured by the resulting
1750   // constraint correspond to integer points in the original system (i.e., they
1751   // have integer pre-images). Hence, if the lcm's are all 1, the elimination is
1752   // integer exact.
1753   for (auto ubPos : ubIndices) {
1754     for (auto lbPos : lbIndices) {
1755       SmallVector<int64_t, 4> ineq;
1756       ineq.reserve(newRel.getNumCols());
1757       int64_t lbCoeff = atIneq(lbPos, pos);
1758       // Note that in the comments above, ubCoeff is the negation of the
1759       // coefficient in the canonical form as the view taken here is that of the
1760       // term being moved to the other size of '>='.
1761       int64_t ubCoeff = -atIneq(ubPos, pos);
1762       // TODO: refactor this loop to avoid all branches inside.
1763       for (unsigned l = 0, e = getNumCols(); l < e; l++) {
1764         if (l == pos)
1765           continue;
1766         assert(lbCoeff >= 1 && ubCoeff >= 1 && "bounds wrongly identified");
1767         int64_t lcm = mlir::lcm(lbCoeff, ubCoeff);
1768         ineq.push_back(atIneq(ubPos, l) * (lcm / ubCoeff) +
1769                        atIneq(lbPos, l) * (lcm / lbCoeff));
1770         lcmProducts *= lcm;
1771       }
1772       if (darkShadow) {
1773         // The dark shadow is a convex subset of the exact integer shadow. If
1774         // there is a point here, it proves the existence of a solution.
1775         ineq[ineq.size() - 1] += lbCoeff * ubCoeff - lbCoeff - ubCoeff + 1;
1776       }
1777       // TODO: we need to have a way to add inequalities in-place in
1778       // IntegerRelation instead of creating and copying over.
1779       newRel.addInequality(ineq);
1780     }
1781   }
1782 
1783   LLVM_DEBUG(llvm::dbgs() << "FM isResultIntegerExact: " << (lcmProducts == 1)
1784                           << "\n");
1785   if (lcmProducts == 1 && isResultIntegerExact)
1786     *isResultIntegerExact = true;
1787 
1788   // Copy over the constraints not involving this variable.
1789   for (auto nbPos : nbIndices) {
1790     SmallVector<int64_t, 4> ineq;
1791     ineq.reserve(getNumCols() - 1);
1792     for (unsigned l = 0, e = getNumCols(); l < e; l++) {
1793       if (l == pos)
1794         continue;
1795       ineq.push_back(atIneq(nbPos, l));
1796     }
1797     newRel.addInequality(ineq);
1798   }
1799 
1800   assert(newRel.getNumConstraints() ==
1801          lbIndices.size() * ubIndices.size() + nbIndices.size());
1802 
1803   // Copy over the equalities.
1804   for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
1805     SmallVector<int64_t, 4> eq;
1806     eq.reserve(newRel.getNumCols());
1807     for (unsigned l = 0, e = getNumCols(); l < e; l++) {
1808       if (l == pos)
1809         continue;
1810       eq.push_back(atEq(r, l));
1811     }
1812     newRel.addEquality(eq);
1813   }
1814 
1815   // GCD tightening and normalization allows detection of more trivially
1816   // redundant constraints.
1817   newRel.gcdTightenInequalities();
1818   newRel.normalizeConstraintsByGCD();
1819   newRel.removeTrivialRedundancy();
1820   clearAndCopyFrom(newRel);
1821   LLVM_DEBUG(llvm::dbgs() << "FM output:\n");
1822   LLVM_DEBUG(dump());
1823 }
1824 
1825 #undef DEBUG_TYPE
1826 #define DEBUG_TYPE "presburger"
1827 
1828 void IntegerRelation::projectOut(unsigned pos, unsigned num) {
1829   if (num == 0)
1830     return;
1831 
1832   // 'pos' can be at most getNumCols() - 2 if num > 0.
1833   assert((getNumCols() < 2 || pos <= getNumCols() - 2) && "invalid position");
1834   assert(pos + num < getNumCols() && "invalid range");
1835 
1836   // Eliminate as many identifiers as possible using Gaussian elimination.
1837   unsigned currentPos = pos;
1838   unsigned numToEliminate = num;
1839   unsigned numGaussianEliminated = 0;
1840 
1841   while (currentPos < getNumIds()) {
1842     unsigned curNumEliminated =
1843         gaussianEliminateIds(currentPos, currentPos + numToEliminate);
1844     ++currentPos;
1845     numToEliminate -= curNumEliminated + 1;
1846     numGaussianEliminated += curNumEliminated;
1847   }
1848 
1849   // Eliminate the remaining using Fourier-Motzkin.
1850   for (unsigned i = 0; i < num - numGaussianEliminated; i++) {
1851     unsigned numToEliminate = num - numGaussianEliminated - i;
1852     fourierMotzkinEliminate(
1853         getBestIdToEliminate(*this, pos, pos + numToEliminate));
1854   }
1855 
1856   // Fast/trivial simplifications.
1857   gcdTightenInequalities();
1858   // Normalize constraints after tightening since the latter impacts this, but
1859   // not the other way round.
1860   normalizeConstraintsByGCD();
1861 }
1862 
1863 namespace {
1864 
1865 enum BoundCmpResult { Greater, Less, Equal, Unknown };
1866 
1867 /// Compares two affine bounds whose coefficients are provided in 'first' and
1868 /// 'second'. The last coefficient is the constant term.
1869 static BoundCmpResult compareBounds(ArrayRef<int64_t> a, ArrayRef<int64_t> b) {
1870   assert(a.size() == b.size());
1871 
1872   // For the bounds to be comparable, their corresponding identifier
1873   // coefficients should be equal; the constant terms are then compared to
1874   // determine less/greater/equal.
1875 
1876   if (!std::equal(a.begin(), a.end() - 1, b.begin()))
1877     return Unknown;
1878 
1879   if (a.back() == b.back())
1880     return Equal;
1881 
1882   return a.back() < b.back() ? Less : Greater;
1883 }
1884 } // namespace
1885 
1886 // Returns constraints that are common to both A & B.
1887 static void getCommonConstraints(const IntegerRelation &a,
1888                                  const IntegerRelation &b, IntegerRelation &c) {
1889   c = IntegerRelation(a.getSpace());
1890   // a naive O(n^2) check should be enough here given the input sizes.
1891   for (unsigned r = 0, e = a.getNumInequalities(); r < e; ++r) {
1892     for (unsigned s = 0, f = b.getNumInequalities(); s < f; ++s) {
1893       if (a.getInequality(r) == b.getInequality(s)) {
1894         c.addInequality(a.getInequality(r));
1895         break;
1896       }
1897     }
1898   }
1899   for (unsigned r = 0, e = a.getNumEqualities(); r < e; ++r) {
1900     for (unsigned s = 0, f = b.getNumEqualities(); s < f; ++s) {
1901       if (a.getEquality(r) == b.getEquality(s)) {
1902         c.addEquality(a.getEquality(r));
1903         break;
1904       }
1905     }
1906   }
1907 }
1908 
1909 // Computes the bounding box with respect to 'other' by finding the min of the
1910 // lower bounds and the max of the upper bounds along each of the dimensions.
1911 LogicalResult
1912 IntegerRelation::unionBoundingBox(const IntegerRelation &otherCst) {
1913   assert(space.isEqual(otherCst.getSpace()) && "Spaces should match.");
1914   assert(getNumLocalIds() == 0 && "local ids not supported yet here");
1915 
1916   // Get the constraints common to both systems; these will be added as is to
1917   // the union.
1918   IntegerRelation commonCst(PresburgerSpace::getRelationSpace());
1919   getCommonConstraints(*this, otherCst, commonCst);
1920 
1921   std::vector<SmallVector<int64_t, 8>> boundingLbs;
1922   std::vector<SmallVector<int64_t, 8>> boundingUbs;
1923   boundingLbs.reserve(2 * getNumDimIds());
1924   boundingUbs.reserve(2 * getNumDimIds());
1925 
1926   // To hold lower and upper bounds for each dimension.
1927   SmallVector<int64_t, 4> lb, otherLb, ub, otherUb;
1928   // To compute min of lower bounds and max of upper bounds for each dimension.
1929   SmallVector<int64_t, 4> minLb(getNumSymbolIds() + 1);
1930   SmallVector<int64_t, 4> maxUb(getNumSymbolIds() + 1);
1931   // To compute final new lower and upper bounds for the union.
1932   SmallVector<int64_t, 8> newLb(getNumCols()), newUb(getNumCols());
1933 
1934   int64_t lbFloorDivisor, otherLbFloorDivisor;
1935   for (unsigned d = 0, e = getNumDimIds(); d < e; ++d) {
1936     auto extent = getConstantBoundOnDimSize(d, &lb, &lbFloorDivisor, &ub);
1937     if (!extent.hasValue())
1938       // TODO: symbolic extents when necessary.
1939       // TODO: handle union if a dimension is unbounded.
1940       return failure();
1941 
1942     auto otherExtent = otherCst.getConstantBoundOnDimSize(
1943         d, &otherLb, &otherLbFloorDivisor, &otherUb);
1944     if (!otherExtent.hasValue() || lbFloorDivisor != otherLbFloorDivisor)
1945       // TODO: symbolic extents when necessary.
1946       return failure();
1947 
1948     assert(lbFloorDivisor > 0 && "divisor always expected to be positive");
1949 
1950     auto res = compareBounds(lb, otherLb);
1951     // Identify min.
1952     if (res == BoundCmpResult::Less || res == BoundCmpResult::Equal) {
1953       minLb = lb;
1954       // Since the divisor is for a floordiv, we need to convert to ceildiv,
1955       // i.e., i >= expr floordiv div <=> i >= (expr - div + 1) ceildiv div <=>
1956       // div * i >= expr - div + 1.
1957       minLb.back() -= lbFloorDivisor - 1;
1958     } else if (res == BoundCmpResult::Greater) {
1959       minLb = otherLb;
1960       minLb.back() -= otherLbFloorDivisor - 1;
1961     } else {
1962       // Uncomparable - check for constant lower/upper bounds.
1963       auto constLb = getConstantBound(BoundType::LB, d);
1964       auto constOtherLb = otherCst.getConstantBound(BoundType::LB, d);
1965       if (!constLb.hasValue() || !constOtherLb.hasValue())
1966         return failure();
1967       std::fill(minLb.begin(), minLb.end(), 0);
1968       minLb.back() = std::min(constLb.getValue(), constOtherLb.getValue());
1969     }
1970 
1971     // Do the same for ub's but max of upper bounds. Identify max.
1972     auto uRes = compareBounds(ub, otherUb);
1973     if (uRes == BoundCmpResult::Greater || uRes == BoundCmpResult::Equal) {
1974       maxUb = ub;
1975     } else if (uRes == BoundCmpResult::Less) {
1976       maxUb = otherUb;
1977     } else {
1978       // Uncomparable - check for constant lower/upper bounds.
1979       auto constUb = getConstantBound(BoundType::UB, d);
1980       auto constOtherUb = otherCst.getConstantBound(BoundType::UB, d);
1981       if (!constUb.hasValue() || !constOtherUb.hasValue())
1982         return failure();
1983       std::fill(maxUb.begin(), maxUb.end(), 0);
1984       maxUb.back() = std::max(constUb.getValue(), constOtherUb.getValue());
1985     }
1986 
1987     std::fill(newLb.begin(), newLb.end(), 0);
1988     std::fill(newUb.begin(), newUb.end(), 0);
1989 
1990     // The divisor for lb, ub, otherLb, otherUb at this point is lbDivisor,
1991     // and so it's the divisor for newLb and newUb as well.
1992     newLb[d] = lbFloorDivisor;
1993     newUb[d] = -lbFloorDivisor;
1994     // Copy over the symbolic part + constant term.
1995     std::copy(minLb.begin(), minLb.end(), newLb.begin() + getNumDimIds());
1996     std::transform(newLb.begin() + getNumDimIds(), newLb.end(),
1997                    newLb.begin() + getNumDimIds(), std::negate<int64_t>());
1998     std::copy(maxUb.begin(), maxUb.end(), newUb.begin() + getNumDimIds());
1999 
2000     boundingLbs.push_back(newLb);
2001     boundingUbs.push_back(newUb);
2002   }
2003 
2004   // Clear all constraints and add the lower/upper bounds for the bounding box.
2005   clearConstraints();
2006   for (unsigned d = 0, e = getNumDimIds(); d < e; ++d) {
2007     addInequality(boundingLbs[d]);
2008     addInequality(boundingUbs[d]);
2009   }
2010 
2011   // Add the constraints that were common to both systems.
2012   append(commonCst);
2013   removeTrivialRedundancy();
2014 
2015   // TODO: copy over pure symbolic constraints from this and 'other' over to the
2016   // union (since the above are just the union along dimensions); we shouldn't
2017   // be discarding any other constraints on the symbols.
2018 
2019   return success();
2020 }
2021 
2022 bool IntegerRelation::isColZero(unsigned pos) const {
2023   unsigned rowPos;
2024   return !findConstraintWithNonZeroAt(pos, /*isEq=*/false, &rowPos) &&
2025          !findConstraintWithNonZeroAt(pos, /*isEq=*/true, &rowPos);
2026 }
2027 
2028 /// Find positions of inequalities and equalities that do not have a coefficient
2029 /// for [pos, pos + num) identifiers.
2030 static void getIndependentConstraints(const IntegerRelation &cst, unsigned pos,
2031                                       unsigned num,
2032                                       SmallVectorImpl<unsigned> &nbIneqIndices,
2033                                       SmallVectorImpl<unsigned> &nbEqIndices) {
2034   assert(pos < cst.getNumIds() && "invalid start position");
2035   assert(pos + num <= cst.getNumIds() && "invalid limit");
2036 
2037   for (unsigned r = 0, e = cst.getNumInequalities(); r < e; r++) {
2038     // The bounds are to be independent of [offset, offset + num) columns.
2039     unsigned c;
2040     for (c = pos; c < pos + num; ++c) {
2041       if (cst.atIneq(r, c) != 0)
2042         break;
2043     }
2044     if (c == pos + num)
2045       nbIneqIndices.push_back(r);
2046   }
2047 
2048   for (unsigned r = 0, e = cst.getNumEqualities(); r < e; r++) {
2049     // The bounds are to be independent of [offset, offset + num) columns.
2050     unsigned c;
2051     for (c = pos; c < pos + num; ++c) {
2052       if (cst.atEq(r, c) != 0)
2053         break;
2054     }
2055     if (c == pos + num)
2056       nbEqIndices.push_back(r);
2057   }
2058 }
2059 
2060 void IntegerRelation::removeIndependentConstraints(unsigned pos, unsigned num) {
2061   assert(pos + num <= getNumIds() && "invalid range");
2062 
2063   // Remove constraints that are independent of these identifiers.
2064   SmallVector<unsigned, 4> nbIneqIndices, nbEqIndices;
2065   getIndependentConstraints(*this, /*pos=*/0, num, nbIneqIndices, nbEqIndices);
2066 
2067   // Iterate in reverse so that indices don't have to be updated.
2068   // TODO: This method can be made more efficient (because removal of each
2069   // inequality leads to much shifting/copying in the underlying buffer).
2070   for (auto nbIndex : llvm::reverse(nbIneqIndices))
2071     removeInequality(nbIndex);
2072   for (auto nbIndex : llvm::reverse(nbEqIndices))
2073     removeEquality(nbIndex);
2074 }
2075 
2076 IntegerPolyhedron IntegerRelation::getDomainSet() const {
2077   IntegerRelation copyRel = *this;
2078 
2079   // Convert Range variables to Local variables.
2080   copyRel.convertIdKind(IdKind::Range, 0, getNumIdKind(IdKind::Range),
2081                         IdKind::Local);
2082 
2083   // Convert Domain variables to SetDim(Range) variables.
2084   copyRel.convertIdKind(IdKind::Domain, 0, getNumIdKind(IdKind::Domain),
2085                         IdKind::SetDim);
2086 
2087   return IntegerPolyhedron(std::move(copyRel));
2088 }
2089 
2090 IntegerPolyhedron IntegerRelation::getRangeSet() const {
2091   IntegerRelation copyRel = *this;
2092 
2093   // Convert Domain variables to Local variables.
2094   copyRel.convertIdKind(IdKind::Domain, 0, getNumIdKind(IdKind::Domain),
2095                         IdKind::Local);
2096 
2097   // We do not need to do anything to Range variables since they are already in
2098   // SetDim position.
2099 
2100   return IntegerPolyhedron(std::move(copyRel));
2101 }
2102 
2103 void IntegerRelation::intersectDomain(const IntegerPolyhedron &poly) {
2104   assert(getDomainSet().getSpace().isCompatible(poly.getSpace()) &&
2105          "Domain set is not compatible with poly");
2106 
2107   // Treating the poly as a relation, convert it from `0 -> R` to `R -> 0`.
2108   IntegerRelation rel = poly;
2109   rel.inverse();
2110 
2111   // Append dummy range variables to make the spaces compatible.
2112   rel.appendId(IdKind::Range, getNumRangeIds());
2113 
2114   // Intersect in place.
2115   mergeLocalIds(rel);
2116   append(rel);
2117 }
2118 
2119 void IntegerRelation::intersectRange(const IntegerPolyhedron &poly) {
2120   assert(getRangeSet().getSpace().isCompatible(poly.getSpace()) &&
2121          "Range set is not compatible with poly");
2122 
2123   IntegerRelation rel = poly;
2124 
2125   // Append dummy domain variables to make the spaces compatible.
2126   rel.appendId(IdKind::Domain, getNumDomainIds());
2127 
2128   mergeLocalIds(rel);
2129   append(rel);
2130 }
2131 
2132 void IntegerRelation::inverse() {
2133   unsigned numRangeIds = getNumIdKind(IdKind::Range);
2134   convertIdKind(IdKind::Domain, 0, getIdKindEnd(IdKind::Domain), IdKind::Range);
2135   convertIdKind(IdKind::Range, 0, numRangeIds, IdKind::Domain);
2136 }
2137 
2138 void IntegerRelation::compose(const IntegerRelation &rel) {
2139   assert(getRangeSet().getSpace().isCompatible(rel.getDomainSet().getSpace()) &&
2140          "Range of `this` should be compatible with Domain of `rel`");
2141 
2142   IntegerRelation copyRel = rel;
2143 
2144   // Let relation `this` be R1: A -> B, and `rel` be R2: B -> C.
2145   // We convert R1 to A -> (B X C), and R2 to B X C then intersect the range of
2146   // R1 with R2. After this, we get R1: A -> C, by projecting out B.
2147   // TODO: Using nested spaces here would help, since we could directly
2148   // intersect the range with another relation.
2149   unsigned numBIds = getNumRangeIds();
2150 
2151   // Convert R1 from A -> B to A -> (B X C).
2152   appendId(IdKind::Range, copyRel.getNumRangeIds());
2153 
2154   // Convert R2 to B X C.
2155   copyRel.convertIdKind(IdKind::Domain, 0, numBIds, IdKind::Range, 0);
2156 
2157   // Intersect R2 to range of R1.
2158   intersectRange(IntegerPolyhedron(copyRel));
2159 
2160   // Project out B in R1.
2161   convertIdKind(IdKind::Range, 0, numBIds, IdKind::Local);
2162 }
2163 
2164 void IntegerRelation::applyDomain(const IntegerRelation &rel) {
2165   inverse();
2166   compose(rel);
2167   inverse();
2168 }
2169 
2170 void IntegerRelation::applyRange(const IntegerRelation &rel) { compose(rel); }
2171 
2172 void IntegerRelation::printSpace(raw_ostream &os) const {
2173   space.print(os);
2174   os << getNumConstraints() << " constraints\n";
2175 }
2176 
2177 void IntegerRelation::print(raw_ostream &os) const {
2178   assert(hasConsistentState());
2179   printSpace(os);
2180   for (unsigned i = 0, e = getNumEqualities(); i < e; ++i) {
2181     for (unsigned j = 0, f = getNumCols(); j < f; ++j) {
2182       os << atEq(i, j) << " ";
2183     }
2184     os << "= 0\n";
2185   }
2186   for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
2187     for (unsigned j = 0, f = getNumCols(); j < f; ++j) {
2188       os << atIneq(i, j) << " ";
2189     }
2190     os << ">= 0\n";
2191   }
2192   os << '\n';
2193 }
2194 
2195 void IntegerRelation::dump() const { print(llvm::errs()); }
2196 
2197 unsigned IntegerPolyhedron::insertId(IdKind kind, unsigned pos, unsigned num) {
2198   assert((kind != IdKind::Domain || num == 0) &&
2199          "Domain has to be zero in a set");
2200   return IntegerRelation::insertId(kind, pos, num);
2201 }
2202