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