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