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