MLIR 24.0.0git
IntegerRelation.cpp
Go to the documentation of this file.
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// variables supporting symbolic variables and existential quantification.
12//
13//===----------------------------------------------------------------------===//
14
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Sequence.h"
27#include "llvm/ADT/SmallBitVector.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/DebugLog.h"
30#include "llvm/Support/raw_ostream.h"
31#include <algorithm>
32#include <cassert>
33#include <functional>
34#include <memory>
35#include <optional>
36#include <utility>
37#include <vector>
38
39#define DEBUG_TYPE "presburger"
40
41using namespace mlir;
42using namespace presburger;
43
44using llvm::SmallDenseMap;
45
46std::unique_ptr<IntegerRelation> IntegerRelation::clone() const {
47 return std::make_unique<IntegerRelation>(*this);
48}
49
50std::unique_ptr<IntegerPolyhedron> IntegerPolyhedron::clone() const {
51 return std::make_unique<IntegerPolyhedron>(*this);
52}
53
55 assert(space.getNumVars() == oSpace.getNumVars() && "invalid space!");
56 space = oSpace;
57}
58
60 assert(oSpace.getNumLocalVars() == 0 && "no locals should be present!");
61 assert(oSpace.getNumVars() <= getNumVars() && "invalid space!");
62 unsigned newNumLocals = getNumVars() - oSpace.getNumVars();
63 space = oSpace;
64 space.insertVar(VarKind::Local, 0, newNumLocals);
65}
66
67void IntegerRelation::setId(VarKind kind, unsigned i, Identifier id) {
68 assert(space.isUsingIds() &&
69 "space must be using identifiers to set an identifier");
70 assert(kind != VarKind::Local && "local variables cannot have identifiers");
71 assert(i < space.getNumVarKind(kind) && "invalid variable index");
72 space.setId(kind, i, id);
73}
74
76 if (!space.isUsingIds())
77 space.resetIds();
78 return space.getIds(kind);
79}
80
82 assert(space.isEqual(other.getSpace()) && "Spaces must be equal.");
83
84 inequalities.reserveRows(inequalities.getNumRows() +
85 other.getNumInequalities());
86 equalities.reserveRows(equalities.getNumRows() + other.getNumEqualities());
87
88 for (unsigned r = 0, e = other.getNumInequalities(); r < e; r++) {
90 }
91 for (unsigned r = 0, e = other.getNumEqualities(); r < e; r++) {
92 addEquality(other.getEquality(r));
93 }
94}
95
97 IntegerRelation result = *this;
98 result.mergeLocalVars(other);
99 result.append(other);
100 return result;
101}
102
104 assert(space.isCompatible(other.getSpace()) && "Spaces must be compatible.");
105 return PresburgerRelation(*this).isEqual(PresburgerRelation(other));
106}
107
109 if (!space.isEqual(other.getSpace()))
110 return false;
111 if (getNumEqualities() != other.getNumEqualities())
112 return false;
113 if (getNumInequalities() != other.getNumInequalities())
114 return false;
115
116 unsigned cols = getNumCols();
117 for (unsigned i = 0, eqs = getNumEqualities(); i < eqs; ++i) {
118 for (unsigned j = 0; j < cols; ++j) {
119 if (atEq(i, j) != other.atEq(i, j))
120 return false;
121 }
122 }
123 for (unsigned i = 0, ineqs = getNumInequalities(); i < ineqs; ++i) {
124 for (unsigned j = 0; j < cols; ++j) {
125 if (atIneq(i, j) != other.atIneq(i, j))
126 return false;
127 }
128 }
129 return true;
130}
131
133 assert(space.isCompatible(other.getSpace()) && "Spaces must be compatible.");
135}
136
139 assert(getNumSymbolVars() == 0 && "Symbols are not supported!");
142
143 if (!maybeLexMin.isBounded())
144 return maybeLexMin;
145
146 // The Simplex returns the lexmin over all the variables including locals. But
147 // locals are not actually part of the space and should not be returned in the
148 // result. Since the locals are placed last in the list of variables, they
149 // will be minimized last in the lexmin. So simply truncating out the locals
150 // from the end of the answer gives the desired lexmin over the dimensions.
151 assert(maybeLexMin->size() == getNumVars() &&
152 "Incorrect number of vars in lexMin!");
153 maybeLexMin->resize(getNumDimAndSymbolVars());
154 return maybeLexMin;
155}
156
159 assert(getNumSymbolVars() == 0 && "Symbols are not supported!");
162
163 if (!maybeLexMin.isBounded())
164 return maybeLexMin.getKind();
165
166 // The Simplex returns the lexmin over all the variables including locals. But
167 // locals are not actually part of the space and should not be returned in the
168 // result. Since the locals are placed last in the list of variables, they
169 // will be minimized last in the lexmin. So simply truncating out the locals
170 // from the end of the answer gives the desired lexmin over the dimensions.
171 assert(maybeLexMin->size() == getNumVars() &&
172 "Incorrect number of vars in lexMin!");
173 maybeLexMin->resize(getNumDimAndSymbolVars());
174 return maybeLexMin;
175}
176
178 return llvm::all_of(range, [](const DynamicAPInt &x) { return x == 0; });
179}
180
182 unsigned begin, unsigned count) {
183 // We loop until i > 0 and index into i - 1 to avoid sign issues.
184 //
185 // We iterate backwards so that whether we remove constraint i - 1 or not, the
186 // next constraint to be tested is always i - 2.
187 for (unsigned i = poly.getNumEqualities(); i > 0; i--)
188 if (!rangeIsZero(poly.getEquality(i - 1).slice(begin, count)))
189 poly.removeEquality(i - 1);
190 for (unsigned i = poly.getNumInequalities(); i > 0; i--)
191 if (!rangeIsZero(poly.getInequality(i - 1).slice(begin, count)))
192 poly.removeInequality(i - 1);
193}
194
198
200 unsigned curNum = getNumVarKind(kind);
201 assert(num <= curNum && "Can't truncate to more vars!");
202 removeVarRange(kind, num, curNum);
203}
204
206 const CountsSnapshot &counts) {
207 truncateVarKind(kind, counts.getSpace().getNumVarKind(kind));
208}
209
218
220 // If there are no locals, we're done.
221 if (getNumLocalVars() == 0)
222 return PresburgerRelation(*this);
223
224 // Move all the non-div locals to the end, as the current API to
225 // SymbolicLexOpt requires these to form a contiguous range.
226 //
227 // Take a copy so we can perform mutations.
228 IntegerRelation copy = *this;
229 std::vector<MaybeLocalRepr> reprs(getNumLocalVars());
230 copy.getLocalReprs(&reprs);
231
232 // Iterate through all the locals. The last `numNonDivLocals` are the locals
233 // that have been scanned already and do not have division representations.
234 unsigned numNonDivLocals = 0;
235 unsigned offset = copy.getVarKindOffset(VarKind::Local);
236 for (unsigned i = 0, e = copy.getNumLocalVars(); i < e - numNonDivLocals;) {
237 if (!reprs[i]) {
238 // Whenever we come across a local that does not have a division
239 // representation, we swap it to the `numNonDivLocals`-th last position
240 // and increment `numNonDivLocal`s. `reprs` also needs to be swapped.
241 copy.swapVar(offset + i, offset + e - numNonDivLocals - 1);
242 std::swap(reprs[i], reprs[e - numNonDivLocals - 1]);
243 ++numNonDivLocals;
244 continue;
245 }
246 ++i;
247 }
248
249 // If there are no non-div locals, we're done.
250 if (numNonDivLocals == 0)
251 return PresburgerRelation(*this);
252
253 // We computeSymbolicIntegerLexMin by considering the non-div locals as
254 // "non-symbols" and considering everything else as "symbols". This will
255 // compute a function mapping assignments to "symbols" to the
256 // lexicographically minimal valid assignment of "non-symbols", when a
257 // satisfying assignment exists. It separately returns the set of assignments
258 // to the "symbols" such that a satisfying assignment to the "non-symbols"
259 // exists but the lexmin is unbounded. We basically want to find the set of
260 // values of the "symbols" such that an assignment to the "non-symbols"
261 // exists, which is the union of the domain of the returned lexmin function
262 // and the returned set of assignments to the "symbols" that makes the lexmin
263 // unbounded.
264 SymbolicLexOpt lexminResult =
265 SymbolicLexSimplex(copy, /*symbolOffset*/ 0,
267 /*numDims=*/copy.getNumVars() - numNonDivLocals)))
270 lexminResult.lexopt.getDomain().unionSet(lexminResult.unboundedDomain);
271
272 // The result set might lie in the wrong space -- all its ids are dims.
273 // Set it to the desired space and return.
275 space.removeVarRange(VarKind::Local, 0, getNumLocalVars());
276 result.setSpace(space);
277 return result;
278}
279
281 // Symbol and Domain vars will be used as symbols for symbolic lexmin.
282 // In other words, for every value of the symbols and domain, return the
283 // lexmin value of the (range, locals).
284 llvm::SmallBitVector isSymbol(getNumVars(), false);
285 isSymbol.set(getVarKindOffset(VarKind::Symbol),
287 isSymbol.set(getVarKindOffset(VarKind::Domain),
289 // Compute the symbolic lexmin of the dims and locals, with the symbols being
290 // the actual symbols of this set.
291 // The resultant space of lexmin is the space of the relation itself.
293 SymbolicLexSimplex(*this,
295 /*numDims=*/getNumDomainVars(),
296 /*numSymbols=*/getNumSymbolVars())),
297 isSymbol)
299
300 // We want to return only the lexmin over the dims, so strip the locals from
301 // the computed lexmin.
302 result.lexopt.removeOutputs(result.lexopt.getNumOutputs() - getNumLocalVars(),
303 result.lexopt.getNumOutputs());
304 return result;
305}
306
307/// findSymbolicIntegerLexMax is implemented using findSymbolicIntegerLexMin as
308/// follows:
309/// 1. A new relation is created which is `this` relation with the sign of
310/// each dimension variable in range flipped;
311/// 2. findSymbolicIntegerLexMin is called on the range negated relation to
312/// compute the negated lexmax of `this` relation;
313/// 3. The sign of the negated lexmax is flipped and returned.
315 IntegerRelation flippedRel = *this;
316 // Flip range sign by flipping the sign of range variables in all constraints.
317 for (unsigned j = getNumDomainVars(),
319 j < b; j++) {
320 for (unsigned i = 0, a = getNumEqualities(); i < a; i++)
321 flippedRel.atEq(i, j) = -1 * atEq(i, j);
322 for (unsigned i = 0, a = getNumInequalities(); i < a; i++)
323 flippedRel.atIneq(i, j) = -1 * atIneq(i, j);
324 }
325 // Compute negated lexmax by computing lexmin.
326 SymbolicLexOpt flippedSymbolicIntegerLexMax =
327 flippedRel.findSymbolicIntegerLexMin(),
328 symbolicIntegerLexMax(
329 flippedSymbolicIntegerLexMax.lexopt.getSpace());
330 // Get lexmax by flipping range sign in the PWMA constraints.
331 for (auto &flippedPiece :
332 flippedSymbolicIntegerLexMax.lexopt.getAllPieces()) {
333 IntMatrix mat = flippedPiece.output.getOutputMatrix();
334 for (unsigned i = 0, e = mat.getNumRows(); i < e; i++)
335 mat.negateRow(i);
336 MultiAffineFunction maf(flippedPiece.output.getSpace(), mat);
337 PWMAFunction::Piece piece = {flippedPiece.domain, maf};
338 symbolicIntegerLexMax.lexopt.addPiece(piece);
339 }
340 symbolicIntegerLexMax.unboundedDomain =
341 flippedSymbolicIntegerLexMax.unboundedDomain;
342 return symbolicIntegerLexMax;
343}
344
347 return PresburgerRelation(*this).subtract(set);
348}
349
350unsigned IntegerRelation::insertVar(VarKind kind, unsigned pos, unsigned num) {
351 assert(pos <= getNumVarKind(kind));
352
353 unsigned insertPos = space.insertVar(kind, pos, num);
354 inequalities.insertColumns(insertPos, num);
355 equalities.insertColumns(insertPos, num);
356 return insertPos;
357}
358
359unsigned IntegerRelation::appendVar(VarKind kind, unsigned num) {
360 unsigned pos = getNumVarKind(kind);
361 return insertVar(kind, pos, num);
362}
363
365 assert(eq.size() == getNumCols());
366 unsigned row = equalities.appendExtraRow();
367 for (unsigned i = 0, e = eq.size(); i < e; ++i)
368 equalities(row, i) = eq[i];
369}
370
372 assert(inEq.size() == getNumCols());
373 unsigned row = inequalities.appendExtraRow();
374 for (unsigned i = 0, e = inEq.size(); i < e; ++i)
375 inequalities(row, i) = inEq[i];
376}
377
378void IntegerRelation::removeVar(VarKind kind, unsigned pos) {
379 removeVarRange(kind, pos, pos + 1);
380}
381
382void IntegerRelation::removeVar(unsigned pos) { removeVarRange(pos, pos + 1); }
383
384void IntegerRelation::removeVarRange(VarKind kind, unsigned varStart,
385 unsigned varLimit) {
386 assert(varLimit <= getNumVarKind(kind));
387
388 if (varStart >= varLimit)
389 return;
390
391 // Remove eliminated variables from the constraints.
392 unsigned offset = getVarKindOffset(kind);
393 equalities.removeColumns(offset + varStart, varLimit - varStart);
394 inequalities.removeColumns(offset + varStart, varLimit - varStart);
395
396 // Remove eliminated variables from the space.
397 space.removeVarRange(kind, varStart, varLimit);
398}
399
400void IntegerRelation::removeVarRange(unsigned varStart, unsigned varLimit) {
401 assert(varLimit <= getNumVars());
402
403 if (varStart >= varLimit)
404 return;
405
406 // Helper function to remove vars of the specified kind in the given range
407 // [start, limit), The range is absolute (i.e. it is not relative to the kind
408 // of variable). Also updates `limit` to reflect the deleted variables.
409 auto removeVarKindInRange = [this](VarKind kind, unsigned &start,
410 unsigned &limit) {
411 if (start >= limit)
412 return;
413
414 unsigned offset = getVarKindOffset(kind);
415 unsigned num = getNumVarKind(kind);
416
417 // Get `start`, `limit` relative to the specified kind.
418 unsigned relativeStart =
419 start <= offset ? 0 : std::min(num, start - offset);
420 unsigned relativeLimit =
421 limit <= offset ? 0 : std::min(num, limit - offset);
422
423 // Remove vars of the specified kind in the relative range.
424 removeVarRange(kind, relativeStart, relativeLimit);
425
426 // Update `limit` to reflect deleted variables.
427 // `start` does not need to be updated because any variables that are
428 // deleted are after position `start`.
429 limit -= relativeLimit - relativeStart;
430 };
431
432 removeVarKindInRange(VarKind::Domain, varStart, varLimit);
433 removeVarKindInRange(VarKind::Range, varStart, varLimit);
434 removeVarKindInRange(VarKind::Symbol, varStart, varLimit);
435 removeVarKindInRange(VarKind::Local, varStart, varLimit);
436}
437
439 equalities.removeRow(pos);
440}
441
443 inequalities.removeRow(pos);
444}
445
447 if (pos >= getNumInequalities()) {
449 } else {
450 removeInequality(pos);
451 }
452}
453
454void IntegerRelation::removeEqualityRange(unsigned start, unsigned end) {
455 if (start >= end)
456 return;
457 equalities.removeRows(start, end - start);
458}
459
460void IntegerRelation::removeInequalityRange(unsigned start, unsigned end) {
461 if (start >= end)
462 return;
463 inequalities.removeRows(start, end - start);
464}
465
466void IntegerRelation::swapVar(unsigned posA, unsigned posB) {
467 assert(posA < getNumVars() && "invalid position A");
468 assert(posB < getNumVars() && "invalid position B");
469
470 if (posA == posB)
471 return;
472
473 VarKind kindA = space.getVarKindAt(posA);
474 VarKind kindB = space.getVarKindAt(posB);
475 unsigned relativePosA = posA - getVarKindOffset(kindA);
476 unsigned relativePosB = posB - getVarKindOffset(kindB);
477 space.swapVar(kindA, kindB, relativePosA, relativePosB);
478
479 inequalities.swapColumns(posA, posB);
480 equalities.swapColumns(posA, posB);
481}
482
484 equalities.resizeVertically(0);
485 inequalities.resizeVertically(0);
486}
487
488/// Gather all lower and upper bounds of the variable at `pos`, and
489/// optionally any equalities on it. In addition, the bounds are to be
490/// independent of variables in position range [`offset`, `offset` + `num`).
492 unsigned pos, SmallVectorImpl<unsigned> *lbIndices,
494 unsigned offset, unsigned num) const {
495 assert(pos < getNumVars() && "invalid position");
496 assert(offset + num < getNumCols() && "invalid range");
497
498 // Checks for a constraint that has a non-zero coeff for the variables in
499 // the position range [offset, offset + num) while ignoring `pos`.
500 auto containsConstraintDependentOnRange = [&](unsigned r, bool isEq) {
501 unsigned c, f;
502 auto cst = isEq ? getEquality(r) : getInequality(r);
503 for (c = offset, f = offset + num; c < f; ++c) {
504 if (c == pos)
505 continue;
506 if (cst[c] != 0)
507 break;
508 }
509 return c < f;
510 };
511
512 // Gather all lower bounds and upper bounds of the variable. Since the
513 // canonical form c_1*x_1 + c_2*x_2 + ... + c_0 >= 0, a constraint is a lower
514 // bound for x_i if c_i >= 1, and an upper bound if c_i <= -1.
515 for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
516 // The bounds are to be independent of [offset, offset + num) columns.
517 if (containsConstraintDependentOnRange(r, /*isEq=*/false))
518 continue;
519 if (atIneq(r, pos) >= 1) {
520 // Lower bound.
521 lbIndices->emplace_back(r);
522 } else if (atIneq(r, pos) <= -1) {
523 // Upper bound.
524 ubIndices->emplace_back(r);
525 }
526 }
527
528 // An equality is both a lower and upper bound. Record any equalities
529 // involving the pos^th variable.
530 if (!eqIndices)
531 return;
532
533 for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
534 if (atEq(r, pos) == 0)
535 continue;
536 if (containsConstraintDependentOnRange(r, /*isEq=*/true))
537 continue;
538 eqIndices->emplace_back(r);
539 }
540}
541
543 if (!inequalities.hasConsistentState())
544 return false;
545 if (!equalities.hasConsistentState())
546 return false;
547 return true;
548}
549
551 ArrayRef<DynamicAPInt> values) {
552 if (values.empty())
553 return;
554 assert(pos + values.size() <= getNumVars() &&
555 "invalid position or too many values");
556 // Setting x_j = p in sum_i a_i x_i + c is equivalent to adding p*a_j to the
557 // constant term and removing the var x_j. We do this for all the vars
558 // pos, pos + 1, ... pos + values.size() - 1.
559 unsigned constantColPos = getNumCols() - 1;
560 for (unsigned i = 0, numVals = values.size(); i < numVals; ++i)
561 inequalities.addToColumn(i + pos, constantColPos, values[i]);
562 for (unsigned i = 0, numVals = values.size(); i < numVals; ++i)
563 equalities.addToColumn(i + pos, constantColPos, values[i]);
564 removeVarRange(pos, pos + values.size());
565}
566
568 *this = other;
569}
570
571std::optional<unsigned>
572IntegerRelation::findConstraintWithNonZeroAt(unsigned colIdx, bool isEq) const {
573 assert(colIdx < getNumCols() && "position out of bounds");
574 auto at = [&](unsigned rowIdx) -> DynamicAPInt {
575 return isEq ? atEq(rowIdx, colIdx) : atIneq(rowIdx, colIdx);
576 };
577 unsigned e = isEq ? getNumEqualities() : getNumInequalities();
578 for (unsigned rowIdx = 0; rowIdx < e; ++rowIdx) {
579 if (at(rowIdx) != 0)
580 return rowIdx;
581 }
582 return std::nullopt;
583}
584
586 for (unsigned i = 0, e = getNumEqualities(); i < e; ++i)
587 equalities.normalizeRow(i);
588 for (unsigned i = 0, e = getNumInequalities(); i < e; ++i)
589 inequalities.normalizeRow(i);
590}
591
593 assert(hasConsistentState());
594 auto check = [&](bool isEq) -> bool {
595 unsigned numCols = getNumCols();
596 unsigned numRows = isEq ? getNumEqualities() : getNumInequalities();
597 for (unsigned i = 0, e = numRows; i < e; ++i) {
598 unsigned j;
599 for (j = 0; j < numCols - 1; ++j) {
600 DynamicAPInt v = isEq ? atEq(i, j) : atIneq(i, j);
601 // Skip rows with non-zero variable coefficients.
602 if (v != 0)
603 break;
604 }
605 if (j < numCols - 1) {
606 continue;
607 }
608 // Check validity of constant term at 'numCols - 1' w.r.t 'isEq'.
609 // Example invalid constraints include: '1 == 0' or '-1 >= 0'
610 DynamicAPInt v = isEq ? atEq(i, numCols - 1) : atIneq(i, numCols - 1);
611 if ((isEq && v != 0) || (!isEq && v < 0)) {
612 return true;
613 }
614 }
615 return false;
616 };
617 if (check(/*isEq=*/true))
618 return true;
619 return check(/*isEq=*/false);
620}
621
622/// Returns the position of the variable that has the minimum <number of lower
623/// bounds> times <number of upper bounds> from the specified range of
624/// variables [start, end). It is often best to eliminate in the increasing
625/// order of these counts when doing Fourier-Motzkin elimination since FM adds
626/// that many new constraints.
627static unsigned getBestVarToEliminate(const IntegerRelation &cst,
628 unsigned start, unsigned end) {
629 assert(start < cst.getNumVars() && end < cst.getNumVars() + 1);
630
631 auto getProductOfNumLowerUpperBounds = [&](unsigned pos) {
632 unsigned numLb = 0;
633 unsigned numUb = 0;
634 for (unsigned r = 0, e = cst.getNumInequalities(); r < e; r++) {
635 if (cst.atIneq(r, pos) > 0) {
636 ++numLb;
637 } else if (cst.atIneq(r, pos) < 0) {
638 ++numUb;
639 }
640 }
641 return numLb * numUb;
642 };
643
644 unsigned minLoc = start;
645 unsigned min = getProductOfNumLowerUpperBounds(start);
646 for (unsigned c = start + 1; c < end; c++) {
647 unsigned numLbUbProduct = getProductOfNumLowerUpperBounds(c);
648 if (numLbUbProduct < min) {
649 min = numLbUbProduct;
650 minLoc = c;
651 }
652 }
653 return minLoc;
654}
655
656// Checks for emptiness of the set by eliminating variables successively and
657// using the GCD test (on all equality constraints) and checking for trivially
658// invalid constraints. Returns 'true' if the constraint system is found to be
659// empty; false otherwise.
662 return true;
663
664 IntegerRelation tmpCst(*this);
665
666 // First, eliminate as many local variables as possible using equalities.
668 if (tmpCst.isEmptyByGCDTest() || tmpCst.hasInvalidConstraint())
669 return true;
670
671 // Eliminate as many variables as possible using Gaussian elimination.
672 unsigned currentPos = 0;
673 while (currentPos < tmpCst.getNumVars()) {
674 tmpCst.gaussianEliminateVars(currentPos, tmpCst.getNumVars());
675 ++currentPos;
676 // We check emptiness through trivial checks after eliminating each ID to
677 // detect emptiness early. Since the checks isEmptyByGCDTest() and
678 // hasInvalidConstraint() are linear time and single sweep on the constraint
679 // buffer, this appears reasonable - but can optimize in the future.
680 if (tmpCst.hasInvalidConstraint() || tmpCst.isEmptyByGCDTest())
681 return true;
682 }
683
684 // Eliminate the remaining using FM.
685 for (unsigned i = 0, e = tmpCst.getNumVars(); i < e; i++) {
687 getBestVarToEliminate(tmpCst, 0, tmpCst.getNumVars()));
688 // Check for a constraint explosion. This rarely happens in practice, but
689 // this check exists as a safeguard against improperly constructed
690 // constraint systems or artificially created arbitrarily complex systems
691 // that aren't the intended use case for IntegerRelation. This is
692 // needed since FM has a worst case exponential complexity in theory.
693 if (tmpCst.getNumConstraints() >= kExplosionFactor * getNumVars()) {
694 LDBG() << "FM constraint explosion detected";
695 return false;
696 }
697
698 // FM wouldn't have modified the equalities in any way. So no need to again
699 // run GCD test. Check for trivial invalid constraints.
700 if (tmpCst.hasInvalidConstraint())
701 return true;
702 }
703 return false;
704}
705
709
710// Runs the GCD test on all equality constraints. Returns 'true' if this test
711// fails on any equality. Returns 'false' otherwise.
712// This test can be used to disprove the existence of a solution. If it returns
713// true, no integer solution to the equality constraints can exist.
714//
715// GCD test definition:
716//
717// The equality constraint:
718//
719// c_1*x_1 + c_2*x_2 + ... + c_n*x_n = c_0
720//
721// has an integer solution iff:
722//
723// GCD of c_1, c_2, ..., c_n divides c_0.
725 assert(hasConsistentState());
726 unsigned numCols = getNumCols();
727 for (unsigned i = 0, e = getNumEqualities(); i < e; ++i) {
728 DynamicAPInt gcd = abs(atEq(i, 0));
729 for (unsigned j = 1; j < numCols - 1; ++j) {
730 gcd = llvm::gcd(gcd, abs(atEq(i, j)));
731 }
732 DynamicAPInt v = abs(atEq(i, numCols - 1));
733 if (gcd > 0 && (v % gcd != 0)) {
734 return true;
735 }
736 }
737 return false;
738}
739
740// Returns a matrix where each row is a vector along which the polytope is
741// bounded. The span of the returned vectors is guaranteed to contain all
742// such vectors. The returned vectors are NOT guaranteed to be linearly
743// independent. This function should not be called on empty sets.
744//
745// It is sufficient to check the perpendiculars of the constraints, as the set
746// of perpendiculars which are bounded must span all bounded directions.
748 // Note that it is necessary to add the equalities too (which the constructor
749 // does) even though we don't need to check if they are bounded; whether an
750 // inequality is bounded or not depends on what other constraints, including
751 // equalities, are present.
752 Simplex simplex(*this);
753
754 assert(!simplex.isEmpty() && "It is not meaningful to ask whether a "
755 "direction is bounded in an empty set.");
756
757 SmallVector<unsigned, 8> boundedIneqs;
758 // The constructor adds the inequalities to the simplex first, so this
759 // processes all the inequalities.
760 for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
761 if (simplex.isBoundedAlongConstraint(i))
762 boundedIneqs.emplace_back(i);
763 }
764
765 // The direction vector is given by the coefficients and does not include the
766 // constant term, so the matrix has one fewer column.
767 unsigned dirsNumCols = getNumCols() - 1;
768 IntMatrix dirs(boundedIneqs.size() + getNumEqualities(), dirsNumCols);
769
770 // Copy the bounded inequalities.
771 unsigned row = 0;
772 for (unsigned i : boundedIneqs) {
773 for (unsigned col = 0; col < dirsNumCols; ++col)
774 dirs(row, col) = atIneq(i, col);
775 ++row;
776 }
777
778 // Copy the equalities. All the equalities' perpendiculars are bounded.
779 for (unsigned i = 0, e = getNumEqualities(); i < e; ++i) {
780 for (unsigned col = 0; col < dirsNumCols; ++col)
781 dirs(row, col) = atEq(i, col);
782 ++row;
783 }
784
785 return dirs;
786}
787
789
790/// Let this set be S. If S is bounded then we directly call into the GBR
791/// sampling algorithm. Otherwise, there are some unbounded directions, i.e.,
792/// vectors v such that S extends to infinity along v or -v. In this case we
793/// use an algorithm described in the integer set library (isl) manual and used
794/// by the isl_set_sample function in that library. The algorithm is:
795///
796/// 1) Apply a unimodular transform T to S to obtain S*T, such that all
797/// dimensions in which S*T is bounded lie in the linear span of a prefix of the
798/// dimensions.
799///
800/// 2) Construct a set B by removing all constraints that involve
801/// the unbounded dimensions and then deleting the unbounded dimensions. Note
802/// that B is a Bounded set.
803///
804/// 3) Try to obtain a sample from B using the GBR sampling
805/// algorithm. If no sample is found, return that S is empty.
806///
807/// 4) Otherwise, substitute the obtained sample into S*T to obtain a set
808/// C. C is a full-dimensional Cone and always contains a sample.
809///
810/// 5) Obtain an integer sample from C.
811///
812/// 6) Return T*v, where v is the concatenation of the samples from B and C.
813///
814/// The following is a sketch of a proof that
815/// a) If the algorithm returns empty, then S is empty.
816/// b) If the algorithm returns a sample, it is a valid sample in S.
817///
818/// The algorithm returns empty only if B is empty, in which case S*T is
819/// certainly empty since B was obtained by removing constraints and then
820/// deleting unconstrained dimensions from S*T. Since T is unimodular, a vector
821/// v is in S*T iff T*v is in S. So in this case, since
822/// S*T is empty, S is empty too.
823///
824/// Otherwise, the algorithm substitutes the sample from B into S*T. All the
825/// constraints of S*T that did not involve unbounded dimensions are satisfied
826/// by this substitution. All dimensions in the linear span of the dimensions
827/// outside the prefix are unbounded in S*T (step 1). Substituting values for
828/// the bounded dimensions cannot make these dimensions bounded, and these are
829/// the only remaining dimensions in C, so C is unbounded along every vector (in
830/// the positive or negative direction, or both). C is hence a full-dimensional
831/// cone and therefore always contains an integer point.
832///
833/// Concatenating the samples from B and C gives a sample v in S*T, so the
834/// returned sample T*v is a sample in S.
835std::optional<SmallVector<DynamicAPInt, 8>>
837 // First, try the GCD test heuristic.
838 if (isEmptyByGCDTest())
839 return {};
840
841 Simplex simplex(*this);
842 if (simplex.isEmpty())
843 return {};
844
845 // For a bounded set, we directly call into the GBR sampling algorithm.
846 if (!simplex.isUnbounded())
847 return simplex.findIntegerSample();
848
849 // The set is unbounded. We cannot directly use the GBR algorithm.
850 //
851 // m is a matrix containing, in each row, a vector in which S is
852 // bounded, such that the linear span of all these dimensions contains all
853 // bounded dimensions in S.
855 // In column echelon form, each row of m occupies only the first rank(m)
856 // columns and has zeros on the other columns. The transform T that brings S
857 // to column echelon form is unimodular as well, so this is a suitable
858 // transform to use in step 1 of the algorithm.
859 std::pair<unsigned, LinearTransform> result =
861 const LinearTransform &transform = result.second;
862 // 1) Apply T to S to obtain S*T.
863 IntegerRelation transformedSet = transform.applyTo(*this);
864
865 // 2) Remove the unbounded dimensions and constraints involving them to
866 // obtain a bounded set.
867 IntegerRelation boundedSet(transformedSet);
868 unsigned numBoundedDims = result.first;
869 unsigned numUnboundedDims = getNumVars() - numBoundedDims;
870 removeConstraintsInvolvingVarRange(boundedSet, numBoundedDims,
871 numUnboundedDims);
872 boundedSet.removeVarRange(numBoundedDims, boundedSet.getNumVars());
873
874 // 3) Try to obtain a sample from the bounded set.
875 std::optional<SmallVector<DynamicAPInt, 8>> boundedSample =
876 Simplex(boundedSet).findIntegerSample();
877 if (!boundedSample)
878 return {};
879 assert(boundedSet.containsPoint(*boundedSample) &&
880 "Simplex returned an invalid sample!");
881
882 // 4) Substitute the values of the bounded dimensions into S*T to obtain a
883 // full-dimensional cone, which necessarily contains an integer sample.
884 transformedSet.setAndEliminate(0, *boundedSample);
885 IntegerRelation &cone = transformedSet;
886
887 // 5) Obtain an integer sample from the cone.
888 //
889 // We shrink the cone such that for any rational point in the shrunken cone,
890 // rounding up each of the point's coordinates produces a point that still
891 // lies in the original cone.
892 //
893 // Rounding up a point x adds a number e_i in [0, 1) to each coordinate x_i.
894 // For each inequality sum_i a_i x_i + c >= 0 in the original cone, the
895 // shrunken cone will have the inequality tightened by some amount s, such
896 // that if x satisfies the shrunken cone's tightened inequality, then x + e
897 // satisfies the original inequality, i.e.,
898 //
899 // sum_i a_i x_i + c + s >= 0 implies sum_i a_i (x_i + e_i) + c >= 0
900 //
901 // for any e_i values in [0, 1). In fact, we will handle the slightly more
902 // general case where e_i can be in [0, 1]. For example, consider the
903 // inequality 2x_1 - 3x_2 - 7x_3 - 6 >= 0, and let x = (3, 0, 0). How low
904 // could the LHS go if we added a number in [0, 1] to each coordinate? The LHS
905 // is minimized when we add 1 to the x_i with negative coefficient a_i and
906 // keep the other x_i the same. In the example, we would get x = (3, 1, 1),
907 // changing the value of the LHS by -3 + -7 = -10.
908 //
909 // In general, the value of the LHS can change by at most the sum of the
910 // negative a_i, so we accomodate this by shifting the inequality by this
911 // amount for the shrunken cone.
912 for (unsigned i = 0, e = cone.getNumInequalities(); i < e; ++i) {
913 for (unsigned j = 0; j < cone.getNumVars(); ++j) {
914 DynamicAPInt coeff = cone.atIneq(i, j);
915 if (coeff < 0)
916 cone.atIneq(i, cone.getNumVars()) += coeff;
917 }
918 }
919
920 // Obtain an integer sample in the cone by rounding up a rational point from
921 // the shrunken cone. Shrinking the cone amounts to shifting its apex
922 // "inwards" without changing its "shape"; the shrunken cone is still a
923 // full-dimensional cone and is hence non-empty.
924 Simplex shrunkenConeSimplex(cone);
925 assert(!shrunkenConeSimplex.isEmpty() && "Shrunken cone cannot be empty!");
926
927 // The sample will always exist since the shrunken cone is non-empty.
928 SmallVector<Fraction, 8> shrunkenConeSample =
929 *shrunkenConeSimplex.getRationalSample();
930
932 llvm::map_range(shrunkenConeSample, ceil));
933
934 // 6) Return transform * concat(boundedSample, coneSample).
935 SmallVector<DynamicAPInt, 8> &sample = *boundedSample;
936 sample.append(coneSample.begin(), coneSample.end());
937 return transform.postMultiplyWithColumn(sample);
938}
939
940/// Helper to evaluate an affine expression at a point.
941/// The expression is a list of coefficients for the dimensions followed by the
942/// constant term.
943static DynamicAPInt valueAt(ArrayRef<DynamicAPInt> expr,
945 assert(expr.size() == 1 + point.size() &&
946 "Dimensionalities of point and expression don't match!");
947 DynamicAPInt value = expr.back();
948 for (unsigned i = 0; i < point.size(); ++i)
949 value += expr[i] * point[i];
950 return value;
951}
952
953/// A point satisfies an equality iff the value of the equality at the
954/// expression is zero, and it satisfies an inequality iff the value of the
955/// inequality at that point is non-negative.
957 for (unsigned i = 0, e = getNumEqualities(); i < e; ++i) {
958 if (valueAt(getEquality(i), point) != 0)
959 return false;
960 }
961 for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
962 if (valueAt(getInequality(i), point) < 0)
963 return false;
964 }
965 return true;
966}
967
968/// Just substitute the values given and check if an integer sample exists for
969/// the local vars.
970///
971/// TODO: this could be made more efficient by handling divisions separately.
972/// Instead of finding an integer sample over all the locals, we can first
973/// compute the values of the locals that have division representations and
974/// only use the integer emptiness check for the locals that don't have this.
975/// Handling this correctly requires ordering the divs, though.
976std::optional<SmallVector<DynamicAPInt, 8>>
978 assert(point.size() == getNumVars() - getNumLocalVars() &&
979 "Point should contain all vars except locals!");
981 "This function depends on locals being stored last!");
982 IntegerRelation copy = *this;
983 copy.setAndEliminate(0, point);
984 return copy.findIntegerSample();
985}
986
988IntegerRelation::getLocalReprs(std::vector<MaybeLocalRepr> *repr) const {
989 SmallVector<bool, 8> foundRepr(getNumVars(), false);
990 for (unsigned i = 0, e = getNumDimAndSymbolVars(); i < e; ++i)
991 foundRepr[i] = true;
992
993 unsigned localOffset = getVarKindOffset(VarKind::Local);
995 bool changed;
996 do {
997 // Each time changed is true, at end of this iteration, one or more local
998 // vars have been detected as floor divs.
999 changed = false;
1000 for (unsigned i = 0, e = getNumLocalVars(); i < e; ++i) {
1001 if (!foundRepr[i + localOffset]) {
1002 MaybeLocalRepr res =
1003 computeSingleVarRepr(*this, foundRepr, localOffset + i,
1004 divs.getDividend(i), divs.getDenom(i));
1005 if (!res) {
1006 // No representation was found, so clear the representation and
1007 // continue.
1008 divs.clearRepr(i);
1009 continue;
1010 }
1011 foundRepr[localOffset + i] = true;
1012 if (repr)
1013 (*repr)[i] = res;
1014 changed = true;
1015 }
1016 }
1017 } while (changed);
1018
1019 return divs;
1020}
1021
1022/// Tightens inequalities given that we are dealing with integer spaces. This is
1023/// analogous to the GCD test but applied to inequalities. The constant term can
1024/// be reduced to the preceding multiple of the GCD of the coefficients, i.e.,
1025/// 64*i - 100 >= 0 => 64*i - 128 >= 0 (since 'i' is an integer). This is a
1026/// fast method - linear in the number of coefficients.
1027// Example on how this affects practical cases: consider the scenario:
1028// 64*i >= 100, j = 64*i; without a tightening, elimination of i would yield
1029// j >= 100 instead of the tighter (exact) j >= 128.
1031 unsigned numCols = getNumCols();
1032 for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
1033 // Normalize the constraint and tighten the constant term by the GCD.
1034 DynamicAPInt gcd = inequalities.normalizeRow(i, getNumCols() - 1);
1035 if (gcd > 1)
1036 atIneq(i, numCols - 1) = floorDiv(atIneq(i, numCols - 1), gcd);
1037 }
1038}
1039
1040// Eliminates all variable variables in column range [posStart, posLimit).
1041// Returns the number of variables eliminated.
1043 unsigned posLimit) {
1044 // Return if variable positions to eliminate are out of range.
1045 assert(posLimit <= getNumVars());
1046 assert(hasConsistentState());
1047
1048 if (posStart >= posLimit)
1049 return 0;
1050
1052
1053 unsigned pivotCol = 0;
1054 for (pivotCol = posStart; pivotCol < posLimit; ++pivotCol) {
1055 // Find a row which has a non-zero coefficient in column 'j'.
1056 std::optional<unsigned> pivotRow =
1057 findConstraintWithNonZeroAt(pivotCol, /*isEq=*/true);
1058 // No pivot row in equalities with non-zero at 'pivotCol'.
1059 if (!pivotRow) {
1060 // If inequalities are also non-zero in 'pivotCol', it can be eliminated.
1061 if ((pivotRow = findConstraintWithNonZeroAt(pivotCol, /*isEq=*/false)))
1062 break;
1063 continue;
1064 }
1065
1066 // Eliminate variable at 'pivotCol' from every other constraint.
1067 eliminateVarUsingEquality(pivotCol, *pivotRow);
1069 removeEquality(*pivotRow);
1071 }
1072 // Update position limit based on number eliminated.
1073 posLimit = pivotCol;
1074 // Remove eliminated columns from all constraints.
1075 removeVarRange(posStart, posLimit);
1076 return posLimit - posStart;
1077}
1078
1079static std::optional<unsigned>
1081 unsigned colIdx) {
1082 assert(fromRow < rel.getNumEqualities() && colIdx < rel.getNumCols() &&
1083 "position out of bounds");
1084 for (unsigned rowIdx = fromRow, e = rel.getNumEqualities(); rowIdx < e;
1085 ++rowIdx) {
1086 if (rel.atEq(rowIdx, colIdx) != 0)
1087 return rowIdx;
1088 }
1089 return std::nullopt;
1090}
1091
1094 unsigned firstVar = 0, vars = getNumVars();
1095 unsigned nowDone, eqs;
1096 std::optional<unsigned> pivotRow;
1097 for (nowDone = 0, eqs = getNumEqualities(); nowDone < eqs; ++nowDone) {
1098 // Finds the first non-empty column that we haven't dealt with.
1099 for (; firstVar < vars; ++firstVar) {
1100 if ((pivotRow =
1101 findEqualityWithNonZeroAfterRow(*this, nowDone, firstVar)))
1102 break;
1103 }
1104 // The matrix has been normalized to row echelon form.
1105 if (firstVar >= vars)
1106 break;
1107
1108 // The first pivot row found is below where it should currently be placed.
1109 if (*pivotRow > nowDone) {
1110 equalities.swapRows(*pivotRow, nowDone);
1111 *pivotRow = nowDone;
1112 }
1113
1114 // Normalize all lower equations and all inequalities. Only rows other
1115 // than the pivot row are modified, so this view of it stays valid.
1116 ArrayRef<DynamicAPInt> pivot = equalities.getRow(*pivotRow);
1117 for (unsigned i = nowDone + 1; i < eqs; ++i) {
1118 equalities.eliminateColumnUsingRow(firstVar, pivot, i);
1119 equalities.normalizeRow(i);
1120 }
1121 for (unsigned i = 0, ineqs = getNumInequalities(); i < ineqs; ++i) {
1122 inequalities.eliminateColumnUsingRow(firstVar, pivot, i);
1123 inequalities.normalizeRow(i);
1124 }
1126
1127 // The column is finished. Tell the next iteration to start at the next
1128 // column.
1129 firstVar++;
1130 }
1131
1132 // No redundant rows.
1133 if (nowDone == eqs)
1134 return false;
1135
1136 // Check to see if the redundant rows constant is zero, a non-zero value means
1137 // the set is empty.
1138 for (unsigned i = nowDone; i < eqs; ++i) {
1139 if (atEq(i, vars) == 0)
1140 continue;
1141
1142 *this = getEmpty(getSpace());
1143 return true;
1144 }
1145 // Eliminate rows that are confined to be all zeros.
1146 removeEqualityRange(nowDone, eqs);
1147 return true;
1148}
1149
1150// A more complex check to eliminate redundant inequalities. Uses FourierMotzkin
1151// to check if a constraint is redundant.
1154 // To check if an inequality is redundant, we replace the inequality by its
1155 // complement (for eg., i - 1 >= 0 by i <= 0), and check if the resulting
1156 // system is empty. If it is, the inequality is redundant.
1157 IntegerRelation tmpCst(*this);
1158 for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
1159 // Change the inequality to its complement.
1160 tmpCst.inequalities.negateRow(r);
1161 --tmpCst.atIneq(r, tmpCst.getNumCols() - 1);
1162 if (tmpCst.isEmpty()) {
1163 redun[r] = true;
1164 // Zero fill the redundant inequality.
1165 inequalities.fillRow(r, /*value=*/0);
1166 tmpCst.inequalities.fillRow(r, /*value=*/0);
1167 } else {
1168 // Reverse the change (to avoid recreating tmpCst each time).
1169 ++tmpCst.atIneq(r, tmpCst.getNumCols() - 1);
1170 tmpCst.inequalities.negateRow(r);
1171 }
1172 }
1173
1174 unsigned pos = 0;
1175 for (unsigned r = 0, e = getNumInequalities(); r < e; ++r) {
1176 if (!redun[r])
1177 inequalities.copyRow(r, pos++);
1178 }
1179 inequalities.resizeVertically(pos);
1180}
1181
1182// A more complex check to eliminate redundant inequalities and equalities. Uses
1183// Simplex to check if a constraint is redundant.
1185 // First, we run gcdTightenInequalities. This allows us to catch some
1186 // constraints which are not redundant when considering rational solutions
1187 // but are redundant in terms of integer solutions.
1189 Simplex simplex(*this);
1190 simplex.detectRedundant();
1191 removeRedundantConstraintsFromSimplex(simplex, /*offset=*/0);
1192}
1193
1195 const Simplex &simplex, unsigned offset) {
1196 unsigned numIneqs = getNumInequalities();
1197 assert(offset + numIneqs + 2 * getNumEqualities() <=
1198 simplex.getNumConstraints() &&
1199 "simplex does not contain all constraints of this relation");
1200
1201 unsigned pos = 0;
1202 // Scan to get rid of all inequalities marked redundant, in-place. In Simplex,
1203 // the first constraints added are the inequalities.
1204 for (unsigned r = 0; r < numIneqs; r++) {
1205 if (!simplex.isMarkedRedundant(offset + r))
1206 inequalities.copyRow(r, pos++);
1207 }
1208 inequalities.resizeVertically(pos);
1209
1210 // Scan to get rid of all equalities marked redundant, in-place. In Simplex,
1211 // after the inequalities, a pair of constraints for each equality is added.
1212 // An equality is redundant if both the inequalities in its pair are
1213 // redundant.
1214 pos = 0;
1215 for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
1216 if (!(simplex.isMarkedRedundant(offset + numIneqs + 2 * r) &&
1217 simplex.isMarkedRedundant(offset + numIneqs + 2 * r + 1)))
1218 equalities.copyRow(r, pos++);
1219 }
1220 equalities.resizeVertically(pos);
1221}
1222
1223void IntegerRelation::eliminateVarUsingEquality(unsigned col, unsigned eqIdx) {
1224 assert(eqIdx < getNumEqualities() && "equality index out of bounds");
1225 assert(col < getNumVars() && "column must be a variable");
1226 assert(atEq(eqIdx, col) != 0 &&
1227 "equality must have non-zero coefficient at col");
1228 // Only rows other than the pivot row are modified, so this view of it stays
1229 // valid.
1230 ArrayRef<DynamicAPInt> eq = equalities.getRow(eqIdx);
1231 for (unsigned i = 0, e = getNumEqualities(); i < e; ++i)
1232 if (i != eqIdx)
1233 equalities.eliminateColumnUsingRow(col, eq, i);
1234 for (unsigned i = 0, e = getNumInequalities(); i < e; ++i)
1235 inequalities.eliminateColumnUsingRow(col, eq, i);
1236}
1237
1238std::optional<DynamicAPInt> IntegerRelation::computeVolume() const {
1239 assert(getNumSymbolVars() == 0 && "Symbols are not yet supported!");
1240
1241 Simplex simplex(*this);
1242 // If the polytope is rationally empty, there are certainly no integer
1243 // points.
1244 if (simplex.isEmpty())
1245 return DynamicAPInt(0);
1246
1247 // Just find the maximum and minimum integer value of each non-local var
1248 // separately, thus finding the number of integer values each such var can
1249 // take. Multiplying these together gives a valid overapproximation of the
1250 // number of integer points in the relation. The result this gives is
1251 // equivalent to projecting (rationally) the relation onto its non-local vars
1252 // and returning the number of integer points in a minimal axis-parallel
1253 // hyperrectangular overapproximation of that.
1254 //
1255 // We also handle the special case where one dimension is unbounded and
1256 // another dimension can take no integer values. In this case, the volume is
1257 // zero.
1258 //
1259 // If there is no such empty dimension, if any dimension is unbounded we
1260 // just return the result as unbounded.
1261 DynamicAPInt count(1);
1263 bool hasUnboundedVar = false;
1264 for (unsigned i = 0, e = getNumDimAndSymbolVars(); i < e; ++i) {
1265 dim[i] = 1;
1266 auto [min, max] = simplex.computeIntegerBounds(dim);
1267 dim[i] = 0;
1268
1269 assert((!min.isEmpty() && !max.isEmpty()) &&
1270 "Polytope should be rationally non-empty!");
1271
1272 // One of the dimensions is unbounded. Note this fact. We will return
1273 // unbounded if none of the other dimensions makes the volume zero.
1274 if (min.isUnbounded() || max.isUnbounded()) {
1275 hasUnboundedVar = true;
1276 continue;
1277 }
1278
1279 // In this case there are no valid integer points and the volume is
1280 // definitely zero.
1281 if (min.getBoundedOptimum() > max.getBoundedOptimum())
1282 return DynamicAPInt(0);
1283
1284 count *= (*max - *min + 1);
1285 }
1286
1287 if (count == 0)
1288 return DynamicAPInt(0);
1289 if (hasUnboundedVar)
1290 return {};
1291 return count;
1292}
1293
1294void IntegerRelation::eliminateRedundantLocalVar(unsigned posA, unsigned posB) {
1295 assert(posA < getNumLocalVars() && "Invalid local var position");
1296 assert(posB < getNumLocalVars() && "Invalid local var position");
1297
1298 unsigned localOffset = getVarKindOffset(VarKind::Local);
1299 posA += localOffset;
1300 posB += localOffset;
1301 inequalities.addToColumn(posB, posA, 1);
1302 equalities.addToColumn(posB, posA, 1);
1303 removeVar(posB);
1304}
1305
1306/// mergeAndAlignSymbols's implementation can be broken down into two steps:
1307/// 1. Merge and align identifiers into `other` from `this. If an identifier
1308/// from `this` exists in `other` then we align it. Otherwise, we assume it is a
1309/// new identifier and insert it into `other` in the same position as `this`.
1310/// 2. Add identifiers that are in `other` but not `this to `this`.
1312 assert(space.isUsingIds() && other.space.isUsingIds() &&
1313 "both relations need to have identifers to merge and align");
1314
1315 unsigned i = 0;
1316 for (const Identifier identifier : space.getIds(VarKind::Symbol)) {
1317 // Search in `other` starting at position `i` since the left of `i` is
1318 // aligned.
1319 const Identifier *findBegin =
1320 other.space.getIds(VarKind::Symbol).begin() + i;
1321 const Identifier *findEnd = other.space.getIds(VarKind::Symbol).end();
1322 const Identifier *itr = std::find(findBegin, findEnd, identifier);
1323 if (itr != findEnd) {
1324 other.swapVar(other.getVarKindOffset(VarKind::Symbol) + i,
1326 std::distance(findBegin, itr));
1327 } else {
1328 other.insertVar(VarKind::Symbol, i);
1329 other.space.setId(VarKind::Symbol, i, identifier);
1330 }
1331 ++i;
1332 }
1333
1334 for (unsigned e = other.getNumVarKind(VarKind::Symbol); i < e; ++i) {
1336 space.setId(VarKind::Symbol, i, other.space.getId(VarKind::Symbol, i));
1337 }
1338}
1339
1340/// Adds additional local ids to the sets such that they both have the union
1341/// of the local ids in each set, without changing the set of points that
1342/// lie in `this` and `other`.
1343///
1344/// To detect local ids that always take the same value, each local id is
1345/// represented as a floordiv with constant denominator in terms of other ids.
1346/// After extracting these divisions, local ids in `other` with the same
1347/// division representation as some other local id in any set are considered
1348/// duplicate and are merged.
1349///
1350/// It is possible that division representation for some local id cannot be
1351/// obtained, and thus these local ids are not considered for detecting
1352/// duplicates.
1354 IntegerRelation &relA = *this;
1355 IntegerRelation &relB = other;
1356
1357 unsigned oldALocals = relA.getNumLocalVars();
1358
1359 // Merge function that merges the local variables in both sets by treating
1360 // them as the same variable.
1361 auto merge = [&relA, &relB, oldALocals](unsigned i, unsigned j) -> bool {
1362 // We only merge from local at pos j to local at pos i, where j > i.
1363 if (i >= j)
1364 return false;
1365
1366 // If i < oldALocals, we are trying to merge duplicate divs. Since we do not
1367 // want to merge duplicates in A, we ignore this call.
1368 if (j < oldALocals)
1369 return false;
1370
1371 // Merge local at pos j into local at position i.
1374 return true;
1375 };
1376
1377 presburger::mergeLocalVars(*this, other, merge);
1378
1379 // Since we do not remove duplicate divisions in relA, this is guranteed to be
1380 // non-negative.
1381 return relA.getNumLocalVars() - oldALocals;
1382}
1383
1387
1389 DivisionRepr divs = getLocalReprs();
1390 auto merge = [this](unsigned i, unsigned j) -> bool {
1392 return true;
1393 };
1394 divs.removeDuplicateDivs(merge);
1395}
1396
1398 bool changed = true;
1399 // Repeat until we reach a fixed point.
1400 while (changed) {
1401 if (isObviouslyEmpty())
1402 return;
1403 changed = false;
1405 changed |= gaussianEliminate();
1406 changed |= removeDuplicateConstraints();
1407 }
1408 // Current set is not empty.
1409}
1410
1411/// Removes local variables using equalities. Each equality is checked if it
1412/// can be reduced to the form: `e = affine-expr`, where `e` is a local
1413/// variable and `affine-expr` is an affine expression not containing `e`.
1414/// If an equality satisfies this form, the local variable is replaced in
1415/// each constraint and then removed. The equality used to replace this local
1416/// variable is also removed.
1418 // Normalize the equality constraints to reduce coefficients of local
1419 // variables to 1 wherever possible.
1420 for (unsigned i = 0, e = getNumEqualities(); i < e; ++i)
1421 equalities.normalizeRow(i);
1422
1423 while (true) {
1424 unsigned i, e, j, f;
1425 for (i = 0, e = getNumEqualities(); i < e; ++i) {
1426 // Find a local variable to eliminate using ith equality.
1427 for (j = getNumDimAndSymbolVars(), f = getNumVars(); j < f; ++j)
1428 if (abs(atEq(i, j)) == 1)
1429 break;
1430
1431 // Local variable can be eliminated using ith equality.
1432 if (j < f)
1433 break;
1434 }
1435
1436 // No equality can be used to eliminate a local variable.
1437 if (i == e)
1438 break;
1439
1440 // Use the ith equality to eliminate the local variable from every other
1441 // constraint. Equalities are then normalized by GCD; this only affects
1442 // the ones that changed, since the others are already normalized.
1444 for (unsigned k = 0, t = getNumEqualities(); k < t; ++k)
1445 equalities.normalizeRow(k);
1446
1447 // Remove the ith equality and the found local variable.
1448 removeVar(j);
1449 removeEquality(i);
1450 }
1451}
1452
1453void IntegerRelation::convertVarKind(VarKind srcKind, unsigned varStart,
1454 unsigned varLimit, VarKind dstKind,
1455 unsigned pos) {
1456 assert(varLimit <= getNumVarKind(srcKind) && "invalid id range");
1457
1458 if (varStart >= varLimit)
1459 return;
1460
1461 unsigned srcOffset = getVarKindOffset(srcKind);
1462 unsigned dstOffset = getVarKindOffset(dstKind);
1463 unsigned convertCount = varLimit - varStart;
1464 int forwardMoveOffset = dstOffset > srcOffset ? -convertCount : 0;
1465
1466 equalities.moveColumns(srcOffset + varStart, convertCount,
1467 dstOffset + pos + forwardMoveOffset);
1468 inequalities.moveColumns(srcOffset + varStart, convertCount,
1469 dstOffset + pos + forwardMoveOffset);
1470
1471 space.convertVarKind(srcKind, varStart, varLimit - varStart, dstKind, pos);
1472}
1473
1474void IntegerRelation::addBound(BoundType type, unsigned pos,
1475 const DynamicAPInt &value) {
1476 assert(pos < getNumCols());
1477 if (type == BoundType::EQ) {
1478 unsigned row = equalities.appendExtraRow();
1479 equalities(row, pos) = 1;
1480 equalities(row, getNumCols() - 1) = -value;
1481 } else {
1482 unsigned row = inequalities.appendExtraRow();
1483 inequalities(row, pos) = type == BoundType::LB ? 1 : -1;
1484 inequalities(row, getNumCols() - 1) =
1485 type == BoundType::LB ? -value : value;
1486 }
1487}
1488
1490 const DynamicAPInt &value) {
1491 assert(type != BoundType::EQ && "EQ not implemented");
1492 assert(expr.size() == getNumCols());
1493 unsigned row = inequalities.appendExtraRow();
1494 for (unsigned i = 0, e = expr.size(); i < e; ++i)
1495 inequalities(row, i) = type == BoundType::LB ? expr[i] : -expr[i];
1496 inequalities(inequalities.getNumRows() - 1, getNumCols() - 1) +=
1497 type == BoundType::LB ? -value : value;
1498}
1499
1500/// Adds a new local variable as the floordiv of an affine function of other
1501/// variables, the coefficients of which are provided in 'dividend' and with
1502/// respect to a positive constant 'divisor'. Two constraints are added to the
1503/// system to capture equivalence with the floordiv.
1504/// q = expr floordiv c <=> c*q <= expr <= c*q + c - 1.
1505/// Returns the column position of the new local variable.
1507 const DynamicAPInt &divisor) {
1508 assert(dividend.size() == getNumCols() && "incorrect dividend size");
1509 assert(divisor > 0 && "positive divisor expected");
1510
1511 unsigned newVar = appendVar(VarKind::Local);
1512
1513 SmallVector<DynamicAPInt, 8> dividendCopy(dividend);
1514 dividendCopy.insert(dividendCopy.end() - 1, DynamicAPInt(0));
1516 getDivLowerBound(dividendCopy, divisor, dividendCopy.size() - 2));
1518 getDivUpperBound(dividendCopy, divisor, dividendCopy.size() - 2));
1519 return newVar;
1520}
1521
1523 const DynamicAPInt &modulus) {
1524 assert(exprs.size() == getNumCols() && "incorrect exprs size");
1525 assert(modulus > 0 && "positive modulus expected");
1526
1527 /// Add a local variable for q = expr floordiv modulus
1528 addLocalFloorDiv(exprs, modulus);
1529
1530 /// Add a local var to represent the result
1531 auto resultIndex = appendVar(VarKind::Local);
1532
1533 SmallVector<DynamicAPInt, 8> exprsCopy(exprs);
1534 /// Insert the two new locals before the constant
1535 /// Add locals that correspond to `q` and `result` to compute
1536 /// 0 = (expr - modulus * q) - result
1537 exprsCopy.insert(exprsCopy.end() - 1,
1538 {DynamicAPInt(-modulus), DynamicAPInt(-1)});
1539 addEquality(exprsCopy);
1540 return resultIndex;
1541}
1542
1543int IntegerRelation::findEqualityToConstant(unsigned pos, bool symbolic) const {
1544 assert(pos < getNumVars() && "invalid position");
1545 for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
1546 DynamicAPInt v = atEq(r, pos);
1547 if (v * v != 1)
1548 continue;
1549 unsigned c;
1550 unsigned f = symbolic ? getNumDimVars() : getNumVars();
1551 // This checks for zeros in all positions other than 'pos' in [0, f)
1552 for (c = 0; c < f; c++) {
1553 if (c == pos)
1554 continue;
1555 if (atEq(r, c) != 0) {
1556 // Dependent on another variable.
1557 break;
1558 }
1559 }
1560 if (c == f)
1561 // Equality is free of other variables.
1562 return r;
1563 }
1564 return -1;
1565}
1566
1567LogicalResult IntegerRelation::constantFoldVar(unsigned pos) {
1568 assert(pos < getNumVars() && "invalid position");
1569 int rowIdx;
1570 if ((rowIdx = findEqualityToConstant(pos)) == -1)
1571 return failure();
1572
1573 // atEq(rowIdx, pos) is either -1 or 1.
1574 assert(atEq(rowIdx, pos) * atEq(rowIdx, pos) == 1);
1575 DynamicAPInt constVal = -atEq(rowIdx, getNumCols() - 1) / atEq(rowIdx, pos);
1576 setAndEliminate(pos, constVal);
1577 return success();
1578}
1579
1580void IntegerRelation::constantFoldVarRange(unsigned pos, unsigned num) {
1581 for (unsigned s = pos, t = pos, e = pos + num; s < e; s++) {
1582 if (constantFoldVar(t).failed())
1583 t++;
1584 }
1585}
1586
1587/// Returns a non-negative constant bound on the extent (upper bound - lower
1588/// bound) of the specified variable if it is found to be a constant; returns
1589/// std::nullopt if it's not a constant. This methods treats symbolic variables
1590/// specially, i.e., it looks for constant differences between affine
1591/// expressions involving only the symbolic variables. See comments at function
1592/// definition for example. 'lb', if provided, is set to the lower bound
1593/// associated with the constant difference. Note that 'lb' is purely symbolic
1594/// and thus will contain the coefficients of the symbolic variables and the
1595/// constant coefficient.
1596// Egs: 0 <= i <= 15, return 16.
1597// s0 + 2 <= i <= s0 + 17, returns 16. (s0 has to be a symbol)
1598// s0 + s1 + 16 <= d0 <= s0 + s1 + 31, returns 16.
1599// s0 - 7 <= 8*j <= s0 returns 1 with lb = s0, lbDivisor = 8 (since lb =
1600// ceil(s0 - 7 / 8) = floor(s0 / 8)).
1602 unsigned pos, SmallVectorImpl<DynamicAPInt> *lb,
1603 DynamicAPInt *boundFloorDivisor, SmallVectorImpl<DynamicAPInt> *ub,
1604 unsigned *minLbPos, unsigned *minUbPos) const {
1605 assert(pos < getNumDimVars() && "Invalid variable position");
1606
1607 // Find an equality for 'pos'^th variable that equates it to some function
1608 // of the symbolic variables (+ constant).
1609 int eqPos = findEqualityToConstant(pos, /*symbolic=*/true);
1610 if (eqPos != -1) {
1611 auto eq = getEquality(eqPos);
1612 // If the equality involves a local var, we do not handle it.
1613 // FlatLinearConstraints can instead be used to detect the local variable as
1614 // an affine function (potentially div/mod) of other variables and use
1615 // affine expressions/maps to represent output.
1616 if (!std::all_of(eq.begin() + getNumDimAndSymbolVars(), eq.end() - 1,
1617 [](const DynamicAPInt &coeff) { return coeff == 0; }))
1618 return std::nullopt;
1619
1620 // This variable can only take a single value.
1621 if (lb) {
1622 // Set lb to that symbolic value.
1623 lb->resize(getNumSymbolVars() + 1);
1624 if (ub)
1625 ub->resize(getNumSymbolVars() + 1);
1626 for (unsigned c = 0, f = getNumSymbolVars() + 1; c < f; c++) {
1627 DynamicAPInt v = atEq(eqPos, pos);
1628 // atEq(eqRow, pos) is either -1 or 1.
1629 assert(v * v == 1);
1630 (*lb)[c] = v < 0 ? atEq(eqPos, getNumDimVars() + c) / -v
1631 : -atEq(eqPos, getNumDimVars() + c) / v;
1632 // Since this is an equality, ub = lb.
1633 if (ub)
1634 (*ub)[c] = (*lb)[c];
1635 }
1636 assert(boundFloorDivisor &&
1637 "both lb and divisor or none should be provided");
1638 *boundFloorDivisor = 1;
1639 }
1640 if (minLbPos)
1641 *minLbPos = eqPos;
1642 if (minUbPos)
1643 *minUbPos = eqPos;
1644 return DynamicAPInt(1);
1645 }
1646
1647 // Check if the variable appears at all in any of the inequalities.
1648 unsigned r, e;
1649 for (r = 0, e = getNumInequalities(); r < e; r++) {
1650 if (atIneq(r, pos) != 0)
1651 break;
1652 }
1653 if (r == e)
1654 // If it doesn't, there isn't a bound on it.
1655 return std::nullopt;
1656
1657 // Positions of constraints that are lower/upper bounds on the variable.
1658 SmallVector<unsigned, 4> lbIndices, ubIndices;
1659
1660 // Gather all symbolic lower bounds and upper bounds of the variable, i.e.,
1661 // the bounds can only involve symbolic (and local) variables. Since the
1662 // canonical form c_1*x_1 + c_2*x_2 + ... + c_0 >= 0, a constraint is a lower
1663 // bound for x_i if c_i >= 1, and an upper bound if c_i <= -1.
1664 getLowerAndUpperBoundIndices(pos, &lbIndices, &ubIndices,
1665 /*eqIndices=*/nullptr, /*offset=*/0,
1666 /*num=*/getNumDimVars());
1667
1668 std::optional<DynamicAPInt> minDiff;
1669 unsigned minLbPosition = 0, minUbPosition = 0;
1670 for (auto ubPos : ubIndices) {
1671 for (auto lbPos : lbIndices) {
1672 // Look for a lower bound and an upper bound that only differ by a
1673 // constant, i.e., pairs of the form 0 <= c_pos - f(c_i's) <= diffConst.
1674 // For example, if ii is the pos^th variable, we are looking for
1675 // constraints like ii >= i, ii <= ii + 50, 50 being the difference. The
1676 // minimum among all such constant differences is kept since that's the
1677 // constant bounding the extent of the pos^th variable.
1678 unsigned j, e;
1679 for (j = 0, e = getNumCols() - 1; j < e; j++)
1680 if (atIneq(ubPos, j) != -atIneq(lbPos, j)) {
1681 break;
1682 }
1683 if (j < getNumCols() - 1)
1684 continue;
1685 DynamicAPInt diff = ceilDiv(atIneq(ubPos, getNumCols() - 1) +
1686 atIneq(lbPos, getNumCols() - 1) + 1,
1687 atIneq(lbPos, pos));
1688 // This bound is non-negative by definition.
1689 diff = std::max<DynamicAPInt>(diff, DynamicAPInt(0));
1690 if (minDiff == std::nullopt || diff < minDiff) {
1691 minDiff = diff;
1692 minLbPosition = lbPos;
1693 minUbPosition = ubPos;
1694 }
1695 }
1696 }
1697 if (lb && minDiff) {
1698 // Set lb to the symbolic lower bound.
1699 lb->resize(getNumSymbolVars() + 1);
1700 if (ub)
1701 ub->resize(getNumSymbolVars() + 1);
1702 // The lower bound is the ceildiv of the lb constraint over the coefficient
1703 // of the variable at 'pos'. We express the ceildiv equivalently as a floor
1704 // for uniformity. For eg., if the lower bound constraint was: 32*d0 - N +
1705 // 31 >= 0, the lower bound for d0 is ceil(N - 31, 32), i.e., floor(N, 32).
1706 *boundFloorDivisor = atIneq(minLbPosition, pos);
1707 assert(*boundFloorDivisor == -atIneq(minUbPosition, pos));
1708 for (unsigned c = 0, e = getNumSymbolVars() + 1; c < e; c++) {
1709 (*lb)[c] = -atIneq(minLbPosition, getNumDimVars() + c);
1710 }
1711 if (ub) {
1712 for (unsigned c = 0, e = getNumSymbolVars() + 1; c < e; c++)
1713 (*ub)[c] = atIneq(minUbPosition, getNumDimVars() + c);
1714 }
1715 // The lower bound leads to a ceildiv while the upper bound is a floordiv
1716 // whenever the coefficient at pos != 1. ceildiv (val / d) = floordiv (val +
1717 // d - 1 / d); hence, the addition of 'atIneq(minLbPosition, pos) - 1' to
1718 // the constant term for the lower bound.
1719 (*lb)[getNumSymbolVars()] += atIneq(minLbPosition, pos) - 1;
1720 }
1721 if (minLbPos)
1722 *minLbPos = minLbPosition;
1723 if (minUbPos)
1724 *minUbPos = minUbPosition;
1725 return minDiff;
1726}
1727
1729 llvm::DenseSet<unsigned> relatedCols({pos}), relatedRows;
1730
1731 // Early exit if constraints is empty.
1732 unsigned numConstraints = getNumConstraints();
1733 if (numConstraints == 0)
1734 return;
1735
1736 llvm::SmallVector<unsigned> rowStack, colStack({pos});
1737 // The following code performs a graph traversal, starting from the target
1738 // variable, to identify all variables(recorded in relatedCols) and
1739 // constraints (recorded in relatedRows) belonging to the same connected
1740 // component.
1741 while (!rowStack.empty() || !colStack.empty()) {
1742 if (!rowStack.empty()) {
1743 unsigned currentRow = rowStack.pop_back_val();
1744 // Push all variable that accociated to this constraints to relatedCols
1745 // and colStack.
1746 for (unsigned colIndex = 0; colIndex < getNumVars(); ++colIndex) {
1747 if (atConstraint(currentRow, colIndex) != 0 &&
1748 relatedCols.insert(colIndex).second) {
1749 colStack.push_back(colIndex);
1750 }
1751 }
1752 } else {
1753 unsigned currentCol = colStack.pop_back_val();
1754 // Push all constraints that are associated with this variable to related
1755 // rows and the row stack.
1756 for (unsigned rowIndex = 0; rowIndex < numConstraints; ++rowIndex) {
1757 if (atConstraint(rowIndex, currentCol) != 0 &&
1758 relatedRows.insert(rowIndex).second) {
1759 rowStack.push_back(rowIndex);
1760 }
1761 }
1762 }
1763 }
1764
1765 // Prune all constraints not related to target variable.
1766 for (int constraintId = numConstraints - 1; constraintId >= 0;
1767 --constraintId) {
1768 if (!relatedRows.contains(constraintId))
1769 removeConstraint((unsigned)constraintId);
1770 }
1771}
1772
1773template <bool isLower>
1774std::optional<DynamicAPInt>
1776 assert(pos < getNumVars() && "invalid position");
1777 // Project to 'pos'.
1778 // Prune orthogonal constraints to reduce unnecessary computations and
1779 // accelerate the bound computation.
1781 projectOut(0, pos);
1782
1783 // After projecting out values, more orthogonal constraints may be exposed.
1784 // Prune these orthogonal constraints again.
1786 projectOut(1, getNumVars() - 1);
1787 // Check if there's an equality equating the '0'^th variable to a constant.
1788 int eqRowIdx = findEqualityToConstant(/*pos=*/0, /*symbolic=*/false);
1789 if (eqRowIdx != -1)
1790 // atEq(rowIdx, 0) is either -1 or 1.
1791 return -atEq(eqRowIdx, getNumCols() - 1) / atEq(eqRowIdx, 0);
1792
1793 // Check if the variable appears at all in any of the inequalities.
1794 unsigned r, e;
1795 for (r = 0, e = getNumInequalities(); r < e; r++) {
1796 if (atIneq(r, 0) != 0)
1797 break;
1798 }
1799 if (r == e)
1800 // If it doesn't, there isn't a bound on it.
1801 return std::nullopt;
1802
1803 std::optional<DynamicAPInt> minOrMaxConst;
1804
1805 // Take the max across all const lower bounds (or min across all constant
1806 // upper bounds).
1807 for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
1808 if (isLower) {
1809 if (atIneq(r, 0) <= 0)
1810 // Not a lower bound.
1811 continue;
1812 } else if (atIneq(r, 0) >= 0) {
1813 // Not an upper bound.
1814 continue;
1815 }
1816 unsigned c, f;
1817 for (c = 0, f = getNumCols() - 1; c < f; c++)
1818 if (c != 0 && atIneq(r, c) != 0)
1819 break;
1820 if (c < getNumCols() - 1)
1821 // Not a constant bound.
1822 continue;
1823
1824 DynamicAPInt boundConst =
1825 isLower ? ceilDiv(-atIneq(r, getNumCols() - 1), atIneq(r, 0))
1826 : floorDiv(atIneq(r, getNumCols() - 1), -atIneq(r, 0));
1827 if (isLower) {
1828 if (minOrMaxConst == std::nullopt || boundConst > minOrMaxConst)
1829 minOrMaxConst = boundConst;
1830 } else {
1831 if (minOrMaxConst == std::nullopt || boundConst < minOrMaxConst)
1832 minOrMaxConst = boundConst;
1833 }
1834 }
1835 return minOrMaxConst;
1836}
1837
1838std::optional<DynamicAPInt>
1840 if (type == BoundType::LB)
1841 return IntegerRelation(*this)
1842 .computeConstantLowerOrUpperBound</*isLower=*/true>(pos);
1843 if (type == BoundType::UB)
1844 return IntegerRelation(*this)
1845 .computeConstantLowerOrUpperBound</*isLower=*/false>(pos);
1846
1847 assert(type == BoundType::EQ && "expected EQ");
1848 std::optional<DynamicAPInt> lb =
1849 IntegerRelation(*this).computeConstantLowerOrUpperBound</*isLower=*/true>(
1850 pos);
1851 std::optional<DynamicAPInt> ub =
1852 IntegerRelation(*this)
1853 .computeConstantLowerOrUpperBound</*isLower=*/false>(pos);
1854 return (lb && ub && *lb == *ub) ? std::optional<DynamicAPInt>(*ub)
1855 : std::nullopt;
1856}
1857
1858// A simple (naive and conservative) check for hyper-rectangularity.
1859bool IntegerRelation::isHyperRectangular(unsigned pos, unsigned num) const {
1860 assert(pos < getNumCols() - 1);
1861 // Check for two non-zero coefficients in the range [pos, pos + sum).
1862 for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
1863 unsigned sum = 0;
1864 for (unsigned c = pos; c < pos + num; c++) {
1865 if (atIneq(r, c) != 0)
1866 sum++;
1867 }
1868 if (sum > 1)
1869 return false;
1870 }
1871 for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
1872 unsigned sum = 0;
1873 for (unsigned c = pos; c < pos + num; c++) {
1874 if (atEq(r, c) != 0)
1875 sum++;
1876 }
1877 if (sum > 1)
1878 return false;
1879 }
1880 return true;
1881}
1882
1883/// Removes duplicate constraints, trivially true constraints, and constraints
1884/// that can be detected as redundant as a result of differing only in their
1885/// constant term part. A constraint of the form <non-negative constant> >= 0 is
1886/// considered trivially true.
1887// Uses a DenseSet to hash and detect duplicates followed by a linear scan to
1888// remove duplicates in place.
1892
1893 // A map used to detect redundancy stemming from constraints that only differ
1894 // in their constant term. The value stored is <row position, const term>
1895 // for a given row.
1896 SmallDenseMap<ArrayRef<DynamicAPInt>, std::pair<unsigned, DynamicAPInt>>
1897 rowsWithoutConstTerm;
1898
1899 // Check if constraint is of the form <non-negative-constant> >= 0.
1900 auto isTriviallyValid = [&](unsigned r) -> bool {
1901 for (unsigned c = 0, e = getNumCols() - 1; c < e; c++) {
1902 if (atIneq(r, c) != 0)
1903 return false;
1904 }
1905 return atIneq(r, getNumCols() - 1) >= 0;
1906 };
1907
1908 // Detect and mark redundant constraints.
1909 SmallVector<bool, 256> redunIneq(getNumInequalities(), false);
1910 for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
1911 DynamicAPInt *rowStart = &inequalities(r, 0);
1912 if (isTriviallyValid(r)) {
1913 redunIneq[r] = true;
1914 continue;
1915 }
1916
1917 // Among constraints that only differ in the constant term part, mark
1918 // everything other than the one with the smallest constant term redundant.
1919 // (eg: among i - 16j - 5 >= 0, i - 16j - 1 >=0, i - 16j - 7 >= 0, the
1920 // former two are redundant).
1921 DynamicAPInt constTerm = atIneq(r, getNumCols() - 1);
1922 auto rowWithoutConstTerm =
1923 ArrayRef<DynamicAPInt>(rowStart, getNumCols() - 1);
1924 const auto &ret =
1925 rowsWithoutConstTerm.insert({rowWithoutConstTerm, {r, constTerm}});
1926 if (!ret.second) {
1927 // Check if the other constraint has a higher constant term.
1928 auto &val = ret.first->second;
1929 if (val.second > constTerm) {
1930 // The stored row is redundant. Mark it so, and update with this one.
1931 redunIneq[val.first] = true;
1932 val = {r, constTerm};
1933 } else {
1934 // The one stored makes this one redundant.
1935 redunIneq[r] = true;
1936 }
1937 }
1938 }
1939
1940 // Scan to get rid of all rows marked redundant, in-place.
1941 unsigned pos = 0;
1942 for (unsigned r = 0, e = getNumInequalities(); r < e; r++)
1943 if (!redunIneq[r])
1944 inequalities.copyRow(r, pos++);
1945
1946 inequalities.resizeVertically(pos);
1947
1948 // TODO: consider doing this for equalities as well, but probably not worth
1949 // the savings.
1950}
1951
1952#undef DEBUG_TYPE
1953#define DEBUG_TYPE "fm"
1954
1955/// Eliminates variable at the specified position using Fourier-Motzkin
1956/// variable elimination. This technique is exact for rational spaces but
1957/// conservative (in "rare" cases) for integer spaces. The operation corresponds
1958/// to a projection operation yielding the (convex) set of integer points
1959/// contained in the rational shadow of the set. An emptiness test that relies
1960/// on this method will guarantee emptiness, i.e., it disproves the existence of
1961/// a solution if it says it's empty.
1962/// If a non-null isResultIntegerExact is passed, it is set to true if the
1963/// result is also integer exact. If it's set to false, the obtained solution
1964/// *may* not be exact, i.e., it may contain integer points that do not have an
1965/// integer pre-image in the original set.
1966///
1967/// Eg:
1968/// j >= 0, j <= i + 1
1969/// i >= 0, i <= N + 1
1970/// Eliminating i yields,
1971/// j >= 0, 0 <= N + 1, j - 1 <= N + 1
1972///
1973/// If darkShadow = true, this method computes the dark shadow on elimination;
1974/// the dark shadow is a convex integer subset of the exact integer shadow. A
1975/// non-empty dark shadow proves the existence of an integer solution. The
1976/// elimination in such a case could however be an under-approximation, and thus
1977/// should not be used for scanning sets or used by itself for dependence
1978/// checking.
1979///
1980/// Eg: 2-d set, * represents grid points, 'o' represents a point in the set.
1981/// ^
1982/// |
1983/// | * * * * o o
1984/// i | * * o o o o
1985/// | o * * * * *
1986/// --------------->
1987/// j ->
1988///
1989/// Eliminating i from this system (projecting on the j dimension):
1990/// rational shadow / integer light shadow: 1 <= j <= 6
1991/// dark shadow: 3 <= j <= 6
1992/// exact integer shadow: j = 1 \union 3 <= j <= 6
1993/// holes/splinters: j = 2
1994///
1995/// darkShadow = false, isResultIntegerExact = nullptr are default values.
1996// TODO: a slight modification to yield dark shadow version of FM (tightened),
1997// which can prove the existence of a solution if there is one.
1998void IntegerRelation::fourierMotzkinEliminate(unsigned pos, bool darkShadow,
1999 bool *isResultIntegerExact) {
2000 LDBG() << "FM input (eliminate pos " << pos << "):";
2001 LLVM_DEBUG(dump());
2002 assert(pos < getNumVars() && "invalid position");
2003 assert(hasConsistentState());
2004
2005 // Check if this variable can be eliminated through a substitution.
2006 for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
2007 if (atEq(r, pos) != 0) {
2008 // Use Gaussian elimination here (since we have an equality).
2009 LogicalResult ret = gaussianEliminateVar(pos);
2010 (void)ret;
2011 assert(ret.succeeded() && "Gaussian elimination guaranteed to succeed");
2012 LDBG() << "FM output (through Gaussian elimination):";
2013 LLVM_DEBUG(dump());
2014 return;
2015 }
2016 }
2017
2018 // A fast linear time tightening.
2020
2021 // Check if the variable appears at all in any of the inequalities.
2022 if (isColZero(pos)) {
2023 // If it doesn't appear, just remove the column and return.
2024 // TODO: refactor removeColumns to use it from here.
2025 removeVar(pos);
2026 LDBG() << "FM output:";
2027 LLVM_DEBUG(dump());
2028 return;
2029 }
2030
2031 // Positions of constraints that are lower bounds on the variable.
2032 SmallVector<unsigned, 4> lbIndices;
2033 // Positions of constraints that are lower bounds on the variable.
2034 SmallVector<unsigned, 4> ubIndices;
2035 // Positions of constraints that do not involve the variable.
2036 std::vector<unsigned> nbIndices;
2037 nbIndices.reserve(getNumInequalities());
2038
2039 // Gather all lower bounds and upper bounds of the variable. Since the
2040 // canonical form c_1*x_1 + c_2*x_2 + ... + c_0 >= 0, a constraint is a lower
2041 // bound for x_i if c_i >= 1, and an upper bound if c_i <= -1.
2042 for (unsigned r = 0, e = getNumInequalities(); r < e; r++) {
2043 if (atIneq(r, pos) == 0) {
2044 // Var does not appear in bound.
2045 nbIndices.emplace_back(r);
2046 } else if (atIneq(r, pos) >= 1) {
2047 // Lower bound.
2048 lbIndices.emplace_back(r);
2049 } else {
2050 // Upper bound.
2051 ubIndices.emplace_back(r);
2052 }
2053 }
2054
2055 PresburgerSpace newSpace = getSpace();
2056 VarKind idKindRemove = newSpace.getVarKindAt(pos);
2057 unsigned relativePos = pos - newSpace.getVarKindOffset(idKindRemove);
2058 newSpace.removeVarRange(idKindRemove, relativePos, relativePos + 1);
2059
2060 /// Create the new system which has one variable less.
2061 IntegerRelation newRel(lbIndices.size() * ubIndices.size() + nbIndices.size(),
2062 getNumEqualities(), getNumCols() - 1, newSpace);
2063
2064 // This will be used to check if the elimination was integer exact.
2065 bool allLCMsAreOne = true;
2066
2067 // Let x be the variable we are eliminating.
2068 // For each lower bound, lb <= c_l*x, and each upper bound c_u*x <= ub, (note
2069 // that c_l, c_u >= 1) we have:
2070 // lb*lcm(c_l, c_u)/c_l <= lcm(c_l, c_u)*x <= ub*lcm(c_l, c_u)/c_u
2071 // We thus generate a constraint:
2072 // lcm(c_l, c_u)/c_l*lb <= lcm(c_l, c_u)/c_u*ub.
2073 // Note if c_l = c_u = 1, all integer points captured by the resulting
2074 // constraint correspond to integer points in the original system (i.e., they
2075 // have integer pre-images). Hence, if the lcm's are all 1, the elimination is
2076 // integer exact.
2077 for (auto ubPos : ubIndices) {
2078 for (auto lbPos : lbIndices) {
2080 ineq.reserve(newRel.getNumCols());
2081 DynamicAPInt lbCoeff = atIneq(lbPos, pos);
2082 // Note that in the comments above, ubCoeff is the negation of the
2083 // coefficient in the canonical form as the view taken here is that of the
2084 // term being moved to the other size of '>='.
2085 DynamicAPInt ubCoeff = -atIneq(ubPos, pos);
2086 // TODO: refactor this loop to avoid all branches inside.
2087 for (unsigned l = 0, e = getNumCols(); l < e; l++) {
2088 if (l == pos)
2089 continue;
2090 assert(lbCoeff >= 1 && ubCoeff >= 1 && "bounds wrongly identified");
2091 DynamicAPInt lcm = llvm::lcm(lbCoeff, ubCoeff);
2092 ineq.emplace_back(atIneq(ubPos, l) * (lcm / ubCoeff) +
2093 atIneq(lbPos, l) * (lcm / lbCoeff));
2094 assert(lcm > 0 && "lcm should be positive!");
2095 if (lcm != 1)
2096 allLCMsAreOne = false;
2097 }
2098 if (darkShadow) {
2099 // The dark shadow is a convex subset of the exact integer shadow. If
2100 // there is a point here, it proves the existence of a solution.
2101 ineq[ineq.size() - 1] += lbCoeff * ubCoeff - lbCoeff - ubCoeff + 1;
2102 }
2103 // TODO: we need to have a way to add inequalities in-place in
2104 // IntegerRelation instead of creating and copying over.
2105 newRel.addInequality(ineq);
2106 }
2107 }
2108
2109 LDBG() << "FM isResultIntegerExact: " << allLCMsAreOne;
2110 if (allLCMsAreOne && isResultIntegerExact)
2111 *isResultIntegerExact = true;
2112
2113 // Copy over the constraints not involving this variable.
2114 for (auto nbPos : nbIndices) {
2116 ineq.reserve(getNumCols() - 1);
2117 for (unsigned l = 0, e = getNumCols(); l < e; l++) {
2118 if (l == pos)
2119 continue;
2120 ineq.emplace_back(atIneq(nbPos, l));
2121 }
2122 newRel.addInequality(ineq);
2123 }
2124
2125 assert(newRel.getNumConstraints() ==
2126 lbIndices.size() * ubIndices.size() + nbIndices.size());
2127
2128 // Copy over the equalities.
2129 for (unsigned r = 0, e = getNumEqualities(); r < e; r++) {
2131 eq.reserve(newRel.getNumCols());
2132 for (unsigned l = 0, e = getNumCols(); l < e; l++) {
2133 if (l == pos)
2134 continue;
2135 eq.emplace_back(atEq(r, l));
2136 }
2137 newRel.addEquality(eq);
2138 }
2139
2140 // GCD tightening and normalization allows detection of more trivially
2141 // redundant constraints.
2142 newRel.gcdTightenInequalities();
2144 newRel.removeTrivialRedundancy();
2145 clearAndCopyFrom(newRel);
2146 LDBG() << "FM output:";
2147 LLVM_DEBUG(dump());
2148}
2149
2150#undef DEBUG_TYPE
2151#define DEBUG_TYPE "presburger"
2152
2153void IntegerRelation::projectOut(unsigned pos, unsigned num) {
2154 if (num == 0)
2155 return;
2156
2157 // 'pos' can be at most getNumCols() - 2 if num > 0.
2158 assert((getNumCols() < 2 || pos <= getNumCols() - 2) && "invalid position");
2159 assert(pos + num < getNumCols() && "invalid range");
2160
2161 // Eliminate as many variables as possible using Gaussian elimination.
2162 unsigned currentPos = pos;
2163 unsigned numToEliminate = num;
2164 unsigned numGaussianEliminated = 0;
2165
2166 while (currentPos < getNumVars()) {
2167 unsigned curNumEliminated =
2168 gaussianEliminateVars(currentPos, currentPos + numToEliminate);
2169 ++currentPos;
2170 numToEliminate -= curNumEliminated + 1;
2171 numGaussianEliminated += curNumEliminated;
2172 }
2173
2174 // Eliminate the remaining using Fourier-Motzkin.
2175 for (unsigned i = 0; i < num - numGaussianEliminated; i++) {
2176 unsigned numToEliminate = num - numGaussianEliminated - i;
2178 getBestVarToEliminate(*this, pos, pos + numToEliminate));
2179 }
2180
2181 // Fast/trivial simplifications.
2183 // Normalize constraints after tightening since the latter impacts this, but
2184 // not the other way round.
2186}
2187
2188namespace {
2189
2190enum BoundCmpResult { Greater, Less, Equal, Unknown };
2191
2192/// Compares two affine bounds whose coefficients are provided in 'first' and
2193/// 'second'. The last coefficient is the constant term.
2194static BoundCmpResult compareBounds(ArrayRef<DynamicAPInt> a,
2196 assert(a.size() == b.size());
2197
2198 // For the bounds to be comparable, their corresponding variable
2199 // coefficients should be equal; the constant terms are then compared to
2200 // determine less/greater/equal.
2201
2202 if (!std::equal(a.begin(), a.end() - 1, b.begin()))
2203 return Unknown;
2204
2205 if (a.back() == b.back())
2206 return Equal;
2207
2208 return a.back() < b.back() ? Less : Greater;
2209}
2210} // namespace
2211
2212// Returns constraints that are common to both A & B.
2214 const IntegerRelation &b, IntegerRelation &c) {
2215 c = IntegerRelation(a.getSpace());
2216 // a naive O(n^2) check should be enough here given the input sizes.
2217 for (unsigned r = 0, e = a.getNumInequalities(); r < e; ++r) {
2218 for (unsigned s = 0, f = b.getNumInequalities(); s < f; ++s) {
2219 if (a.getInequality(r) == b.getInequality(s)) {
2221 break;
2222 }
2223 }
2224 }
2225 for (unsigned r = 0, e = a.getNumEqualities(); r < e; ++r) {
2226 for (unsigned s = 0, f = b.getNumEqualities(); s < f; ++s) {
2227 if (a.getEquality(r) == b.getEquality(s)) {
2228 c.addEquality(a.getEquality(r));
2229 break;
2230 }
2231 }
2232 }
2233}
2234
2235// Computes the bounding box with respect to 'other' by finding the min of the
2236// lower bounds and the max of the upper bounds along each of the dimensions.
2237LogicalResult
2239 assert(space.isEqual(otherCst.getSpace()) && "Spaces should match.");
2240 assert(getNumLocalVars() == 0 && "local ids not supported yet here");
2241
2242 // Get the constraints common to both systems; these will be added as is to
2243 // the union.
2245 getCommonConstraints(*this, otherCst, commonCst);
2246
2247 std::vector<SmallVector<DynamicAPInt, 8>> boundingLbs;
2248 std::vector<SmallVector<DynamicAPInt, 8>> boundingUbs;
2249 boundingLbs.reserve(2 * getNumDimVars());
2250 boundingUbs.reserve(2 * getNumDimVars());
2251
2252 // To hold lower and upper bounds for each dimension.
2253 SmallVector<DynamicAPInt, 4> lb, otherLb, ub, otherUb;
2254 // To compute min of lower bounds and max of upper bounds for each dimension.
2257 // To compute final new lower and upper bounds for the union.
2259
2260 DynamicAPInt lbFloorDivisor, otherLbFloorDivisor;
2261 for (unsigned d = 0, e = getNumDimVars(); d < e; ++d) {
2262 auto extent = getConstantBoundOnDimSize(d, &lb, &lbFloorDivisor, &ub);
2263 if (!extent.has_value())
2264 // TODO: symbolic extents when necessary.
2265 // TODO: handle union if a dimension is unbounded.
2266 return failure();
2267
2268 auto otherExtent = otherCst.getConstantBoundOnDimSize(
2269 d, &otherLb, &otherLbFloorDivisor, &otherUb);
2270 if (!otherExtent.has_value() || lbFloorDivisor != otherLbFloorDivisor)
2271 // TODO: symbolic extents when necessary.
2272 return failure();
2273
2274 assert(lbFloorDivisor > 0 && "divisor always expected to be positive");
2275
2276 auto res = compareBounds(lb, otherLb);
2277 // Identify min.
2278 if (res == BoundCmpResult::Less || res == BoundCmpResult::Equal) {
2279 minLb = lb;
2280 // Since the divisor is for a floordiv, we need to convert to ceildiv,
2281 // i.e., i >= expr floordiv div <=> i >= (expr - div + 1) ceildiv div <=>
2282 // div * i >= expr - div + 1.
2283 minLb.back() -= lbFloorDivisor - 1;
2284 } else if (res == BoundCmpResult::Greater) {
2285 minLb = otherLb;
2286 minLb.back() -= otherLbFloorDivisor - 1;
2287 } else {
2288 // Uncomparable - check for constant lower/upper bounds.
2289 auto constLb = getConstantBound(BoundType::LB, d);
2290 auto constOtherLb = otherCst.getConstantBound(BoundType::LB, d);
2291 if (!constLb.has_value() || !constOtherLb.has_value())
2292 return failure();
2293 llvm::fill(minLb, 0);
2294 minLb.back() = std::min(*constLb, *constOtherLb);
2295 }
2296
2297 // Do the same for ub's but max of upper bounds. Identify max.
2298 auto uRes = compareBounds(ub, otherUb);
2299 if (uRes == BoundCmpResult::Greater || uRes == BoundCmpResult::Equal) {
2300 maxUb = ub;
2301 } else if (uRes == BoundCmpResult::Less) {
2302 maxUb = otherUb;
2303 } else {
2304 // Uncomparable - check for constant lower/upper bounds.
2305 auto constUb = getConstantBound(BoundType::UB, d);
2306 auto constOtherUb = otherCst.getConstantBound(BoundType::UB, d);
2307 if (!constUb.has_value() || !constOtherUb.has_value())
2308 return failure();
2309 llvm::fill(maxUb, 0);
2310 maxUb.back() = std::max(*constUb, *constOtherUb);
2311 }
2312
2313 llvm::fill(newLb, 0);
2314 llvm::fill(newUb, 0);
2315
2316 // The divisor for lb, ub, otherLb, otherUb at this point is lbDivisor,
2317 // and so it's the divisor for newLb and newUb as well.
2318 newLb[d] = lbFloorDivisor;
2319 newUb[d] = -lbFloorDivisor;
2320 // Copy over the symbolic part + constant term.
2321 llvm::copy(minLb, newLb.begin() + getNumDimVars());
2322 std::transform(newLb.begin() + getNumDimVars(), newLb.end(),
2323 newLb.begin() + getNumDimVars(),
2324 std::negate<DynamicAPInt>());
2325 llvm::copy(maxUb, newUb.begin() + getNumDimVars());
2326
2327 boundingLbs.emplace_back(newLb);
2328 boundingUbs.emplace_back(newUb);
2329 }
2330
2331 // Clear all constraints and add the lower/upper bounds for the bounding box.
2333 for (unsigned d = 0, e = getNumDimVars(); d < e; ++d) {
2334 addInequality(boundingLbs[d]);
2335 addInequality(boundingUbs[d]);
2336 }
2337
2338 // Add the constraints that were common to both systems.
2339 append(commonCst);
2341
2342 // TODO: copy over pure symbolic constraints from this and 'other' over to the
2343 // union (since the above are just the union along dimensions); we shouldn't
2344 // be discarding any other constraints on the symbols.
2345
2346 return success();
2347}
2348
2349bool IntegerRelation::isColZero(unsigned pos) const {
2350 return !findConstraintWithNonZeroAt(pos, /*isEq=*/false) &&
2351 !findConstraintWithNonZeroAt(pos, /*isEq=*/true);
2352}
2353
2354/// Find positions of inequalities and equalities that do not have a coefficient
2355/// for [pos, pos + num) variables.
2356static void getIndependentConstraints(const IntegerRelation &cst, unsigned pos,
2357 unsigned num,
2358 SmallVectorImpl<unsigned> &nbIneqIndices,
2359 SmallVectorImpl<unsigned> &nbEqIndices) {
2360 assert(pos < cst.getNumVars() && "invalid start position");
2361 assert(pos + num <= cst.getNumVars() && "invalid limit");
2362
2363 for (unsigned r = 0, e = cst.getNumInequalities(); r < e; r++) {
2364 // The bounds are to be independent of [offset, offset + num) columns.
2365 unsigned c;
2366 for (c = pos; c < pos + num; ++c) {
2367 if (cst.atIneq(r, c) != 0)
2368 break;
2369 }
2370 if (c == pos + num)
2371 nbIneqIndices.emplace_back(r);
2372 }
2373
2374 for (unsigned r = 0, e = cst.getNumEqualities(); r < e; r++) {
2375 // The bounds are to be independent of [offset, offset + num) columns.
2376 unsigned c;
2377 for (c = pos; c < pos + num; ++c) {
2378 if (cst.atEq(r, c) != 0)
2379 break;
2380 }
2381 if (c == pos + num)
2382 nbEqIndices.emplace_back(r);
2383 }
2384}
2385
2386void IntegerRelation::removeIndependentConstraints(unsigned pos, unsigned num) {
2387 assert(pos + num <= getNumVars() && "invalid range");
2388
2389 // Remove constraints that are independent of these variables.
2390 SmallVector<unsigned, 4> nbIneqIndices, nbEqIndices;
2391 getIndependentConstraints(*this, /*pos=*/0, num, nbIneqIndices, nbEqIndices);
2392
2393 // Iterate in reverse so that indices don't have to be updated.
2394 // TODO: This method can be made more efficient (because removal of each
2395 // inequality leads to much shifting/copying in the underlying buffer).
2396 for (auto nbIndex : llvm::reverse(nbIneqIndices))
2397 removeInequality(nbIndex);
2398 for (auto nbIndex : llvm::reverse(nbEqIndices))
2399 removeEquality(nbIndex);
2400}
2401
2403 IntegerRelation copyRel = *this;
2404
2405 // Convert Range variables to Local variables.
2408
2409 // Convert Domain variables to SetDim(Range) variables.
2412
2413 return IntegerPolyhedron(std::move(copyRel));
2414}
2415
2417 bool changed = false;
2418 SmallDenseMap<ArrayRef<DynamicAPInt>, unsigned> hashTable;
2419 unsigned ineqs = getNumInequalities(), cols = getNumCols();
2420
2421 if (ineqs <= 1)
2422 return changed;
2423
2424 // Check if the non-constant part of the constraint is the same.
2425 ArrayRef<DynamicAPInt> row = getInequality(0).drop_back();
2426 hashTable.insert({row, 0});
2427 for (unsigned k = 1; k < ineqs; ++k) {
2428 row = getInequality(k).drop_back();
2429 if (hashTable.try_emplace(row, k).second)
2430 continue;
2431
2432 // For identical cases, keep only the smaller part of the constant term.
2433 unsigned l = hashTable[row];
2434 changed = true;
2435 if (atIneq(k, cols - 1) <= atIneq(l, cols - 1))
2436 inequalities.swapRows(k, l);
2438 --k;
2439 --ineqs;
2440 }
2441
2442 // Check the neg form of each inequality, need an extra vector to store it.
2443 SmallVector<DynamicAPInt> negIneq(cols - 1);
2444 for (unsigned k = 0; k < ineqs; ++k) {
2445 row = getInequality(k).drop_back();
2446 negIneq.assign(row.begin(), row.end());
2447 for (DynamicAPInt &ele : negIneq)
2448 ele = -ele;
2449 if (!hashTable.contains(negIneq))
2450 continue;
2451
2452 // For cases where the neg is the same as other inequalities, check that the
2453 // sum of their constant terms is positive.
2454 unsigned l = hashTable[row];
2455 auto sum = atIneq(l, cols - 1) + atIneq(k, cols - 1);
2456 if (sum > 0 || l == k)
2457 continue;
2458
2459 // A sum of constant terms equal to zero combines two inequalities into one
2460 // equation, less than zero means the set is empty.
2461 changed = true;
2462 if (k < l)
2463 std::swap(l, k);
2464 if (sum == 0) {
2468 } else {
2469 *this = getEmpty(getSpace());
2470 }
2471 break;
2472 }
2473
2474 return changed;
2475}
2476
2478 IntegerRelation copyRel = *this;
2479
2480 // Convert Domain variables to Local variables.
2483
2484 // We do not need to do anything to Range variables since they are already in
2485 // SetDim position.
2486
2487 return IntegerPolyhedron(std::move(copyRel));
2488}
2489
2491 assert(getDomainSet().getSpace().isCompatible(poly.getSpace()) &&
2492 "Domain set is not compatible with poly");
2493
2494 // Treating the poly as a relation, convert it from `0 -> R` to `R -> 0`.
2495 IntegerRelation rel = poly;
2496 rel.inverse();
2497
2498 // Append dummy range variables to make the spaces compatible.
2500
2501 // Intersect in place.
2502 mergeLocalVars(rel);
2503 append(rel);
2504}
2505
2507 assert(getRangeSet().getSpace().isCompatible(poly.getSpace()) &&
2508 "Range set is not compatible with poly");
2509
2510 IntegerRelation rel = poly;
2511
2512 // Append dummy domain variables to make the spaces compatible.
2514
2515 mergeLocalVars(rel);
2516 append(rel);
2517}
2518
2525
2527 assert(getRangeSet().getSpace().isCompatible(rel.getDomainSet().getSpace()) &&
2528 "Range of `this` should be compatible with Domain of `rel`");
2529
2530 IntegerRelation copyRel = rel;
2531
2532 // Let relation `this` be R1: A -> B, and `rel` be R2: B -> C.
2533 // We convert R1 to A -> (B X C), and R2 to B X C then intersect the range of
2534 // R1 with R2. After this, we get R1: A -> C, by projecting out B.
2535 // TODO: Using nested spaces here would help, since we could directly
2536 // intersect the range with another relation.
2537 unsigned numBVars = getNumRangeVars();
2538
2539 // Convert R1 from A -> B to A -> (B X C).
2541
2542 // Convert R2 to B X C.
2543 copyRel.convertVarKind(VarKind::Domain, 0, numBVars, VarKind::Range, 0);
2544
2545 // Intersect R2 to range of R1.
2547
2548 // Project out B in R1.
2550
2551 // Eliminate local variables
2553}
2554
2556 inverse();
2557 compose(rel);
2558 inverse();
2559}
2560
2562
2564 /// R1: (i, j) -> k : f(i, j, k) = 0
2565 /// R2: (i, j) -> l : g(i, j, l) = 0
2566 /// R1.rangeProduct(R2): (i, j) -> (k, l) : f(i, j, k) = 0 and g(i, j, l) = 0
2567 assert(getNumDomainVars() == rel.getNumDomainVars() &&
2568 "Range product is only defined for relations with equal domains");
2569
2570 // Extend `this` with the range variables of `rel` and `rel` with the range
2571 // variables of `this`, then intersect them, which also merges their locals.
2572 IntegerRelation result = *this;
2573 result.appendVar(VarKind::Range, rel.getNumRangeVars());
2574 IntegerRelation other = rel;
2576 return result.intersect(other);
2577}
2578
2580 space.print(os);
2581 os << getNumConstraints() << " constraints\n";
2582}
2583
2585 for (int i = getNumEqualities() - 1; i >= 0; --i)
2586 if (rangeIsZero(getEquality(i)))
2587 removeEquality(i);
2588}
2589
2591 if (getNumVars() == 0)
2592 return true;
2593 if (isEmpty())
2594 return false;
2595
2596 // If there is a non-trivial equality, the space cannot be full-dimensional.
2598 if (getNumEqualities() > 0)
2599 return false;
2600
2601 // The polytope is full-dimensional iff it is not flat along every
2602 // inequality directions that involve at least one variable.
2603 //
2604 // To check this, we first remove inequalities involving no variables,
2605 // which is done in the following function.
2607 Simplex simplex(*this);
2608 return llvm::none_of(llvm::seq<int>(getNumInequalities()), [&](int i) {
2609 return simplex.isFlatAlong(getInequality(i));
2610 });
2611}
2612
2614 assert(getNumDomainVars() == other.getNumRangeVars() &&
2615 "Domain of this and range of other do not match");
2616 // assert(std::equal(values.begin(), values.begin() +
2617 // other.getNumDomainVars(),
2618 // otherValues.begin() + other.getNumDomainVars()) &&
2619 // "Domain of this and range of other do not match");
2620
2621 IntegerRelation result = other;
2622
2623 const unsigned thisDomain = getNumDomainVars();
2624 const unsigned thisRange = getNumRangeVars();
2625 const unsigned otherDomain = other.getNumDomainVars();
2626 const unsigned otherRange = other.getNumRangeVars();
2627
2628 // Add dimension variables temporarily to merge symbol and local vars.
2629 // Convert `this` from
2630 // [thisDomain] -> [thisRange]
2631 // to
2632 // [otherDomain thisDomain] -> [otherRange thisRange].
2633 // and `result` from
2634 // [otherDomain] -> [otherRange]
2635 // to
2636 // [otherDomain thisDomain] -> [otherRange thisRange]
2637 insertVar(VarKind::Domain, 0, otherDomain);
2638 insertVar(VarKind::Range, 0, otherRange);
2639 result.insertVar(VarKind::Domain, otherDomain, thisDomain);
2640 result.insertVar(VarKind::Range, otherRange, thisRange);
2641
2642 // Merge symbol and local variables.
2645
2646 // Convert `result` from [otherDomain thisDomain] -> [otherRange thisRange] to
2647 // [otherDomain] -> [thisRange]
2648 result.removeVarRange(VarKind::Domain, otherDomain, otherDomain + thisDomain);
2649 result.convertToLocal(VarKind::Range, 0, otherRange);
2650 // Convert `this` from [otherDomain thisDomain] -> [otherRange thisRange] to
2651 // [otherDomain] -> [thisRange]
2652 convertToLocal(VarKind::Domain, otherDomain, otherDomain + thisDomain);
2653 removeVarRange(VarKind::Range, 0, otherRange);
2654
2655 // Add and match domain of `result` to domain of `this`.
2656 for (unsigned i = 0, e = result.getNumDomainVars(); i < e; ++i)
2657 if (result.getSpace().getId(VarKind::Domain, i).hasValue())
2658 space.setId(VarKind::Domain, i,
2659 result.getSpace().getId(VarKind::Domain, i));
2660 // Add and match range of `this` to range of `result`.
2661 for (unsigned i = 0, e = getNumRangeVars(); i < e; ++i)
2662 if (space.getId(VarKind::Range, i).hasValue())
2663 result.space.setId(VarKind::Range, i, space.getId(VarKind::Range, i));
2664
2665 // Append `this` to `result` and simplify constraints.
2666 result.append(*this);
2667 result.removeRedundantLocalVars();
2668
2669 *this = result;
2670}
2671
2673 assert(hasConsistentState());
2674 printSpace(os);
2675 PrintTableMetrics ptm = {0, 0, "-"};
2676 for (unsigned i = 0, e = getNumEqualities(); i < e; ++i)
2677 for (unsigned j = 0, f = getNumCols(); j < f; ++j)
2679 for (unsigned i = 0, e = getNumInequalities(); i < e; ++i)
2680 for (unsigned j = 0, f = getNumCols(); j < f; ++j)
2682 // Print using PrintMetrics.
2683 constexpr unsigned kMinSpacing = 1;
2684 for (unsigned i = 0, e = getNumEqualities(); i < e; ++i) {
2685 for (unsigned j = 0, f = getNumCols(); j < f; ++j) {
2686 printWithPrintMetrics<DynamicAPInt>(os, atEq(i, j), kMinSpacing, ptm);
2687 }
2688 os << " = 0\n";
2689 }
2690 for (unsigned i = 0, e = getNumInequalities(); i < e; ++i) {
2691 for (unsigned j = 0, f = getNumCols(); j < f; ++j) {
2692 printWithPrintMetrics<DynamicAPInt>(os, atIneq(i, j), kMinSpacing, ptm);
2693 }
2694 os << " >= 0\n";
2695 }
2696 os << '\n';
2697}
2698
2699#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2700void IntegerRelation::dump() const { print(llvm::errs()); }
2701#endif
2702
2703unsigned IntegerPolyhedron::insertVar(VarKind kind, unsigned pos,
2704 unsigned num) {
2705 assert((kind != VarKind::Domain || num == 0) &&
2706 "Domain has to be zero in a set");
2707 return IntegerRelation::insertVar(kind, pos, num);
2708}
2713
return success()
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static bool rangeIsZero(ArrayRef< DynamicAPInt > range)
static void getIndependentConstraints(const IntegerRelation &cst, unsigned pos, unsigned num, SmallVectorImpl< unsigned > &nbIneqIndices, SmallVectorImpl< unsigned > &nbEqIndices)
Find positions of inequalities and equalities that do not have a coefficient for [pos,...
static void removeConstraintsInvolvingVarRange(IntegerRelation &poly, unsigned begin, unsigned count)
static unsigned getBestVarToEliminate(const IntegerRelation &cst, unsigned start, unsigned end)
Returns the position of the variable that has the minimum <number of lowerbounds> times <number of up...
static void getCommonConstraints(const IntegerRelation &a, const IntegerRelation &b, IntegerRelation &c)
static std::optional< unsigned > findEqualityWithNonZeroAfterRow(IntegerRelation &rel, unsigned fromRow, unsigned colIdx)
static DynamicAPInt valueAt(ArrayRef< DynamicAPInt > expr, ArrayRef< DynamicAPInt > point)
Helper to evaluate an affine expression at a point.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
Class storing division representation of local variables of a constraint system.
Definition Utils.h:117
void removeDuplicateDivs(llvm::function_ref< bool(unsigned i, unsigned j)> merge)
Removes duplicate divisions.
Definition Utils.cpp:439
void clearRepr(unsigned i)
Definition Utils.h:136
DynamicAPInt & getDenom(unsigned i)
Definition Utils.h:153
MutableArrayRef< DynamicAPInt > getDividend(unsigned i)
Definition Utils.h:139
An Identifier stores a pointer to an object, such as a Value or an Operation.
An IntegerPolyhedron represents the set of points from a PresburgerSpace that satisfy a list of affin...
IntegerPolyhedron intersect(const IntegerPolyhedron &other) const
Return the intersection of the two relations.
unsigned insertVar(VarKind kind, unsigned pos, unsigned num=1) override
Insert num variables of the specified kind at position pos.
PresburgerSet subtract(const PresburgerSet &other) const
Return the set difference of this set and the given set, i.e., return this \ set.
IntegerPolyhedron(unsigned numReservedInequalities, unsigned numReservedEqualities, unsigned numReservedCols, const PresburgerSpace &space)
Constructs a set reserving memory for the specified number of constraints and variables.
std::unique_ptr< IntegerPolyhedron > clone() const
An IntegerRelation represents the set of points from a PresburgerSpace that satisfy a list of affine ...
std::optional< DynamicAPInt > getConstantBoundOnDimSize(unsigned pos, SmallVectorImpl< DynamicAPInt > *lb=nullptr, DynamicAPInt *boundFloorDivisor=nullptr, SmallVectorImpl< DynamicAPInt > *ub=nullptr, unsigned *minLbPos=nullptr, unsigned *minUbPos=nullptr) const
Returns the smallest known constant bound for the extent of the specified variable (pos^th),...
void setId(VarKind kind, unsigned i, Identifier id)
Set the identifier for the ith variable of the specified kind of the IntegerRelation's PresburgerSpac...
virtual void swapVar(unsigned posA, unsigned posB)
Swap the posA^th variable with the posB^th variable.
void removeIndependentConstraints(unsigned pos, unsigned num)
Removes constraints that are independent of (i.e., do not have a coefficient) variables in the range ...
void compose(const IntegerRelation &rel)
Let the relation this be R1, and the relation rel be R2.
void applyRange(const IntegerRelation &rel)
Given a relation rel, apply the relation to the range of this relation.
unsigned getVarKindEnd(VarKind kind) const
Return the index at Which the specified kind of vars ends.
ArrayRef< Identifier > getIds(VarKind kind)
Get the identifiers for the variables of specified varKind.
void removeTrivialRedundancy()
Removes duplicate constraints, trivially true constraints, and constraints that can be detected as re...
unsigned addLocalModulo(ArrayRef< DynamicAPInt > exprs, const DynamicAPInt &modulus)
Adds a new local variable as the modulus of an affine function of other variables,...
static IntegerRelation getEmpty(const PresburgerSpace &space)
Return an empty system containing an invalid equation 0 = 1.
static constexpr unsigned kExplosionFactor
A parameter that controls detection of an unrealistic number of constraints.
ArrayRef< DynamicAPInt > getEquality(unsigned idx) const
std::optional< unsigned > findConstraintWithNonZeroAt(unsigned colIdx, bool isEq) const
Finds a constraint with a non-zero coefficient at colIdx in equality (isEq=true) or inequality (isEq=...
void removeInequalityRange(unsigned start, unsigned end)
void normalizeConstraintsByGCD()
Normalized each constraints by the GCD of its coefficients.
void truncate(const CountsSnapshot &counts)
virtual void eliminateRedundantLocalVar(unsigned posA, unsigned posB)
Eliminate the posB^th local variable, replacing every instance of it with the posA^th local variable.
void removeRedundantConstraintsFromSimplex(const Simplex &simplex, unsigned offset)
Removes the constraints of this that have been marked redundant in simplex (see Simplex::detectRedund...
std::optional< DynamicAPInt > computeConstantLowerOrUpperBound(unsigned pos)
Returns the constant lower bound if isLower is true, and the upper bound if isLower is false.
void removeEqualityRange(unsigned start, unsigned end)
Remove the (in)equalities at positions [start, end).
LogicalResult constantFoldVar(unsigned pos)
Tries to fold the specified variable to a constant using a trivial equality detection; if successful,...
bool isObviouslyEqual(const IntegerRelation &other) const
Perform a quick equality check on this and other.
IntegerPolyhedron getRangeSet() const
Return a set corresponding to all points in the range of the relation.
std::optional< SmallVector< DynamicAPInt, 8 > > containsPointNoLocal(ArrayRef< DynamicAPInt > point) const
Given the values of non-local vars, return a satisfying assignment to the local if one exists,...
unsigned getNumVarKind(VarKind kind) const
Get the number of vars of the specified kind.
bool isEmptyByGCDTest() const
Runs the GCD test on all equality constraints.
void simplify()
Simplify the constraint system by removing canonicalizing constraints and removing redundant constrai...
void convertVarKind(VarKind srcKind, unsigned varStart, unsigned varLimit, VarKind dstKind, unsigned pos)
Converts variables of kind srcKind in the range [varStart, varLimit) to variables of kind dstKind.
void addBound(BoundType type, unsigned pos, const DynamicAPInt &value)
Adds a constant bound for the specified variable.
unsigned appendVar(VarKind kind, unsigned num=1)
Append num variables of the specified kind after the last variable of that kind.
void intersectRange(const IntegerPolyhedron &poly)
Intersect the given poly with the range in-place.
ArrayRef< DynamicAPInt > getInequality(unsigned idx) const
IntegerRelation rangeProduct(const IntegerRelation &rel)
Let the relation this be R1, and the relation rel be R2.
void print(raw_ostream &os) const
bool isIntegerEmpty() const
Returns true if the set of constraints is found to have no solution, false if a solution exists.
DynamicAPInt atIneq(unsigned i, unsigned j) const
Returns the value at the specified inequality row and column.
virtual unsigned insertVar(VarKind kind, unsigned pos, unsigned num=1)
Insert num variables of the specified kind at position pos.
bool containsPoint(ArrayRef< DynamicAPInt > point) const
Returns true if the given point satisfies the constraints, or false otherwise.
std::optional< SmallVector< DynamicAPInt, 8 > > findIntegerSample() const
Find an integer sample point satisfying the constraints using a branch and bound algorithm with gener...
bool hasInvalidConstraint() const
Checks all rows of equality/inequality constraints for trivial contradictions (for example: 1 == 0,...
LogicalResult unionBoundingBox(const IntegerRelation &other)
Updates the constraints to be the smallest bounding (enclosing) box that contains the points of this ...
IntegerRelation(unsigned numReservedInequalities, unsigned numReservedEqualities, unsigned numReservedCols, const PresburgerSpace &space)
Constructs a relation reserving memory for the specified number of constraints and variables.
bool isHyperRectangular(unsigned pos, unsigned num) const
Returns true if the set can be trivially detected as being hyper-rectangular on the specified contigu...
void convertToLocal(VarKind kind, unsigned varStart, unsigned varLimit)
IntMatrix getBoundedDirections() const
Returns a matrix where each row is a vector along which the polytope is bounded.
LogicalResult gaussianEliminateVar(unsigned position)
Eliminates a single variable at position from equality and inequality constraints.
void clearConstraints()
Removes all equalities and inequalities.
DynamicAPInt atEq(unsigned i, unsigned j) const
Returns the value at the specified equality row and column.
LLVM_DUMP_METHOD void dump() const
IntegerRelation intersect(IntegerRelation other) const
Return the intersection of the two relations.
std::optional< DynamicAPInt > computeVolume() const
Compute an overapproximation of the number of integer points in the relation.
MaybeOptimum< SmallVector< DynamicAPInt, 8 > > findIntegerLexMin() const
Same as above, but returns lexicographically minimal integer point.
const PresburgerSpace & getSpace() const
Returns a reference to the underlying space.
SymbolicLexOpt findSymbolicIntegerLexMin() const
Compute the symbolic integer lexmin of the relation.
void setSpace(const PresburgerSpace &oSpace)
Set the space to oSpace, which should have the same number of ids as the current space.
int findEqualityToConstant(unsigned pos, bool symbolic=false) const
Finds an equality that equates the specified variable to a constant.
void inverse()
Invert the relation i.e., swap its domain and range.
void append(const IntegerRelation &other)
Appends constraints from other into this.
void applyDomain(const IntegerRelation &rel)
Given a relation rel, apply the relation to the domain of this relation.
void intersectDomain(const IntegerPolyhedron &poly)
Intersect the given poly with the domain in-place.
unsigned addLocalFloorDiv(ArrayRef< DynamicAPInt > dividend, const DynamicAPInt &divisor)
Adds a new local variable as the floordiv of an affine function of other variables,...
PresburgerRelation subtract(const PresburgerRelation &set) const
Return the set difference of this set and the given set, i.e., return this \ set.
bool isEqual(const IntegerRelation &other) const
Return whether this and other are equal.
virtual void printSpace(raw_ostream &os) const
Prints the number of constraints, dimensions, symbols and locals in the IntegerRelation.
void addEquality(ArrayRef< DynamicAPInt > eq)
Adds an equality from the coefficients specified in eq.
void removeRedundantConstraints()
Removes redundant constraints using Simplex.
PresburgerRelation computeReprWithOnlyDivLocals() const
Compute an equivalent representation of the same set, such that all local vars in all disjuncts have ...
void removeRedundantInequalities()
A more expensive check than removeTrivialRedundancy to detect redundant inequalities.
bool isObviouslyEmpty() const
Performs GCD checks and invalid constraint checks.
IntMatrix equalities
Coefficients of affine equalities (in == 0 form).
SymbolicLexOpt findSymbolicIntegerLexMax() const
Same as findSymbolicIntegerLexMin but produces lexmax instead of lexmin.
bool gaussianEliminate()
Perform a Gaussian elimination operation to reduce all equations to standard form.
void truncateVarKind(VarKind kind, unsigned num)
Truncate the vars of the specified kind to the specified number by dropping some vars at the end.
void eliminateVarUsingEquality(unsigned col, unsigned eqIdx)
Eliminates the variable at column col from every other equality and every inequality of this using th...
void constantFoldVarRange(unsigned pos, unsigned num)
This method calls constantFoldVar for the specified range of variables, num variables starting at pos...
bool isEmpty() const
Checks for emptiness by performing variable elimination on all variables, running the GCD test on eac...
unsigned getNumCols() const
Returns the number of columns in the constraint system.
void getLowerAndUpperBoundIndices(unsigned pos, SmallVectorImpl< unsigned > *lbIndices, SmallVectorImpl< unsigned > *ubIndices, SmallVectorImpl< unsigned > *eqIndices=nullptr, unsigned offset=0, unsigned num=0) const
Gather positions of all lower and upper bounds of the variable at pos, and optionally any equalities ...
void gcdTightenInequalities()
Tightens inequalities given that we are dealing with integer spaces.
void removeVar(VarKind kind, unsigned pos)
Removes variables of the specified kind with the specified pos (or within the specified range) from t...
void setSpaceExceptLocals(const PresburgerSpace &oSpace)
Set the space to oSpace, which should not have any local ids.
unsigned gaussianEliminateVars(unsigned posStart, unsigned posLimit)
Eliminates variables from equality and inequality constraints in column range [posStart,...
void mergeAndCompose(const IntegerRelation &other)
Given a relation other: (A -> B), this operation merges the symbol and local variables and then takes...
IntegerPolyhedron getDomainSet() const
Return a set corresponding to all points in the domain of the relation.
DivisionRepr getLocalReprs(std::vector< MaybeLocalRepr > *repr=nullptr) const
Returns a DivisonRepr representing the division representation of local variables in the constraint s...
bool hasOnlyDivLocals() const
Check whether all local ids have a division representation.
std::optional< DynamicAPInt > getConstantBound(BoundType type, unsigned pos) const
Returns the constant bound for the pos^th variable if there is one; std::nullopt otherwise.
virtual void clearAndCopyFrom(const IntegerRelation &other)
Replaces the contents of this IntegerRelation with other.
void projectOut(unsigned pos, unsigned num)
Projects out (aka eliminates) num variables starting at position pos.
void addInequality(ArrayRef< DynamicAPInt > inEq)
Adds an inequality (>= 0) from the coefficients specified in inEq.
void mergeAndAlignSymbols(IntegerRelation &other)
Merge and align symbol variables of this and other with respect to identifiers.
void removeRedundantLocalVars()
Removes local variables using equalities.
unsigned mergeLocalVars(IntegerRelation &other)
Adds additional local vars to the sets such that they both have the union of the local vars in each s...
MaybeOptimum< SmallVector< Fraction, 8 > > findRationalLexMin() const
Get the lexicographically minimum rational point satisfying the constraints.
DynamicAPInt & atConstraint(unsigned i, unsigned j)
IntMatrix inequalities
Coefficients of affine inequalities (in >= 0 form).
virtual bool hasConsistentState() const
Returns false if the fields corresponding to various variable counts, or equality/inequality buffer s...
bool isSubsetOf(const IntegerRelation &other) const
Return whether this is a subset of the given IntegerRelation.
std::unique_ptr< IntegerRelation > clone() const
void setAndEliminate(unsigned pos, ArrayRef< DynamicAPInt > values)
Sets the values.size() variables starting at pos to the specified values and removes them.
bool isColZero(unsigned pos) const
Returns true if the pos^th column is all zero for both inequalities and equalities.
void pruneOrthogonalConstraints(unsigned pos)
The function removes some constraints that do not impose any bound on the specified variable.
unsigned getVarKindOffset(VarKind kind) const
Return the index at which the specified kind of vars starts.
virtual void removeVarRange(VarKind kind, unsigned varStart, unsigned varLimit)
virtual void fourierMotzkinEliminate(unsigned pos, bool darkShadow=false, bool *isResultIntegerExact=nullptr)
Eliminates the variable at the specified position using Fourier-Motzkin variable elimination,...
bool removeDuplicateConstraints()
Checks for identical inequalities and eliminates redundant inequalities.
A class for lexicographic optimization without any symbols.
Definition Simplex.h:480
MaybeOptimum< SmallVector< Fraction, 8 > > findRationalLexMin()
Return the lexicographically minimum rational solution to the constraints.
Definition Simplex.cpp:235
MaybeOptimum< SmallVector< DynamicAPInt, 8 > > findIntegerLexMin()
Return the lexicographically minimum integer solution to the constraints.
Definition Simplex.cpp:306
static std::pair< unsigned, LinearTransform > makeTransformToColumnEchelon(const IntMatrix &m)
unsigned getNumRows() const
Definition Matrix.h:86
void fillRow(unsigned row, const T &value)
Definition Matrix.cpp:252
void negateRow(unsigned row)
Negate the specified row.
Definition Matrix.cpp:341
OptimumKind getKind() const
Definition Utils.h:50
This class represents a multi-affine function with the domain as Z^d, where d is the number of domain...
ArrayRef< Piece > getAllPieces() const
Return all the pieces of this piece-wise function.
const PresburgerSpace & getSpace() const
PresburgerSet getDomain() const
Return the domain of this piece-wise MultiAffineFunction.
A PresburgerRelation represents a union of IntegerRelations that live in the same PresburgerSpace wit...
PresburgerRelation subtract(const PresburgerRelation &set) const
Return the set difference of this set and the given set, i.e., return this \ set.
bool isSubsetOf(const PresburgerRelation &set) const
Return true if this set is a subset of the given set, and false otherwise.
bool isEqual(const PresburgerRelation &set) const
Return true if this set is equal to the given set, and false otherwise.
PresburgerSet unionSet(const PresburgerRelation &set) const
These operations are the same as the ones in PresburgeRelation, they just forward the arguement and r...
PresburgerSpace is the space of all possible values of a tuple of integer valued variables/variables.
void setId(VarKind kind, unsigned pos, Identifier id)
Set the identifier of pos^th variable of the specified kind.
unsigned getNumVarKind(VarKind kind) const
Get the number of vars of the specified kind.
bool isUsingIds() const
Returns if identifiers are being used.
void removeVarRange(VarKind kind, unsigned varStart, unsigned varLimit)
Removes variables of the specified kind in the column range [varStart, varLimit).
ArrayRef< Identifier > getIds(VarKind kind) const
unsigned getVarKindOffset(VarKind kind) const
Return the index at which the specified kind of var starts.
Identifier getId(VarKind kind, unsigned pos) const
Get the identifier of pos^th variable of the specified kind.
VarKind getVarKindAt(unsigned pos) const
Return the VarKind of the var at the specified position.
static PresburgerSpace getSetSpace(unsigned numDims=0, unsigned numSymbols=0, unsigned numLocals=0)
static PresburgerSpace getRelationSpace(unsigned numDomain=0, unsigned numRange=0, unsigned numSymbols=0, unsigned numLocals=0)
bool isEmpty() const
Returns true if the tableau is empty (has conflicting constraints), false otherwise.
Definition Simplex.cpp:1070
unsigned getNumConstraints() const
Returns the number of constraints in the tableau.
Definition Simplex.cpp:1140
The Simplex class uses the Normal pivot rule and supports integer emptiness checks as well as detecti...
Definition Simplex.h:693
std::pair< MaybeOptimum< DynamicAPInt >, MaybeOptimum< DynamicAPInt > > computeIntegerBounds(ArrayRef< DynamicAPInt > coeffs)
Returns a (min, max) pair denoting the minimum and maximum integer values of the given expression.
Definition Simplex.cpp:2116
bool isMarkedRedundant(unsigned constraintIndex) const
Returns whether the specified constraint has been marked as redundant.
Definition Simplex.cpp:1417
bool isFlatAlong(ArrayRef< DynamicAPInt > coeffs)
Check if the simplex takes only one rational value along the direction of coeffs.
Definition Simplex.cpp:2124
bool isBoundedAlongConstraint(unsigned constraintIndex)
Returns whether the perpendicular of the specified constraint is a is a direction along which the pol...
Definition Simplex.cpp:1407
bool isUnbounded()
Returns true if the polytope is unbounded, i.e., extends to infinity in some direction.
Definition Simplex.cpp:1479
void detectRedundant(unsigned offset, unsigned count)
Finds a subset of constraints that is redundant, i.e., such that the set of solutions does not change...
Definition Simplex.cpp:1437
std::optional< SmallVector< Fraction, 8 > > getRationalSample() const
Returns the current sample point, which may contain non-integer (rational) coordinates.
Definition Simplex.cpp:1579
std::optional< SmallVector< DynamicAPInt, 8 > > findIntegerSample()
Returns an integer sample point if one exists, or std::nullopt otherwise.
Definition Simplex.cpp:2005
A class to perform symbolic lexicographic optimization, i.e., to find, for every assignment to the sy...
Definition Simplex.h:574
SymbolicLexOpt computeSymbolicIntegerLexMin()
The lexmin will be stored as a function lexopt from symbols to non-symbols in the result.
Definition Simplex.cpp:536
BoundType
The type of bound: equal, lower bound or upper bound.
VarKind
Kind of variable.
MaybeLocalRepr computeSingleVarRepr(const IntegerRelation &cst, ArrayRef< bool > foundRepr, unsigned pos, MutableArrayRef< DynamicAPInt > dividend, DynamicAPInt &divisor)
Returns the MaybeLocalRepr struct which contains the indices of the constraints that can be expressed...
Definition Utils.cpp:227
void mergeLocalVars(IntegerRelation &relA, IntegerRelation &relB, llvm::function_ref< bool(unsigned i, unsigned j)> merge)
Given two relations, A and B, add additional local vars to the sets such that both have the union of ...
Definition Utils.cpp:288
DynamicAPInt ceil(const Fraction &f)
Definition Fraction.h:79
Fraction abs(const Fraction &f)
Definition Fraction.h:107
SmallVector< DynamicAPInt, 8 > getDivUpperBound(ArrayRef< DynamicAPInt > dividend, const DynamicAPInt &divisor, unsigned localVarIdx)
If q is defined to be equal to expr floordiv d, this equivalent to saying that q is an integer and q ...
Definition Utils.cpp:315
void printWithPrintMetrics(raw_ostream &os, T val, unsigned minSpacing, const PrintTableMetrics &m)
Print val in the table with metrics specified in 'm'.
Definition Utils.h:330
void updatePrintMetrics(T val, PrintTableMetrics &m)
Iterate over each val in the table and update 'm' where .maxPreIndent and .maxPostIndent are initiali...
Definition Utils.h:316
SmallVector< DynamicAPInt, 8 > getDivLowerBound(ArrayRef< DynamicAPInt > dividend, const DynamicAPInt &divisor, unsigned localVarIdx)
Definition Utils.cpp:327
Include the generated interface declarations.
The struct CountsSnapshot stores the count of each VarKind, and also of each constraint type.
MaybeLocalRepr contains the indices of the constraints that can be expressed as a floordiv of an affi...
Definition Utils.h:97
Example usage: Print .12, 3.4, 56.7 preAlign = ".", minSpacing = 1, .12 .12 3.4 3....
Definition Utils.h:305
Represents the result of a symbolic lexicographic optimization computation.
Definition Simplex.h:531
PWMAFunction lexopt
This maps assignments of symbols to the corresponding lexopt.
Definition Simplex.h:539
PresburgerSet unboundedDomain
Contains all assignments to the symbols that made the lexopt unbounded.
Definition Simplex.h:543
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.