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() = default;
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_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative()) {
233     Preconditions.emplace_back(
234         CmpInst::ICMP_UGE, Op0,
235         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
236     return {{CI->getSExtValue(), nullptr}, {1, Op0}};
237   }
238   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1))))
239     return {{0, nullptr}, {1, Op0}, {1, Op1}};
240 
241   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))))
242     return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}};
243   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
244     return {{0, nullptr}, {1, Op0}, {-1, Op1}};
245 
246   return {{0, nullptr}, {1, V}};
247 }
248 
249 /// Turn a condition \p CmpI into a vector of constraints, using indices from \p
250 /// Value2Index. Additional indices for newly discovered values are added to \p
251 /// NewIndices.
252 static ConstraintListTy
253 getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
254               const DenseMap<Value *, unsigned> &Value2Index,
255               DenseMap<Value *, unsigned> &NewIndices) {
256   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
257   switch (Pred) {
258   case CmpInst::ICMP_UGT:
259   case CmpInst::ICMP_UGE:
260   case CmpInst::ICMP_SGT:
261   case CmpInst::ICMP_SGE: {
262     Pred = CmpInst::getSwappedPredicate(Pred);
263     std::swap(Op0, Op1);
264     break;
265   }
266   case CmpInst::ICMP_EQ:
267     if (match(Op1, m_Zero())) {
268       Pred = CmpInst::ICMP_ULE;
269     } else {
270       auto A =
271           getConstraint(CmpInst::ICMP_UGE, Op0, Op1, Value2Index, NewIndices);
272       auto B =
273           getConstraint(CmpInst::ICMP_ULE, Op0, Op1, Value2Index, NewIndices);
274       A.mergeIn(B);
275       return A;
276     }
277     break;
278   case CmpInst::ICMP_NE:
279     if (!match(Op1, m_Zero()))
280       return {};
281     Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
282     std::swap(Op0, Op1);
283     break;
284   default:
285     break;
286   }
287 
288   // Only ULE and ULT predicates are supported at the moment.
289   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
290       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
291     return {};
292 
293   SmallVector<PreconditionTy, 4> Preconditions;
294   bool IsSigned = CmpInst::isSigned(Pred);
295   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
296                         Preconditions, IsSigned);
297   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
298                         Preconditions, IsSigned);
299   // Skip if decomposing either of the values failed.
300   if (ADec.empty() || BDec.empty())
301     return {};
302 
303   // Skip trivial constraints without any variables.
304   if (ADec.size() == 1 && BDec.size() == 1)
305     return {};
306 
307   int64_t Offset1 = ADec[0].first;
308   int64_t Offset2 = BDec[0].first;
309   Offset1 *= -1;
310 
311   // Create iterator ranges that skip the constant-factor.
312   auto VariablesA = llvm::drop_begin(ADec);
313   auto VariablesB = llvm::drop_begin(BDec);
314 
315   // First try to look up \p V in Value2Index and NewIndices. Otherwise add a
316   // new entry to NewIndices.
317   auto GetOrAddIndex = [&Value2Index, &NewIndices](Value *V) -> unsigned {
318     auto V2I = Value2Index.find(V);
319     if (V2I != Value2Index.end())
320       return V2I->second;
321     auto Insert =
322         NewIndices.insert({V, Value2Index.size() + NewIndices.size() + 1});
323     return Insert.first->second;
324   };
325 
326   // Make sure all variables have entries in Value2Index or NewIndices.
327   for (const auto &KV :
328        concat<std::pair<int64_t, Value *>>(VariablesA, VariablesB))
329     GetOrAddIndex(KV.second);
330 
331   // Build result constraint, by first adding all coefficients from A and then
332   // subtracting all coefficients from B.
333   SmallVector<int64_t, 8> R(Value2Index.size() + NewIndices.size() + 1, 0);
334   for (const auto &KV : VariablesA)
335     R[GetOrAddIndex(KV.second)] += KV.first;
336 
337   for (const auto &KV : VariablesB)
338     R[GetOrAddIndex(KV.second)] -= KV.first;
339 
340   R[0] = Offset1 + Offset2 +
341          (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT) ? -1 : 0);
342   return {{{R, IsSigned}}, Preconditions};
343 }
344 
345 static ConstraintListTy getConstraint(CmpInst *Cmp, ConstraintInfo &Info,
346                                       DenseMap<Value *, unsigned> &NewIndices) {
347   return getConstraint(
348       Cmp->getPredicate(), Cmp->getOperand(0), Cmp->getOperand(1),
349       Info.getValue2Index(CmpInst::isSigned(Cmp->getPredicate())), NewIndices);
350 }
351 
352 bool ConstraintListTy::isValid(const ConstraintInfo &Info) const {
353   return all_of(Preconditions, [&Info](const PreconditionTy &C) {
354     DenseMap<Value *, unsigned> NewIndices;
355     auto R = getConstraint(C.Pred, C.Op0, C.Op1,
356                            Info.getValue2Index(CmpInst::isSigned(C.Pred)),
357                            NewIndices);
358     // TODO: properly check NewIndices.
359     return NewIndices.empty() && R.Preconditions.empty() && R.size() == 1 &&
360            Info.getCS(CmpInst::isSigned(C.Pred))
361                .isConditionImplied(R.get(0).Coefficients);
362   });
363 }
364 
365 namespace {
366 /// Represents either a condition that holds on entry to a block or a basic
367 /// block, with their respective Dominator DFS in and out numbers.
368 struct ConstraintOrBlock {
369   unsigned NumIn;
370   unsigned NumOut;
371   bool IsBlock;
372   bool Not;
373   union {
374     BasicBlock *BB;
375     CmpInst *Condition;
376   };
377 
378   ConstraintOrBlock(DomTreeNode *DTN)
379       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
380         BB(DTN->getBlock()) {}
381   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
382       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
383         Not(Not), Condition(Condition) {}
384 };
385 
386 struct StackEntry {
387   unsigned NumIn;
388   unsigned NumOut;
389   Instruction *Condition;
390   bool IsNot;
391   bool IsSigned = false;
392 
393   StackEntry(unsigned NumIn, unsigned NumOut, Instruction *Condition,
394              bool IsNot, bool IsSigned)
395       : NumIn(NumIn), NumOut(NumOut), Condition(Condition), IsNot(IsNot),
396         IsSigned(IsSigned) {}
397 };
398 } // namespace
399 
400 #ifndef NDEBUG
401 static void dumpWithNames(ConstraintTy &C,
402                           DenseMap<Value *, unsigned> &Value2Index) {
403   SmallVector<std::string> Names(Value2Index.size(), "");
404   for (auto &KV : Value2Index) {
405     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
406   }
407   ConstraintSystem CS;
408   CS.addVariableRowFill(C.Coefficients);
409   CS.dump(Names);
410 }
411 #endif
412 
413 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
414   bool Changed = false;
415   DT.updateDFSNumbers();
416 
417   ConstraintInfo Info;
418 
419   SmallVector<ConstraintOrBlock, 64> WorkList;
420 
421   // First, collect conditions implied by branches and blocks with their
422   // Dominator DFS in and out numbers.
423   for (BasicBlock &BB : F) {
424     if (!DT.getNode(&BB))
425       continue;
426     WorkList.emplace_back(DT.getNode(&BB));
427 
428     // True as long as long as the current instruction is guaranteed to execute.
429     bool GuaranteedToExecute = true;
430     // Scan BB for assume calls.
431     // TODO: also use this scan to queue conditions to simplify, so we can
432     // interleave facts from assumes and conditions to simplify in a single
433     // basic block. And to skip another traversal of each basic block when
434     // simplifying.
435     for (Instruction &I : BB) {
436       Value *Cond;
437       // For now, just handle assumes with a single compare as condition.
438       if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
439           isa<ICmpInst>(Cond)) {
440         if (GuaranteedToExecute) {
441           // The assume is guaranteed to execute when BB is entered, hence Cond
442           // holds on entry to BB.
443           WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false);
444         } else {
445           // Otherwise the condition only holds in the successors.
446           for (BasicBlock *Succ : successors(&BB))
447             WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond),
448                                   false);
449         }
450       }
451       GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
452     }
453 
454     auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
455     if (!Br || !Br->isConditional())
456       continue;
457 
458     // Returns true if we can add a known condition from BB to its successor
459     // block Succ. Each predecessor of Succ can either be BB or be dominated by
460     // Succ (e.g. the case when adding a condition from a pre-header to a loop
461     // header).
462     auto CanAdd = [&BB, &DT](BasicBlock *Succ) {
463       assert(isa<BranchInst>(BB.getTerminator()));
464       return any_of(successors(&BB),
465                     [Succ](const BasicBlock *S) { return S != Succ; }) &&
466              all_of(predecessors(Succ), [&BB, &DT, Succ](BasicBlock *Pred) {
467                return Pred == &BB || DT.dominates(Succ, Pred);
468              });
469     };
470     // If the condition is an OR of 2 compares and the false successor only has
471     // the current block as predecessor, queue both negated conditions for the
472     // false successor.
473     Value *Op0, *Op1;
474     if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) &&
475         isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) {
476       BasicBlock *FalseSuccessor = Br->getSuccessor(1);
477       if (CanAdd(FalseSuccessor)) {
478         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op0),
479                               true);
480         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op1),
481                               true);
482       }
483       continue;
484     }
485 
486     // If the condition is an AND of 2 compares and the true successor only has
487     // the current block as predecessor, queue both conditions for the true
488     // successor.
489     if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) &&
490         isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) {
491       BasicBlock *TrueSuccessor = Br->getSuccessor(0);
492       if (CanAdd(TrueSuccessor)) {
493         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op0),
494                               false);
495         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op1),
496                               false);
497       }
498       continue;
499     }
500 
501     auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
502     if (!CmpI)
503       continue;
504     if (CanAdd(Br->getSuccessor(0)))
505       WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
506     if (CanAdd(Br->getSuccessor(1)))
507       WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
508   }
509 
510   // Next, sort worklist by dominance, so that dominating blocks and conditions
511   // come before blocks and conditions dominated by them. If a block and a
512   // condition have the same numbers, the condition comes before the block, as
513   // it holds on entry to the block.
514   sort(WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
515     return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock);
516   });
517 
518   // Finally, process ordered worklist and eliminate implied conditions.
519   SmallVector<StackEntry, 16> DFSInStack;
520   for (ConstraintOrBlock &CB : WorkList) {
521     // First, pop entries from the stack that are out-of-scope for CB. Remove
522     // the corresponding entry from the constraint system.
523     while (!DFSInStack.empty()) {
524       auto &E = DFSInStack.back();
525       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
526                         << "\n");
527       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
528       assert(E.NumIn <= CB.NumIn);
529       if (CB.NumOut <= E.NumOut)
530         break;
531       LLVM_DEBUG(dbgs() << "Removing " << *E.Condition << " " << E.IsNot
532                         << "\n");
533       DFSInStack.pop_back();
534       Info.popLastConstraint(E.IsSigned);
535     }
536 
537     LLVM_DEBUG({
538       dbgs() << "Processing ";
539       if (CB.IsBlock)
540         dbgs() << *CB.BB;
541       else
542         dbgs() << *CB.Condition;
543       dbgs() << "\n";
544     });
545 
546     // For a block, check if any CmpInsts become known based on the current set
547     // of constraints.
548     if (CB.IsBlock) {
549       for (Instruction &I : *CB.BB) {
550         auto *Cmp = dyn_cast<ICmpInst>(&I);
551         if (!Cmp)
552           continue;
553 
554         DenseMap<Value *, unsigned> NewIndices;
555         auto R = getConstraint(Cmp, Info, NewIndices);
556         if (!R.isValidSingle(Info) || R.needsNewIndices(NewIndices))
557           continue;
558 
559         auto &CSToUse = Info.getCS(R.get(0).IsSigned);
560         if (CSToUse.isConditionImplied(R.get(0).Coefficients)) {
561           if (!DebugCounter::shouldExecute(EliminatedCounter))
562             continue;
563 
564           LLVM_DEBUG(dbgs() << "Condition " << *Cmp
565                             << " implied by dominating constraints\n");
566           LLVM_DEBUG({
567             for (auto &E : reverse(DFSInStack))
568               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
569           });
570           Cmp->replaceUsesWithIf(
571               ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) {
572                 // Conditions in an assume trivially simplify to true. Skip uses
573                 // in assume calls to not destroy the available information.
574                 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
575                 return !II || II->getIntrinsicID() != Intrinsic::assume;
576               });
577           NumCondsRemoved++;
578           Changed = true;
579         }
580         if (CSToUse.isConditionImplied(
581                 ConstraintSystem::negate(R.get(0).Coefficients))) {
582           if (!DebugCounter::shouldExecute(EliminatedCounter))
583             continue;
584 
585           LLVM_DEBUG(dbgs() << "Condition !" << *Cmp
586                             << " implied by dominating constraints\n");
587           LLVM_DEBUG({
588             for (auto &E : reverse(DFSInStack))
589               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
590           });
591           Cmp->replaceAllUsesWith(
592               ConstantInt::getFalse(F.getParent()->getContext()));
593           NumCondsRemoved++;
594           Changed = true;
595         }
596       }
597       continue;
598     }
599 
600     // Set up a function to restore the predicate at the end of the scope if it
601     // has been negated. Negate the predicate in-place, if required.
602     auto *CI = dyn_cast<ICmpInst>(CB.Condition);
603     auto PredicateRestorer = make_scope_exit([CI, &CB]() {
604       if (CB.Not && CI)
605         CI->setPredicate(CI->getInversePredicate());
606     });
607     if (CB.Not) {
608       if (CI) {
609         CI->setPredicate(CI->getInversePredicate());
610       } else {
611         LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n");
612         continue;
613       }
614     }
615 
616     // Otherwise, add the condition to the system and stack, if we can transform
617     // it into a constraint.
618     DenseMap<Value *, unsigned> NewIndices;
619     auto R = getConstraint(CB.Condition, Info, NewIndices);
620     if (!R.isValid(Info))
621       continue;
622 
623     for (auto &KV : NewIndices)
624       Info.getValue2Index(CmpInst::isSigned(CB.Condition->getPredicate()))
625           .insert(KV);
626 
627     LLVM_DEBUG(dbgs() << "Adding " << *CB.Condition << " " << CB.Not << "\n");
628     bool Added = false;
629     for (auto &E : R.Constraints) {
630       auto &CSToUse = Info.getCS(E.IsSigned);
631       if (E.Coefficients.empty())
632         continue;
633 
634       LLVM_DEBUG({
635         dbgs() << "  constraint: ";
636         dumpWithNames(E, Info.getValue2Index(E.IsSigned));
637       });
638 
639       Added |= CSToUse.addVariableRowFill(E.Coefficients);
640 
641       // If R has been added to the system, queue it for removal once it goes
642       // out-of-scope.
643       if (Added)
644         DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not,
645                                 E.IsSigned);
646     }
647   }
648 
649 #ifndef NDEBUG
650   unsigned SignedEntries =
651       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
652   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
653          "updates to CS and DFSInStack are out of sync");
654   assert(Info.getCS(true).size() == SignedEntries &&
655          "updates to CS and DFSInStack are out of sync");
656 #endif
657 
658   return Changed;
659 }
660 
661 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
662                                                  FunctionAnalysisManager &AM) {
663   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
664   if (!eliminateConstraints(F, DT))
665     return PreservedAnalyses::all();
666 
667   PreservedAnalyses PA;
668   PA.preserve<DominatorTreeAnalysis>();
669   PA.preserveSet<CFGAnalyses>();
670   return PA;
671 }
672 
673 namespace {
674 
675 class ConstraintElimination : public FunctionPass {
676 public:
677   static char ID;
678 
679   ConstraintElimination() : FunctionPass(ID) {
680     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
681   }
682 
683   bool runOnFunction(Function &F) override {
684     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
685     return eliminateConstraints(F, DT);
686   }
687 
688   void getAnalysisUsage(AnalysisUsage &AU) const override {
689     AU.setPreservesCFG();
690     AU.addRequired<DominatorTreeWrapperPass>();
691     AU.addPreserved<GlobalsAAWrapperPass>();
692     AU.addPreserved<DominatorTreeWrapperPass>();
693   }
694 };
695 
696 } // end anonymous namespace
697 
698 char ConstraintElimination::ID = 0;
699 
700 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
701                       "Constraint Elimination", false, false)
702 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
703 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
704 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
705                     "Constraint Elimination", false, false)
706 
707 FunctionPass *llvm::createConstraintEliminationPass() {
708   return new ConstraintElimination();
709 }
710