LLVM 24.0.0git
ConstraintSystem.cpp
Go to the documentation of this file.
1//===- ConstraintSytem.cpp - A system of linear constraints. ----*- C++ -*-===//
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
12#include "llvm/IR/Value.h"
13#include "llvm/Support/Debug.h"
15
16#include <string>
17
18using namespace llvm;
19
20#define DEBUG_TYPE "constraint-system"
21
22bool ConstraintSystem::eliminateUsingFM() {
23 // Implementation of Fourier–Motzkin elimination, with some tricks from the
24 // paper Pugh, William. "The Omega test: a fast and practical integer
25 // programming algorithm for dependence
26 // analysis."
27 // Supercomputing'91: Proceedings of the 1991 ACM/
28 // IEEE conference on Supercomputing. IEEE, 1991.
29 assert(!Constraints.empty() &&
30 "should only be called for non-empty constraint systems");
31
32 unsigned LastIdx = NumVariables - 1;
33
34 // First, either remove the variable in place if it is 0 or add the row to
35 // RemainingRows and remove it from the system.
36 SmallVector<SmallVector<Entry, 8>, 4> RemainingRows;
37 for (unsigned R1 = 0; R1 < Constraints.size();) {
38 SmallVector<Entry, 8> &Row1 = Constraints[R1];
39 if (getLastCoefficient(Row1, LastIdx) == 0) {
40 if (Row1.size() > 0 && Row1.back().Id == LastIdx)
41 Row1.pop_back();
42 R1++;
43 } else {
44 std::swap(Constraints[R1], Constraints.back());
45 RemainingRows.push_back(std::move(Constraints.back()));
46 Constraints.pop_back();
47 }
48 }
49
50 // Process rows where the variable is != 0.
51 unsigned NumRemainingConstraints = RemainingRows.size();
52 for (unsigned R1 = 0; R1 < NumRemainingConstraints; R1++) {
53 // FIXME do not use copy
54 for (unsigned R2 = R1 + 1; R2 < NumRemainingConstraints; R2++) {
55 // Examples of constraints stored as {Constant, Coeff_x, Coeff_y}
56 // R1: 0 >= 1 * x + (-2) * y => { 0, 1, -2 }
57 // R2: 3 >= 2 * x + 3 * y => { 3, 2, 3 }
58 // LastIdx = 2 (tracking coefficient of y)
59 // UpperLast: 3
60 // LowerLast: -2
61 int64_t UpperLast = getLastCoefficient(RemainingRows[R2], LastIdx);
62 int64_t LowerLast = getLastCoefficient(RemainingRows[R1], LastIdx);
63 assert(
64 UpperLast != 0 && LowerLast != 0 &&
65 "RemainingRows should only contain rows where the variable is != 0");
66
67 if ((LowerLast < 0 && UpperLast < 0) || (LowerLast > 0 && UpperLast > 0))
68 continue;
69
70 unsigned LowerR = R1;
71 unsigned UpperR = R2;
72 if (UpperLast < 0) {
73 std::swap(LowerR, UpperR);
74 std::swap(LowerLast, UpperLast);
75 }
76
78 unsigned IdxUpper = 0;
79 unsigned IdxLower = 0;
80 auto &LowerRow = RemainingRows[LowerR];
81 auto &UpperRow = RemainingRows[UpperR];
82 // Combine the two rows to eliminate the variable. If any coefficient
83 // computation overflows, skip them.
84 bool Overflow = false;
85 // Update constant and coefficients of both constraints.
86 // Stops until every coefficient is updated or overflows.
87 while (true) {
88 if (IdxUpper >= UpperRow.size() || IdxLower >= LowerRow.size())
89 break;
90 int64_t M1, M2, N;
91 // Starts with index 0 and updates every coefficients.
92 int64_t UpperV = 0;
93 int64_t LowerV = 0;
94 uint16_t CurrentId = std::numeric_limits<uint16_t>::max();
95 if (IdxUpper < UpperRow.size()) {
96 CurrentId = std::min(UpperRow[IdxUpper].Id, CurrentId);
97 }
98 if (IdxLower < LowerRow.size()) {
99 CurrentId = std::min(LowerRow[IdxLower].Id, CurrentId);
100 }
101
102 if (IdxUpper < UpperRow.size() && UpperRow[IdxUpper].Id == CurrentId) {
103 UpperV = UpperRow[IdxUpper].Coefficient;
104 IdxUpper++;
105 }
106
107 if (MulOverflow(UpperV, -1 * LowerLast, M1)) {
108 Overflow = true;
109 break;
110 }
111 if (IdxLower < LowerRow.size() && LowerRow[IdxLower].Id == CurrentId) {
112 LowerV = LowerRow[IdxLower].Coefficient;
113 IdxLower++;
114 }
115
116 if (MulOverflow(LowerV, UpperLast, M2)) {
117 Overflow = true;
118 break;
119 }
120 // This algorithm is a variant of sparse Gaussian elimination.
121 //
122 // The new coefficient for CurrentId is
123 // N = UpperV * (-1) * LowerLast + LowerV * UpperLast
124 //
125 // UpperRow: { 3, 2, 3 }, LowerLast: -2
126 // LowerRow: { 0, 1, -2 }, UpperLast: 3
127 //
128 // After multiplication:
129 // UpperRow: { 6, 4, 6 }
130 // LowerRow: { 0, 3, -6 }
131 //
132 // Eliminates y after addition:
133 // N: { 6, 7, 0 } => 6 >= 7 * x
134 if (AddOverflow(M1, M2, N)) {
135 Overflow = true;
136 break;
137 }
138 // Skip variable that is completely eliminated.
139 if (N == 0)
140 continue;
141 NR.emplace_back(N, CurrentId);
142 }
143 if (Overflow || NR.empty())
144 continue;
145 Constraints.push_back(std::move(NR));
146 // Give up if the new system gets too big.
147 if (Constraints.size() > 500)
148 return false;
149 }
150 }
151 NumVariables -= 1;
152
153 return true;
154}
155
156bool ConstraintSystem::mayHaveSolutionImpl() {
157 while (!Constraints.empty() && NumVariables > 1) {
158 if (!eliminateUsingFM())
159 return true;
160 }
161
162 if (Constraints.empty() || NumVariables > 1)
163 return true;
164
165 return all_of(Constraints, [](auto &R) {
166 if (R.empty())
167 return true;
168 if (R[0].Id == 0)
169 return R[0].Coefficient >= 0;
170 return true;
171 });
172}
173
174SmallVector<std::string> ConstraintSystem::getVarNamesList() const {
175 SmallVector<std::string> Names(Value2Index.size(), "");
176#ifndef NDEBUG
177 for (auto &[V, Index] : Value2Index) {
178 std::string OperandName;
179 if (V->getName().empty())
180 OperandName = V->getNameOrAsOperand();
181 else
182 OperandName = std::string("%") + V->getName().str();
183 Names[Index - 1] = OperandName;
184 }
185#endif
186 return Names;
187}
188
190#ifndef NDEBUG
191 if (Constraints.empty())
192 return;
193 SmallVector<std::string> Names = getVarNamesList();
194 for (const auto &Row : Constraints) {
196 for (const Entry &E : Row) {
197 if (E.Id >= NumVariables)
198 break;
199 if (E.Id == 0)
200 continue;
201 std::string Coefficient;
202 if (E.Coefficient != 1)
203 Coefficient = std::to_string(E.Coefficient) + " * ";
204 Parts.push_back(Coefficient + Names[E.Id - 1]);
205 }
206 // assert(!Parts.empty() && "need to have at least some parts");
207 int64_t ConstPart = 0;
208 if (Row[0].Id == 0)
209 ConstPart = Row[0].Coefficient;
210 LLVM_DEBUG(dbgs() << join(Parts, std::string(" + "))
211 << " <= " << std::to_string(ConstPart) << "\n");
212 }
213#endif
214}
215
217 LLVM_DEBUG(dbgs() << "---\n");
218 LLVM_DEBUG(dump());
219 bool HasSolution = mayHaveSolutionImpl();
220 LLVM_DEBUG(dbgs() << (HasSolution ? "sat" : "unsat") << "\n");
221 return HasSolution;
222}
223
225 // If all variable coefficients are 0, we have 'C >= 0'. If the constant is >=
226 // 0, R is always true, regardless of the system.
227 if (all_of(ArrayRef(R).drop_front(1), equal_to(0)))
228 return R[0] >= 0;
229
230 // If there is no solution with the negation of R added to the system, the
231 // condition must hold based on the existing constraints.
233 if (R.empty())
234 return false;
235
236 auto NewSystem = *this;
237 NewSystem.addVariableRow(R);
238 return !NewSystem.mayHaveSolution();
239}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define R2(n)
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SmallVector< int64_t, 8 > negate(SmallVector< int64_t, 8 > R)
LLVM_ABI bool mayHaveSolution()
Returns true if there may be a solution for the constraints in the system.
LLVM_ABI bool isConditionImplied(SmallVector< int64_t, 8 > R) const
LLVM_ABI void dump() const
Print the constraints in the system.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This is an optimization pass for GlobalISel generic memory operations.
std::enable_if_t< std::is_signed_v< T >, T > MulOverflow(T X, T Y, T &Result)
Multiply two signed integers, computing the two's complement truncated result, returning true if an o...
Definition MathExtras.h:753
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
unsigned M1(unsigned Val)
Definition VE.h:377
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::enable_if_t< std::is_signed_v< T >, T > AddOverflow(T X, T Y, T &Result)
Add two signed integers, computing the two's complement truncated result, returning true if overflow ...
Definition MathExtras.h:701
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
#define N