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