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