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       if (BB.getSingleSuccessor()) {
423         assert(BB.getSingleSuccessor() == Succ);
424         return DT.properlyDominates(&BB, Succ);
425       }
426       return any_of(successors(&BB),
427                     [Succ](const BasicBlock *S) { return S != Succ; }) &&
428              all_of(predecessors(Succ), [&BB, &DT, Succ](BasicBlock *Pred) {
429                return Pred == &BB || DT.dominates(Succ, Pred);
430              });
431     };
432 
433     // True as long as long as the current instruction is guaranteed to execute.
434     bool GuaranteedToExecute = true;
435     // Scan BB for assume calls.
436     // TODO: also use this scan to queue conditions to simplify, so we can
437     // interleave facts from assumes and conditions to simplify in a single
438     // basic block. And to skip another traversal of each basic block when
439     // simplifying.
440     for (Instruction &I : BB) {
441       Value *Cond;
442       // For now, just handle assumes with a single compare as condition.
443       if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
444           isa<ICmpInst>(Cond)) {
445         if (GuaranteedToExecute) {
446           // The assume is guaranteed to execute when BB is entered, hence Cond
447           // holds on entry to BB.
448           WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false);
449         } else {
450           // Otherwise the condition only holds in the successors.
451           for (BasicBlock *Succ : successors(&BB)) {
452             if (!CanAdd(Succ))
453               continue;
454             WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond),
455                                   false);
456           }
457         }
458       }
459       GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
460     }
461 
462     auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
463     if (!Br || !Br->isConditional())
464       continue;
465 
466     // If the condition is an OR of 2 compares and the false successor only has
467     // the current block as predecessor, queue both negated conditions for the
468     // false successor.
469     Value *Op0, *Op1;
470     if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) &&
471         isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) {
472       BasicBlock *FalseSuccessor = Br->getSuccessor(1);
473       if (CanAdd(FalseSuccessor)) {
474         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op0),
475                               true);
476         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op1),
477                               true);
478       }
479       continue;
480     }
481 
482     // If the condition is an AND of 2 compares and the true successor only has
483     // the current block as predecessor, queue both conditions for the true
484     // successor.
485     if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) &&
486         isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) {
487       BasicBlock *TrueSuccessor = Br->getSuccessor(0);
488       if (CanAdd(TrueSuccessor)) {
489         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op0),
490                               false);
491         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op1),
492                               false);
493       }
494       continue;
495     }
496 
497     auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
498     if (!CmpI)
499       continue;
500     if (CanAdd(Br->getSuccessor(0)))
501       WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
502     if (CanAdd(Br->getSuccessor(1)))
503       WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
504   }
505 
506   // Next, sort worklist by dominance, so that dominating blocks and conditions
507   // come before blocks and conditions dominated by them. If a block and a
508   // condition have the same numbers, the condition comes before the block, as
509   // it holds on entry to the block.
510   sort(WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
511     return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock);
512   });
513 
514   // Finally, process ordered worklist and eliminate implied conditions.
515   SmallVector<StackEntry, 16> DFSInStack;
516   for (ConstraintOrBlock &CB : WorkList) {
517     // First, pop entries from the stack that are out-of-scope for CB. Remove
518     // the corresponding entry from the constraint system.
519     while (!DFSInStack.empty()) {
520       auto &E = DFSInStack.back();
521       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
522                         << "\n");
523       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
524       assert(E.NumIn <= CB.NumIn);
525       if (CB.NumOut <= E.NumOut)
526         break;
527       LLVM_DEBUG(dbgs() << "Removing " << *E.Condition << " " << E.IsNot
528                         << "\n");
529       Info.popLastConstraint(E.IsSigned);
530       // Remove variables in the system that went out of scope.
531       auto &Mapping = Info.getValue2Index(E.IsSigned);
532       for (Value *V : E.ValuesToRelease)
533         Mapping.erase(V);
534       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
535       DFSInStack.pop_back();
536     }
537 
538     LLVM_DEBUG({
539       dbgs() << "Processing ";
540       if (CB.IsBlock)
541         dbgs() << *CB.BB;
542       else
543         dbgs() << *CB.Condition;
544       dbgs() << "\n";
545     });
546 
547     // For a block, check if any CmpInsts become known based on the current set
548     // of constraints.
549     if (CB.IsBlock) {
550       for (Instruction &I : *CB.BB) {
551         auto *Cmp = dyn_cast<ICmpInst>(&I);
552         if (!Cmp)
553           continue;
554 
555         DenseMap<Value *, unsigned> NewIndices;
556         auto R = getConstraint(Cmp, Info, NewIndices);
557         if (R.IsEq || R.size() < 2 || R.needsNewIndices(NewIndices) ||
558             !R.isValid(Info))
559           continue;
560 
561         auto &CSToUse = Info.getCS(R.IsSigned);
562         if (CSToUse.isConditionImplied(R.Coefficients)) {
563           if (!DebugCounter::shouldExecute(EliminatedCounter))
564             continue;
565 
566           LLVM_DEBUG(dbgs() << "Condition " << *Cmp
567                             << " implied by dominating constraints\n");
568           LLVM_DEBUG({
569             for (auto &E : reverse(DFSInStack))
570               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
571           });
572           Cmp->replaceUsesWithIf(
573               ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) {
574                 // Conditions in an assume trivially simplify to true. Skip uses
575                 // in assume calls to not destroy the available information.
576                 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
577                 return !II || II->getIntrinsicID() != Intrinsic::assume;
578               });
579           NumCondsRemoved++;
580           Changed = true;
581         }
582         if (CSToUse.isConditionImplied(
583                 ConstraintSystem::negate(R.Coefficients))) {
584           if (!DebugCounter::shouldExecute(EliminatedCounter))
585             continue;
586 
587           LLVM_DEBUG(dbgs() << "Condition !" << *Cmp
588                             << " implied by dominating constraints\n");
589           LLVM_DEBUG({
590             for (auto &E : reverse(DFSInStack))
591               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
592           });
593           Cmp->replaceAllUsesWith(
594               ConstantInt::getFalse(F.getParent()->getContext()));
595           NumCondsRemoved++;
596           Changed = true;
597         }
598       }
599       continue;
600     }
601 
602     // Set up a function to restore the predicate at the end of the scope if it
603     // has been negated. Negate the predicate in-place, if required.
604     auto *CI = dyn_cast<ICmpInst>(CB.Condition);
605     auto PredicateRestorer = make_scope_exit([CI, &CB]() {
606       if (CB.Not && CI)
607         CI->setPredicate(CI->getInversePredicate());
608     });
609     if (CB.Not) {
610       if (CI) {
611         CI->setPredicate(CI->getInversePredicate());
612       } else {
613         LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n");
614         continue;
615       }
616     }
617 
618     // Otherwise, add the condition to the system and stack, if we can transform
619     // it into a constraint.
620     DenseMap<Value *, unsigned> NewIndices;
621     auto R = getConstraint(CB.Condition, Info, NewIndices);
622     if (!R.isValid(Info))
623       continue;
624 
625     LLVM_DEBUG(dbgs() << "Adding " << *CB.Condition << " " << CB.Not << "\n");
626     bool Added = false;
627     assert(CmpInst::isSigned(CB.Condition->getPredicate()) == R.IsSigned &&
628            "condition and constraint signs must match");
629     auto &CSToUse = Info.getCS(R.IsSigned);
630     if (R.Coefficients.empty())
631       continue;
632 
633     Added |= CSToUse.addVariableRowFill(R.Coefficients);
634 
635     // If R has been added to the system, queue it for removal once it goes
636     // out-of-scope.
637     if (Added) {
638       SmallVector<Value *, 2> ValuesToRelease;
639       for (auto &KV : NewIndices) {
640         Info.getValue2Index(R.IsSigned).insert(KV);
641         ValuesToRelease.push_back(KV.first);
642       }
643 
644       LLVM_DEBUG({
645         dbgs() << "  constraint: ";
646         dumpWithNames(R, Info.getValue2Index(R.IsSigned));
647       });
648 
649       DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not,
650                               R.IsSigned, ValuesToRelease);
651 
652       if (R.IsEq) {
653         // Also add the inverted constraint for equality constraints.
654         for (auto &Coeff : R.Coefficients)
655           Coeff *= -1;
656         CSToUse.addVariableRowFill(R.Coefficients);
657 
658         DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not,
659                                 R.IsSigned, SmallVector<Value *, 2>());
660       }
661     }
662   }
663 
664 #ifndef NDEBUG
665   unsigned SignedEntries =
666       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
667   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
668          "updates to CS and DFSInStack are out of sync");
669   assert(Info.getCS(true).size() == SignedEntries &&
670          "updates to CS and DFSInStack are out of sync");
671 #endif
672 
673   return Changed;
674 }
675 
676 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
677                                                  FunctionAnalysisManager &AM) {
678   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
679   if (!eliminateConstraints(F, DT))
680     return PreservedAnalyses::all();
681 
682   PreservedAnalyses PA;
683   PA.preserve<DominatorTreeAnalysis>();
684   PA.preserveSet<CFGAnalyses>();
685   return PA;
686 }
687 
688 namespace {
689 
690 class ConstraintElimination : public FunctionPass {
691 public:
692   static char ID;
693 
694   ConstraintElimination() : FunctionPass(ID) {
695     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
696   }
697 
698   bool runOnFunction(Function &F) override {
699     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
700     return eliminateConstraints(F, DT);
701   }
702 
703   void getAnalysisUsage(AnalysisUsage &AU) const override {
704     AU.setPreservesCFG();
705     AU.addRequired<DominatorTreeWrapperPass>();
706     AU.addPreserved<GlobalsAAWrapperPass>();
707     AU.addPreserved<DominatorTreeWrapperPass>();
708   }
709 };
710 
711 } // end anonymous namespace
712 
713 char ConstraintElimination::ID = 0;
714 
715 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
716                       "Constraint Elimination", false, false)
717 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
718 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
719 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
720                     "Constraint Elimination", false, false)
721 
722 FunctionPass *llvm::createConstraintEliminationPass() {
723   return new ConstraintElimination();
724 }
725