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