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