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