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