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