xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 349375d0936e9acd6fead5de03a49b15cdbcd1fd)
1 //===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
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 // Eliminate conditions based on constraints collected from dominating
10 // conditions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/ConstraintSystem.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/DebugCounter.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Transforms/Scalar.h"
33 
34 #include <cmath>
35 #include <string>
36 
37 using namespace llvm;
38 using namespace PatternMatch;
39 
40 #define DEBUG_TYPE "constraint-elimination"
41 
42 STATISTIC(NumCondsRemoved, "Number of instructions removed");
43 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
44               "Controls which conditions are eliminated");
45 
46 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
47 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
48 
49 namespace {
50 
51 class ConstraintInfo;
52 
53 struct StackEntry {
54   unsigned NumIn;
55   unsigned NumOut;
56   bool IsSigned = false;
57   /// Variables that can be removed from the system once the stack entry gets
58   /// removed.
59   SmallVector<Value *, 2> ValuesToRelease;
60 
61   StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
62              SmallVector<Value *, 2> ValuesToRelease)
63       : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
64         ValuesToRelease(ValuesToRelease) {}
65 };
66 
67 /// Struct to express a pre-condition of the form %Op0 Pred %Op1.
68 struct PreconditionTy {
69   CmpInst::Predicate Pred;
70   Value *Op0;
71   Value *Op1;
72 
73   PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
74       : Pred(Pred), Op0(Op0), Op1(Op1) {}
75 };
76 
77 struct ConstraintTy {
78   SmallVector<int64_t, 8> Coefficients;
79   SmallVector<PreconditionTy, 2> Preconditions;
80 
81   SmallVector<SmallVector<int64_t, 8>> ExtraInfo;
82 
83   bool IsSigned = false;
84   bool IsEq = false;
85 
86   ConstraintTy() = default;
87 
88   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned)
89       : Coefficients(Coefficients), IsSigned(IsSigned) {}
90 
91   unsigned size() const { return Coefficients.size(); }
92 
93   unsigned empty() const { return Coefficients.empty(); }
94 
95   /// Returns true if all preconditions for this list of constraints are
96   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
97   bool isValid(const ConstraintInfo &Info) const;
98 };
99 
100 /// Wrapper encapsulating separate constraint systems and corresponding value
101 /// mappings for both unsigned and signed information. Facts are added to and
102 /// conditions are checked against the corresponding system depending on the
103 /// signed-ness of their predicates. While the information is kept separate
104 /// based on signed-ness, certain conditions can be transferred between the two
105 /// systems.
106 class ConstraintInfo {
107   DenseMap<Value *, unsigned> UnsignedValue2Index;
108   DenseMap<Value *, unsigned> SignedValue2Index;
109 
110   ConstraintSystem UnsignedCS;
111   ConstraintSystem SignedCS;
112 
113 public:
114   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
115     return Signed ? SignedValue2Index : UnsignedValue2Index;
116   }
117   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
118     return Signed ? SignedValue2Index : UnsignedValue2Index;
119   }
120 
121   ConstraintSystem &getCS(bool Signed) {
122     return Signed ? SignedCS : UnsignedCS;
123   }
124   const ConstraintSystem &getCS(bool Signed) const {
125     return Signed ? SignedCS : UnsignedCS;
126   }
127 
128   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
129   void popLastNVariables(bool Signed, unsigned N) {
130     getCS(Signed).popLastNVariables(N);
131   }
132 
133   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
134 
135   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
136                unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
137 
138   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
139   /// constraints, using indices from the corresponding constraint system.
140   /// New variables that need to be added to the system are collected in
141   /// \p NewVariables.
142   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
143                              SmallVectorImpl<Value *> &NewVariables) const;
144 
145   /// Turn a condition \p CmpI into a vector of constraints, using indices from
146   /// the corresponding constraint system. New variables that need to be added
147   /// to the system are collected in \p NewVariables.
148   ConstraintTy getConstraint(CmpInst *Cmp,
149                              SmallVectorImpl<Value *> &NewVariables) {
150     return getConstraint(Cmp->getPredicate(), Cmp->getOperand(0),
151                          Cmp->getOperand(1), NewVariables);
152   }
153 
154   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
155   /// system if \p Pred is signed/unsigned.
156   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
157                              unsigned NumIn, unsigned NumOut,
158                              SmallVectorImpl<StackEntry> &DFSInStack);
159 };
160 
161 /// Represents a (Coefficient * Variable) entry after IR decomposition.
162 struct DecompEntry {
163   int64_t Coefficient;
164   Value *Variable;
165   /// True if the variable is known positive in the current constraint.
166   bool IsKnownPositive;
167 
168   DecompEntry(int64_t Coefficient, Value *Variable,
169               bool IsKnownPositive = false)
170       : Coefficient(Coefficient), Variable(Variable),
171         IsKnownPositive(IsKnownPositive) {}
172 };
173 
174 } // namespace
175 
176 // Decomposes \p V into a vector of entries of the form { Coefficient, Variable
177 // } where Coefficient * Variable. The sum of the pairs equals \p V.  The first
178 // pair is the constant-factor and X must be nullptr. If the expression cannot
179 // be decomposed, returns an empty vector.
180 static SmallVector<DecompEntry, 4>
181 decompose(Value *V, SmallVector<PreconditionTy, 4> &Preconditions,
182           bool IsSigned) {
183 
184   auto CanUseSExt = [](ConstantInt *CI) {
185     const APInt &Val = CI->getValue();
186     return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
187   };
188   // Decompose \p V used with a signed predicate.
189   if (IsSigned) {
190     if (auto *CI = dyn_cast<ConstantInt>(V)) {
191       if (CanUseSExt(CI))
192         return {{CI->getSExtValue(), nullptr}};
193     }
194 
195     return {{0, nullptr}, {1, V}};
196   }
197 
198   if (auto *CI = dyn_cast<ConstantInt>(V)) {
199     if (CI->uge(MaxConstraintValue))
200       return {};
201     return {{int64_t(CI->getZExtValue()), nullptr}};
202   }
203   auto *GEP = dyn_cast<GetElementPtrInst>(V);
204   if (GEP && GEP->getNumOperands() == 2 && GEP->isInBounds()) {
205     Value *Op0, *Op1;
206     ConstantInt *CI;
207 
208     // If the index is zero-extended, it is guaranteed to be positive.
209     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
210               m_ZExt(m_Value(Op0)))) {
211       if (match(Op0, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) &&
212           CanUseSExt(CI))
213         return {{0, nullptr},
214                 {1, GEP->getPointerOperand()},
215                 {int64_t(std::pow(int64_t(2), CI->getSExtValue())), Op1}};
216       if (match(Op0, m_NSWAdd(m_Value(Op1), m_ConstantInt(CI))) &&
217           CanUseSExt(CI))
218         return {{CI->getSExtValue(), nullptr},
219                 {1, GEP->getPointerOperand()},
220                 {1, Op1}};
221       return {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0, true}};
222     }
223 
224     if (match(GEP->getOperand(GEP->getNumOperands() - 1), m_ConstantInt(CI)) &&
225         !CI->isNegative() && CanUseSExt(CI))
226       return {{CI->getSExtValue(), nullptr}, {1, GEP->getPointerOperand()}};
227 
228     SmallVector<DecompEntry, 4> Result;
229     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
230               m_NUWShl(m_Value(Op0), m_ConstantInt(CI))) &&
231         CanUseSExt(CI))
232       Result = {{0, nullptr},
233                 {1, GEP->getPointerOperand()},
234                 {int(std::pow(int64_t(2), CI->getSExtValue())), Op0}};
235     else if (match(GEP->getOperand(GEP->getNumOperands() - 1),
236                    m_NSWAdd(m_Value(Op0), m_ConstantInt(CI))) &&
237              CanUseSExt(CI))
238       Result = {{CI->getSExtValue(), nullptr},
239                 {1, GEP->getPointerOperand()},
240                 {1, Op0}};
241     else {
242       Op0 = GEP->getOperand(GEP->getNumOperands() - 1);
243       Result = {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}};
244     }
245     // If Op0 is signed non-negative, the GEP is increasing monotonically and
246     // can be de-composed.
247     Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
248                                ConstantInt::get(Op0->getType(), 0));
249     return Result;
250   }
251 
252   Value *Op0;
253   bool IsKnownPositive = false;
254   if (match(V, m_ZExt(m_Value(Op0)))) {
255     IsKnownPositive = true;
256     V = Op0;
257   }
258 
259   auto MergeResults = [&Preconditions, IsSigned](
260                           Value *A, Value *B,
261                           bool IsSignedB) -> SmallVector<DecompEntry, 4> {
262     auto ResA = decompose(A, Preconditions, IsSigned);
263     auto ResB = decompose(B, Preconditions, IsSignedB);
264     if (ResA.empty() || ResB.empty())
265       return {};
266     ResA[0].Coefficient += ResB[0].Coefficient;
267     append_range(ResA, drop_begin(ResB));
268     return ResA;
269   };
270   Value *Op1;
271   ConstantInt *CI;
272   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
273     return MergeResults(Op0, Op1, IsSigned);
274   }
275   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
276       CanUseSExt(CI)) {
277     Preconditions.emplace_back(
278         CmpInst::ICMP_UGE, Op0,
279         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
280     return MergeResults(Op0, CI, true);
281   }
282 
283   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && CanUseSExt(CI))
284     return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}};
285   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
286     return {{0, nullptr}, {1, Op0}, {-1, Op1}};
287 
288   return {{0, nullptr}, {1, V, IsKnownPositive}};
289 }
290 
291 ConstraintTy
292 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
293                               SmallVectorImpl<Value *> &NewVariables) const {
294   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
295   bool IsEq = false;
296   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
297   switch (Pred) {
298   case CmpInst::ICMP_UGT:
299   case CmpInst::ICMP_UGE:
300   case CmpInst::ICMP_SGT:
301   case CmpInst::ICMP_SGE: {
302     Pred = CmpInst::getSwappedPredicate(Pred);
303     std::swap(Op0, Op1);
304     break;
305   }
306   case CmpInst::ICMP_EQ:
307     if (match(Op1, m_Zero())) {
308       Pred = CmpInst::ICMP_ULE;
309     } else {
310       IsEq = true;
311       Pred = CmpInst::ICMP_ULE;
312     }
313     break;
314   case CmpInst::ICMP_NE:
315     if (!match(Op1, m_Zero()))
316       return {};
317     Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
318     std::swap(Op0, Op1);
319     break;
320   default:
321     break;
322   }
323 
324   // Only ULE and ULT predicates are supported at the moment.
325   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
326       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
327     return {};
328 
329   SmallVector<PreconditionTy, 4> Preconditions;
330   bool IsSigned = CmpInst::isSigned(Pred);
331   auto &Value2Index = getValue2Index(IsSigned);
332   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
333                         Preconditions, IsSigned);
334   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
335                         Preconditions, IsSigned);
336   // Skip if decomposing either of the values failed.
337   if (ADec.empty() || BDec.empty())
338     return {};
339 
340   int64_t Offset1 = ADec[0].Coefficient;
341   int64_t Offset2 = BDec[0].Coefficient;
342   Offset1 *= -1;
343 
344   // Create iterator ranges that skip the constant-factor.
345   auto VariablesA = llvm::drop_begin(ADec);
346   auto VariablesB = llvm::drop_begin(BDec);
347 
348   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
349   // new entry to NewVariables.
350   DenseMap<Value *, unsigned> NewIndexMap;
351   auto GetOrAddIndex = [&Value2Index, &NewVariables,
352                         &NewIndexMap](Value *V) -> unsigned {
353     auto V2I = Value2Index.find(V);
354     if (V2I != Value2Index.end())
355       return V2I->second;
356     auto Insert =
357         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
358     if (Insert.second)
359       NewVariables.push_back(V);
360     return Insert.first->second;
361   };
362 
363   // Make sure all variables have entries in Value2Index or NewVariables.
364   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
365     GetOrAddIndex(KV.Variable);
366 
367   // Build result constraint, by first adding all coefficients from A and then
368   // subtracting all coefficients from B.
369   ConstraintTy Res(
370       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
371       IsSigned);
372   // Collect variables that are known to be positive in all uses in the
373   // constraint.
374   DenseMap<Value *, bool> KnownPositiveVariables;
375   Res.IsEq = IsEq;
376   auto &R = Res.Coefficients;
377   for (const auto &KV : VariablesA) {
378     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
379     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
380     I.first->second &= KV.IsKnownPositive;
381   }
382 
383   for (const auto &KV : VariablesB) {
384     R[GetOrAddIndex(KV.Variable)] -= KV.Coefficient;
385     auto I = KnownPositiveVariables.insert({KV.Variable, KV.IsKnownPositive});
386     I.first->second &= KV.IsKnownPositive;
387   }
388 
389   int64_t OffsetSum;
390   if (AddOverflow(Offset1, Offset2, OffsetSum))
391     return {};
392   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
393     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
394       return {};
395   R[0] = OffsetSum;
396   Res.Preconditions = std::move(Preconditions);
397 
398   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
399   // variables.
400   while (!NewVariables.empty()) {
401     int64_t Last = R.back();
402     if (Last != 0)
403       break;
404     R.pop_back();
405     Value *RemovedV = NewVariables.pop_back_val();
406     NewIndexMap.erase(RemovedV);
407   }
408 
409   // Add extra constraints for variables that are known positive.
410   for (auto &KV : KnownPositiveVariables) {
411     if (!KV.second || (Value2Index.find(KV.first) == Value2Index.end() &&
412                        NewIndexMap.find(KV.first) == NewIndexMap.end()))
413       continue;
414     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
415     C[GetOrAddIndex(KV.first)] = -1;
416     Res.ExtraInfo.push_back(C);
417   }
418   return Res;
419 }
420 
421 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
422   return Coefficients.size() > 0 &&
423          all_of(Preconditions, [&Info](const PreconditionTy &C) {
424            return Info.doesHold(C.Pred, C.Op0, C.Op1);
425          });
426 }
427 
428 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
429                               Value *B) const {
430   SmallVector<Value *> NewVariables;
431   auto R = getConstraint(Pred, A, B, NewVariables);
432 
433   if (!NewVariables.empty())
434     return false;
435 
436   return NewVariables.empty() && R.Preconditions.empty() && !R.IsEq &&
437          !R.empty() && getCS(R.IsSigned).isConditionImplied(R.Coefficients);
438 }
439 
440 void ConstraintInfo::transferToOtherSystem(
441     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
442     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
443   // Check if we can combine facts from the signed and unsigned systems to
444   // derive additional facts.
445   if (!A->getType()->isIntegerTy())
446     return;
447   // FIXME: This currently depends on the order we add facts. Ideally we
448   // would first add all known facts and only then try to add additional
449   // facts.
450   switch (Pred) {
451   default:
452     break;
453   case CmpInst::ICMP_ULT:
454     //  If B is a signed positive constant, A >=s 0 and A <s B.
455     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
456       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
457               NumOut, DFSInStack);
458       addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack);
459     }
460     break;
461   case CmpInst::ICMP_SLT:
462     if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0)))
463       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
464     break;
465   case CmpInst::ICMP_SGT:
466     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
467       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
468               NumOut, DFSInStack);
469     break;
470   case CmpInst::ICMP_SGE:
471     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
472       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
473     }
474     break;
475   }
476 }
477 
478 namespace {
479 /// Represents either a condition that holds on entry to a block or a basic
480 /// block, with their respective Dominator DFS in and out numbers.
481 struct ConstraintOrBlock {
482   unsigned NumIn;
483   unsigned NumOut;
484   bool IsBlock;
485   bool Not;
486   union {
487     BasicBlock *BB;
488     CmpInst *Condition;
489   };
490 
491   ConstraintOrBlock(DomTreeNode *DTN)
492       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
493         BB(DTN->getBlock()) {}
494   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
495       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
496         Not(Not), Condition(Condition) {}
497 };
498 
499 /// Keep state required to build worklist.
500 struct State {
501   DominatorTree &DT;
502   SmallVector<ConstraintOrBlock, 64> WorkList;
503 
504   State(DominatorTree &DT) : DT(DT) {}
505 
506   /// Process block \p BB and add known facts to work-list.
507   void addInfoFor(BasicBlock &BB);
508 
509   /// Returns true if we can add a known condition from BB to its successor
510   /// block Succ. Each predecessor of Succ can either be BB or be dominated
511   /// by Succ (e.g. the case when adding a condition from a pre-header to a
512   /// loop header).
513   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
514     if (BB.getSingleSuccessor()) {
515       assert(BB.getSingleSuccessor() == Succ);
516       return DT.properlyDominates(&BB, Succ);
517     }
518     return any_of(successors(&BB),
519                   [Succ](const BasicBlock *S) { return S != Succ; }) &&
520            all_of(predecessors(Succ), [&BB, Succ, this](BasicBlock *Pred) {
521              return Pred == &BB || DT.dominates(Succ, Pred);
522            });
523   }
524 };
525 
526 } // namespace
527 
528 #ifndef NDEBUG
529 static void dumpWithNames(const ConstraintSystem &CS,
530                           DenseMap<Value *, unsigned> &Value2Index) {
531   SmallVector<std::string> Names(Value2Index.size(), "");
532   for (auto &KV : Value2Index) {
533     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
534   }
535   CS.dump(Names);
536 }
537 
538 static void dumpWithNames(ArrayRef<int64_t> C,
539                           DenseMap<Value *, unsigned> &Value2Index) {
540   ConstraintSystem CS;
541   CS.addVariableRowFill(C);
542   dumpWithNames(CS, Value2Index);
543 }
544 #endif
545 
546 void State::addInfoFor(BasicBlock &BB) {
547   WorkList.emplace_back(DT.getNode(&BB));
548 
549   // True as long as long as the current instruction is guaranteed to execute.
550   bool GuaranteedToExecute = true;
551   // Scan BB for assume calls.
552   // TODO: also use this scan to queue conditions to simplify, so we can
553   // interleave facts from assumes and conditions to simplify in a single
554   // basic block. And to skip another traversal of each basic block when
555   // simplifying.
556   for (Instruction &I : BB) {
557     Value *Cond;
558     // For now, just handle assumes with a single compare as condition.
559     if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
560         isa<ICmpInst>(Cond)) {
561       if (GuaranteedToExecute) {
562         // The assume is guaranteed to execute when BB is entered, hence Cond
563         // holds on entry to BB.
564         WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false);
565       } else {
566         // Otherwise the condition only holds in the successors.
567         for (BasicBlock *Succ : successors(&BB)) {
568           if (!canAddSuccessor(BB, Succ))
569             continue;
570           WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), false);
571         }
572       }
573     }
574     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
575   }
576 
577   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
578   if (!Br || !Br->isConditional())
579     return;
580 
581   // If the condition is a chain of ORs and the false successor only has
582   // the current block as predecessor, queue the negated conditions for the
583   // false successor.
584   Value *Op0, *Op1;
585   if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
586     BasicBlock *FalseSuccessor = Br->getSuccessor(1);
587     if (canAddSuccessor(BB, FalseSuccessor)) {
588       SmallVector<Value *> CondWorkList;
589       SmallPtrSet<Value *, 8> SeenCond;
590       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
591         if (SeenCond.insert(V).second)
592           CondWorkList.push_back(V);
593       };
594       QueueValue(Op0);
595       QueueValue(Op1);
596       while (!CondWorkList.empty()) {
597         Value *Cur = CondWorkList.pop_back_val();
598         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
599           WorkList.emplace_back(DT.getNode(FalseSuccessor), Cmp, true);
600           continue;
601         }
602         if (match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
603           QueueValue(Op0);
604           QueueValue(Op1);
605         }
606       }
607     }
608     return;
609   }
610 
611   // If the condition is an AND of 2 compares and the true successor only has
612   // the current block as predecessor, queue both conditions for the true
613   // successor.
614   if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) &&
615       isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) {
616     BasicBlock *TrueSuccessor = Br->getSuccessor(0);
617     if (canAddSuccessor(BB, TrueSuccessor)) {
618       WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op0),
619                             false);
620       WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op1),
621                             false);
622     }
623     return;
624   }
625 
626   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
627   if (!CmpI)
628     return;
629   if (canAddSuccessor(BB, Br->getSuccessor(0)))
630     WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
631   if (canAddSuccessor(BB, Br->getSuccessor(1)))
632     WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
633 }
634 
635 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
636                              unsigned NumIn, unsigned NumOut,
637                              SmallVectorImpl<StackEntry> &DFSInStack) {
638   // If the constraint has a pre-condition, skip the constraint if it does not
639   // hold.
640   SmallVector<Value *> NewVariables;
641   auto R = getConstraint(Pred, A, B, NewVariables);
642   if (!R.isValid(*this))
643     return;
644 
645   LLVM_DEBUG(dbgs() << "Adding '" << CmpInst::getPredicateName(Pred) << " ";
646              A->printAsOperand(dbgs(), false); dbgs() << ", ";
647              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
648   bool Added = false;
649   assert(CmpInst::isSigned(Pred) == R.IsSigned &&
650          "condition and constraint signs must match");
651   auto &CSToUse = getCS(R.IsSigned);
652   if (R.Coefficients.empty())
653     return;
654 
655   Added |= CSToUse.addVariableRowFill(R.Coefficients);
656 
657   // If R has been added to the system, add the new variables and queue it for
658   // removal once it goes out-of-scope.
659   if (Added) {
660     SmallVector<Value *, 2> ValuesToRelease;
661     auto &Value2Index = getValue2Index(R.IsSigned);
662     for (Value *V : NewVariables) {
663       Value2Index.insert({V, Value2Index.size() + 1});
664       ValuesToRelease.push_back(V);
665     }
666 
667     LLVM_DEBUG({
668       dbgs() << "  constraint: ";
669       dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned));
670       dbgs() << "\n";
671     });
672 
673     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, ValuesToRelease);
674 
675     if (R.IsEq) {
676       // Also add the inverted constraint for equality constraints.
677       for (auto &Coeff : R.Coefficients)
678         Coeff *= -1;
679       CSToUse.addVariableRowFill(R.Coefficients);
680 
681       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
682                               SmallVector<Value *, 2>());
683     }
684   }
685 }
686 
687 static bool
688 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
689                           SmallVectorImpl<Instruction *> &ToRemove) {
690   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
691                               ConstraintInfo &Info) {
692     SmallVector<Value *> NewVariables;
693     auto R = Info.getConstraint(Pred, A, B, NewVariables);
694     if (R.size() < 2 || !NewVariables.empty() || !R.isValid(Info))
695       return false;
696 
697     auto &CSToUse = Info.getCS(R.IsSigned);
698     return CSToUse.isConditionImplied(R.Coefficients);
699   };
700 
701   bool Changed = false;
702   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
703     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
704     // can be simplified to a regular sub.
705     Value *A = II->getArgOperand(0);
706     Value *B = II->getArgOperand(1);
707     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
708         !DoesConditionHold(CmpInst::ICMP_SGE, B,
709                            ConstantInt::get(A->getType(), 0), Info))
710       return false;
711 
712     IRBuilder<> Builder(II->getParent(), II->getIterator());
713     Value *Sub = nullptr;
714     for (User *U : make_early_inc_range(II->users())) {
715       if (match(U, m_ExtractValue<0>(m_Value()))) {
716         if (!Sub)
717           Sub = Builder.CreateSub(A, B);
718         U->replaceAllUsesWith(Sub);
719         Changed = true;
720       } else if (match(U, m_ExtractValue<1>(m_Value()))) {
721         U->replaceAllUsesWith(Builder.getFalse());
722         Changed = true;
723       } else
724         continue;
725 
726       if (U->use_empty()) {
727         auto *I = cast<Instruction>(U);
728         ToRemove.push_back(I);
729         I->setOperand(0, PoisonValue::get(II->getType()));
730         Changed = true;
731       }
732     }
733 
734     if (II->use_empty()) {
735       II->eraseFromParent();
736       Changed = true;
737     }
738   }
739   return Changed;
740 }
741 
742 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
743   bool Changed = false;
744   DT.updateDFSNumbers();
745 
746   ConstraintInfo Info;
747   State S(DT);
748 
749   // First, collect conditions implied by branches and blocks with their
750   // Dominator DFS in and out numbers.
751   for (BasicBlock &BB : F) {
752     if (!DT.getNode(&BB))
753       continue;
754     S.addInfoFor(BB);
755   }
756 
757   // Next, sort worklist by dominance, so that dominating blocks and conditions
758   // come before blocks and conditions dominated by them. If a block and a
759   // condition have the same numbers, the condition comes before the block, as
760   // it holds on entry to the block.
761   stable_sort(S.WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
762     return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock);
763   });
764 
765   SmallVector<Instruction *> ToRemove;
766 
767   // Finally, process ordered worklist and eliminate implied conditions.
768   SmallVector<StackEntry, 16> DFSInStack;
769   for (ConstraintOrBlock &CB : S.WorkList) {
770     // First, pop entries from the stack that are out-of-scope for CB. Remove
771     // the corresponding entry from the constraint system.
772     while (!DFSInStack.empty()) {
773       auto &E = DFSInStack.back();
774       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
775                         << "\n");
776       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
777       assert(E.NumIn <= CB.NumIn);
778       if (CB.NumOut <= E.NumOut)
779         break;
780       LLVM_DEBUG({
781         dbgs() << "Removing ";
782         dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(),
783                       Info.getValue2Index(E.IsSigned));
784         dbgs() << "\n";
785       });
786 
787       Info.popLastConstraint(E.IsSigned);
788       // Remove variables in the system that went out of scope.
789       auto &Mapping = Info.getValue2Index(E.IsSigned);
790       for (Value *V : E.ValuesToRelease)
791         Mapping.erase(V);
792       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
793       DFSInStack.pop_back();
794     }
795 
796     LLVM_DEBUG({
797       dbgs() << "Processing ";
798       if (CB.IsBlock)
799         dbgs() << *CB.BB;
800       else
801         dbgs() << *CB.Condition;
802       dbgs() << "\n";
803     });
804 
805     // For a block, check if any CmpInsts become known based on the current set
806     // of constraints.
807     if (CB.IsBlock) {
808       for (Instruction &I : make_early_inc_range(*CB.BB)) {
809         if (auto *II = dyn_cast<WithOverflowInst>(&I)) {
810           Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
811           continue;
812         }
813         auto *Cmp = dyn_cast<ICmpInst>(&I);
814         if (!Cmp)
815           continue;
816 
817         LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
818         SmallVector<Value *> NewVariables;
819         auto R = Info.getConstraint(Cmp, NewVariables);
820         if (R.IsEq || R.empty() || !NewVariables.empty() || !R.isValid(Info))
821           continue;
822 
823         auto &CSToUse = Info.getCS(R.IsSigned);
824 
825         // If there was extra information collected during decomposition, apply
826         // it now and remove it immediately once we are done with reasoning
827         // about the constraint.
828         for (auto &Row : R.ExtraInfo)
829           CSToUse.addVariableRow(Row);
830         auto InfoRestorer = make_scope_exit([&]() {
831           for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
832             CSToUse.popLastConstraint();
833         });
834 
835         if (CSToUse.isConditionImplied(R.Coefficients)) {
836           if (!DebugCounter::shouldExecute(EliminatedCounter))
837             continue;
838 
839           LLVM_DEBUG({
840             dbgs() << "Condition " << *Cmp
841                    << " implied by dominating constraints\n";
842             dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
843           });
844           Cmp->replaceUsesWithIf(
845               ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) {
846                 // Conditions in an assume trivially simplify to true. Skip uses
847                 // in assume calls to not destroy the available information.
848                 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
849                 return !II || II->getIntrinsicID() != Intrinsic::assume;
850               });
851           NumCondsRemoved++;
852           Changed = true;
853         }
854         if (CSToUse.isConditionImplied(
855                 ConstraintSystem::negate(R.Coefficients))) {
856           if (!DebugCounter::shouldExecute(EliminatedCounter))
857             continue;
858 
859           LLVM_DEBUG({
860             dbgs() << "Condition !" << *Cmp
861                    << " implied by dominating constraints\n";
862             dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned));
863           });
864           Cmp->replaceAllUsesWith(
865               ConstantInt::getFalse(F.getParent()->getContext()));
866           NumCondsRemoved++;
867           Changed = true;
868         }
869       }
870       continue;
871     }
872 
873     ICmpInst::Predicate Pred;
874     Value *A, *B;
875     if (match(CB.Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
876       // Use the inverse predicate if required.
877       if (CB.Not)
878         Pred = CmpInst::getInversePredicate(Pred);
879 
880       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
881       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
882     }
883   }
884 
885 #ifndef NDEBUG
886   unsigned SignedEntries =
887       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
888   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
889          "updates to CS and DFSInStack are out of sync");
890   assert(Info.getCS(true).size() == SignedEntries &&
891          "updates to CS and DFSInStack are out of sync");
892 #endif
893 
894   for (Instruction *I : ToRemove)
895     I->eraseFromParent();
896   return Changed;
897 }
898 
899 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
900                                                  FunctionAnalysisManager &AM) {
901   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
902   if (!eliminateConstraints(F, DT))
903     return PreservedAnalyses::all();
904 
905   PreservedAnalyses PA;
906   PA.preserve<DominatorTreeAnalysis>();
907   PA.preserveSet<CFGAnalyses>();
908   return PA;
909 }
910 
911 namespace {
912 
913 class ConstraintElimination : public FunctionPass {
914 public:
915   static char ID;
916 
917   ConstraintElimination() : FunctionPass(ID) {
918     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
919   }
920 
921   bool runOnFunction(Function &F) override {
922     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
923     return eliminateConstraints(F, DT);
924   }
925 
926   void getAnalysisUsage(AnalysisUsage &AU) const override {
927     AU.setPreservesCFG();
928     AU.addRequired<DominatorTreeWrapperPass>();
929     AU.addPreserved<GlobalsAAWrapperPass>();
930     AU.addPreserved<DominatorTreeWrapperPass>();
931   }
932 };
933 
934 } // end anonymous namespace
935 
936 char ConstraintElimination::ID = 0;
937 
938 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
939                       "Constraint Elimination", false, false)
940 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
941 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
942 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
943                     "Constraint Elimination", false, false)
944 
945 FunctionPass *llvm::createConstraintEliminationPass() {
946   return new ConstraintElimination();
947 }
948