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