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