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