xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 0a0181dc2061fc60b309f231a5b2f6251046c552)
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/OptimizationRemarkEmitter.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GetElementPtrTypeIterator.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/PatternMatch.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/DebugCounter.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/ValueMapper.h"
39 
40 #include <cmath>
41 #include <string>
42 
43 using namespace llvm;
44 using namespace PatternMatch;
45 
46 #define DEBUG_TYPE "constraint-elimination"
47 
48 STATISTIC(NumCondsRemoved, "Number of instructions removed");
49 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
50               "Controls which conditions are eliminated");
51 
52 static cl::opt<unsigned>
53     MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden,
54             cl::desc("Maximum number of rows to keep in constraint system"));
55 
56 static cl::opt<bool> DumpReproducers(
57     "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden,
58     cl::desc("Dump IR to reproduce successful transformations."));
59 
60 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
61 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
62 
63 // A helper to multiply 2 signed integers where overflowing is allowed.
64 static int64_t multiplyWithOverflow(int64_t A, int64_t B) {
65   int64_t Result;
66   MulOverflow(A, B, Result);
67   return Result;
68 }
69 
70 // A helper to add 2 signed integers where overflowing is allowed.
71 static int64_t addWithOverflow(int64_t A, int64_t B) {
72   int64_t Result;
73   AddOverflow(A, B, Result);
74   return Result;
75 }
76 
77 namespace {
78 
79 class ConstraintInfo;
80 
81 struct StackEntry {
82   unsigned NumIn;
83   unsigned NumOut;
84   bool IsSigned = false;
85   /// Variables that can be removed from the system once the stack entry gets
86   /// removed.
87   SmallVector<Value *, 2> ValuesToRelease;
88 
89   StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
90              SmallVector<Value *, 2> ValuesToRelease)
91       : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
92         ValuesToRelease(ValuesToRelease) {}
93 };
94 
95 /// Struct to express a pre-condition of the form %Op0 Pred %Op1.
96 struct PreconditionTy {
97   CmpInst::Predicate Pred;
98   Value *Op0;
99   Value *Op1;
100 
101   PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
102       : Pred(Pred), Op0(Op0), Op1(Op1) {}
103 };
104 
105 struct ConstraintTy {
106   SmallVector<int64_t, 8> Coefficients;
107   SmallVector<PreconditionTy, 2> Preconditions;
108 
109   SmallVector<SmallVector<int64_t, 8>> ExtraInfo;
110 
111   bool IsSigned = false;
112   bool IsEq = false;
113 
114   ConstraintTy() = default;
115 
116   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned)
117       : Coefficients(Coefficients), IsSigned(IsSigned) {}
118 
119   unsigned size() const { return Coefficients.size(); }
120 
121   unsigned empty() const { return Coefficients.empty(); }
122 
123   /// Returns true if all preconditions for this list of constraints are
124   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
125   bool isValid(const ConstraintInfo &Info) const;
126 };
127 
128 /// Wrapper encapsulating separate constraint systems and corresponding value
129 /// mappings for both unsigned and signed information. Facts are added to and
130 /// conditions are checked against the corresponding system depending on the
131 /// signed-ness of their predicates. While the information is kept separate
132 /// based on signed-ness, certain conditions can be transferred between the two
133 /// systems.
134 class ConstraintInfo {
135 
136   ConstraintSystem UnsignedCS;
137   ConstraintSystem SignedCS;
138 
139   const DataLayout &DL;
140 
141 public:
142   ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
143       : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {}
144 
145   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
146     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
147   }
148   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
149     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
150   }
151 
152   ConstraintSystem &getCS(bool Signed) {
153     return Signed ? SignedCS : UnsignedCS;
154   }
155   const ConstraintSystem &getCS(bool Signed) const {
156     return Signed ? SignedCS : UnsignedCS;
157   }
158 
159   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
160   void popLastNVariables(bool Signed, unsigned N) {
161     getCS(Signed).popLastNVariables(N);
162   }
163 
164   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
165 
166   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
167                unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
168 
169   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
170   /// constraints, using indices from the corresponding constraint system.
171   /// New variables that need to be added to the system are collected in
172   /// \p NewVariables.
173   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
174                              SmallVectorImpl<Value *> &NewVariables) const;
175 
176   /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
177   /// constraints using getConstraint. Returns an empty constraint if the result
178   /// cannot be used to query the existing constraint system, e.g. because it
179   /// would require adding new variables. Also tries to convert signed
180   /// predicates to unsigned ones if possible to allow using the unsigned system
181   /// which increases the effectiveness of the signed <-> unsigned transfer
182   /// logic.
183   ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
184                                        Value *Op1) const;
185 
186   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
187   /// system if \p Pred is signed/unsigned.
188   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
189                              unsigned NumIn, unsigned NumOut,
190                              SmallVectorImpl<StackEntry> &DFSInStack);
191 };
192 
193 /// Represents a (Coefficient * Variable) entry after IR decomposition.
194 struct DecompEntry {
195   int64_t Coefficient;
196   Value *Variable;
197   /// True if the variable is known positive in the current constraint.
198   bool IsKnownNonNegative;
199 
200   DecompEntry(int64_t Coefficient, Value *Variable,
201               bool IsKnownNonNegative = false)
202       : Coefficient(Coefficient), Variable(Variable),
203         IsKnownNonNegative(IsKnownNonNegative) {}
204 };
205 
206 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
207 struct Decomposition {
208   int64_t Offset = 0;
209   SmallVector<DecompEntry, 3> Vars;
210 
211   Decomposition(int64_t Offset) : Offset(Offset) {}
212   Decomposition(Value *V, bool IsKnownNonNegative = false) {
213     Vars.emplace_back(1, V, IsKnownNonNegative);
214   }
215   Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
216       : Offset(Offset), Vars(Vars) {}
217 
218   void add(int64_t OtherOffset) {
219     Offset = addWithOverflow(Offset, OtherOffset);
220   }
221 
222   void add(const Decomposition &Other) {
223     add(Other.Offset);
224     append_range(Vars, Other.Vars);
225   }
226 
227   void mul(int64_t Factor) {
228     Offset = multiplyWithOverflow(Offset, Factor);
229     for (auto &Var : Vars)
230       Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor);
231   }
232 };
233 
234 } // namespace
235 
236 static Decomposition decompose(Value *V,
237                                SmallVectorImpl<PreconditionTy> &Preconditions,
238                                bool IsSigned, const DataLayout &DL);
239 
240 static bool canUseSExt(ConstantInt *CI) {
241   const APInt &Val = CI->getValue();
242   return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
243 }
244 
245 static Decomposition
246 decomposeGEP(GEPOperator &GEP, SmallVectorImpl<PreconditionTy> &Preconditions,
247              bool IsSigned, const DataLayout &DL) {
248   // Do not reason about pointers where the index size is larger than 64 bits,
249   // as the coefficients used to encode constraints are 64 bit integers.
250   if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
251     return &GEP;
252 
253   if (!GEP.isInBounds())
254     return &GEP;
255 
256   assert(!IsSigned && "The logic below only supports decomposition for "
257                       "unsinged predicates at the moment.");
258   Type *PtrTy = GEP.getType()->getScalarType();
259   unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy);
260   MapVector<Value *, APInt> VariableOffsets;
261   APInt ConstantOffset(BitWidth, 0);
262   if (!GEP.collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
263     return &GEP;
264 
265   // Handle the (gep (gep ....), C) case by incrementing the constant
266   // coefficient of the inner GEP, if C is a constant.
267   auto *InnerGEP = dyn_cast<GEPOperator>(GEP.getPointerOperand());
268   if (VariableOffsets.empty() && InnerGEP && InnerGEP->getNumOperands() == 2) {
269     auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL);
270     Result.add(ConstantOffset.getSExtValue());
271 
272     if (ConstantOffset.isNegative()) {
273       unsigned Scale = DL.getTypeAllocSize(InnerGEP->getResultElementType());
274       int64_t ConstantOffsetI = ConstantOffset.getSExtValue();
275       if (ConstantOffsetI % Scale != 0)
276         return &GEP;
277       // Add pre-condition ensuring the GEP is increasing monotonically and
278       // can be de-composed.
279       // Both sides are normalized by being divided by Scale.
280       Preconditions.emplace_back(
281           CmpInst::ICMP_SGE, InnerGEP->getOperand(1),
282           ConstantInt::get(InnerGEP->getOperand(1)->getType(),
283                            -1 * (ConstantOffsetI / Scale)));
284     }
285     return Result;
286   }
287 
288   Decomposition Result(ConstantOffset.getSExtValue(),
289                        DecompEntry(1, GEP.getPointerOperand()));
290   for (auto [Index, Scale] : VariableOffsets) {
291     auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
292     IdxResult.mul(Scale.getSExtValue());
293     Result.add(IdxResult);
294 
295     // If Op0 is signed non-negative, the GEP is increasing monotonically and
296     // can be de-composed.
297     if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
298       Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
299                                  ConstantInt::get(Index->getType(), 0));
300   }
301   return Result;
302 }
303 
304 // Decomposes \p V into a constant offset + list of pairs { Coefficient,
305 // Variable } where Coefficient * Variable. The sum of the constant offset and
306 // pairs equals \p V.
307 static Decomposition decompose(Value *V,
308                                SmallVectorImpl<PreconditionTy> &Preconditions,
309                                bool IsSigned, const DataLayout &DL) {
310 
311   auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B,
312                                                       bool IsSignedB) {
313     auto ResA = decompose(A, Preconditions, IsSigned, DL);
314     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
315     ResA.add(ResB);
316     return ResA;
317   };
318 
319   // Decompose \p V used with a signed predicate.
320   if (IsSigned) {
321     if (auto *CI = dyn_cast<ConstantInt>(V)) {
322       if (canUseSExt(CI))
323         return CI->getSExtValue();
324     }
325     Value *Op0;
326     Value *Op1;
327     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
328       return MergeResults(Op0, Op1, IsSigned);
329 
330     return V;
331   }
332 
333   if (auto *CI = dyn_cast<ConstantInt>(V)) {
334     if (CI->uge(MaxConstraintValue))
335       return V;
336     return int64_t(CI->getZExtValue());
337   }
338 
339   if (auto *GEP = dyn_cast<GEPOperator>(V))
340     return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
341 
342   Value *Op0;
343   bool IsKnownNonNegative = false;
344   if (match(V, m_ZExt(m_Value(Op0)))) {
345     IsKnownNonNegative = true;
346     V = Op0;
347   }
348 
349   Value *Op1;
350   ConstantInt *CI;
351   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
352     return MergeResults(Op0, Op1, IsSigned);
353   }
354   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
355     if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
356       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
357                                  ConstantInt::get(Op0->getType(), 0));
358     if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
359       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
360                                  ConstantInt::get(Op1->getType(), 0));
361 
362     return MergeResults(Op0, Op1, IsSigned);
363   }
364 
365   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
366       canUseSExt(CI)) {
367     Preconditions.emplace_back(
368         CmpInst::ICMP_UGE, Op0,
369         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
370     return MergeResults(Op0, CI, true);
371   }
372 
373   // Decompose or as an add if there are no common bits between the operands.
374   if (match(V, m_Or(m_Value(Op0), m_ConstantInt(CI))) &&
375       haveNoCommonBitsSet(Op0, CI, DL)) {
376     return MergeResults(Op0, CI, IsSigned);
377   }
378 
379   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
380     if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64)
381       return {V, IsKnownNonNegative};
382     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
383     Result.mul(int64_t{1} << CI->getSExtValue());
384     return Result;
385   }
386 
387   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
388       (!CI->isNegative())) {
389     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
390     Result.mul(CI->getSExtValue());
391     return Result;
392   }
393 
394   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI))
395     return {-1 * CI->getSExtValue(), {{1, Op0}}};
396   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
397     return {0, {{1, Op0}, {-1, Op1}}};
398 
399   return {V, IsKnownNonNegative};
400 }
401 
402 ConstraintTy
403 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
404                               SmallVectorImpl<Value *> &NewVariables) const {
405   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
406   bool IsEq = false;
407   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
408   switch (Pred) {
409   case CmpInst::ICMP_UGT:
410   case CmpInst::ICMP_UGE:
411   case CmpInst::ICMP_SGT:
412   case CmpInst::ICMP_SGE: {
413     Pred = CmpInst::getSwappedPredicate(Pred);
414     std::swap(Op0, Op1);
415     break;
416   }
417   case CmpInst::ICMP_EQ:
418     if (match(Op1, m_Zero())) {
419       Pred = CmpInst::ICMP_ULE;
420     } else {
421       IsEq = true;
422       Pred = CmpInst::ICMP_ULE;
423     }
424     break;
425   case CmpInst::ICMP_NE:
426     if (!match(Op1, m_Zero()))
427       return {};
428     Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
429     std::swap(Op0, Op1);
430     break;
431   default:
432     break;
433   }
434 
435   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
436       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
437     return {};
438 
439   SmallVector<PreconditionTy, 4> Preconditions;
440   bool IsSigned = CmpInst::isSigned(Pred);
441   auto &Value2Index = getValue2Index(IsSigned);
442   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
443                         Preconditions, IsSigned, DL);
444   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
445                         Preconditions, IsSigned, DL);
446   int64_t Offset1 = ADec.Offset;
447   int64_t Offset2 = BDec.Offset;
448   Offset1 *= -1;
449 
450   auto &VariablesA = ADec.Vars;
451   auto &VariablesB = BDec.Vars;
452 
453   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
454   // new entry to NewVariables.
455   DenseMap<Value *, unsigned> NewIndexMap;
456   auto GetOrAddIndex = [&Value2Index, &NewVariables,
457                         &NewIndexMap](Value *V) -> unsigned {
458     auto V2I = Value2Index.find(V);
459     if (V2I != Value2Index.end())
460       return V2I->second;
461     auto Insert =
462         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
463     if (Insert.second)
464       NewVariables.push_back(V);
465     return Insert.first->second;
466   };
467 
468   // Make sure all variables have entries in Value2Index or NewVariables.
469   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
470     GetOrAddIndex(KV.Variable);
471 
472   // Build result constraint, by first adding all coefficients from A and then
473   // subtracting all coefficients from B.
474   ConstraintTy Res(
475       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
476       IsSigned);
477   // Collect variables that are known to be positive in all uses in the
478   // constraint.
479   DenseMap<Value *, bool> KnownNonNegativeVariables;
480   Res.IsEq = IsEq;
481   auto &R = Res.Coefficients;
482   for (const auto &KV : VariablesA) {
483     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
484     auto I =
485         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
486     I.first->second &= KV.IsKnownNonNegative;
487   }
488 
489   for (const auto &KV : VariablesB) {
490     if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient,
491                     R[GetOrAddIndex(KV.Variable)]))
492       return {};
493     auto I =
494         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
495     I.first->second &= KV.IsKnownNonNegative;
496   }
497 
498   int64_t OffsetSum;
499   if (AddOverflow(Offset1, Offset2, OffsetSum))
500     return {};
501   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
502     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
503       return {};
504   R[0] = OffsetSum;
505   Res.Preconditions = std::move(Preconditions);
506 
507   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
508   // variables.
509   while (!NewVariables.empty()) {
510     int64_t Last = R.back();
511     if (Last != 0)
512       break;
513     R.pop_back();
514     Value *RemovedV = NewVariables.pop_back_val();
515     NewIndexMap.erase(RemovedV);
516   }
517 
518   // Add extra constraints for variables that are known positive.
519   for (auto &KV : KnownNonNegativeVariables) {
520     if (!KV.second ||
521         (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first)))
522       continue;
523     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
524     C[GetOrAddIndex(KV.first)] = -1;
525     Res.ExtraInfo.push_back(C);
526   }
527   return Res;
528 }
529 
530 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
531                                                      Value *Op0,
532                                                      Value *Op1) const {
533   // If both operands are known to be non-negative, change signed predicates to
534   // unsigned ones. This increases the reasoning effectiveness in combination
535   // with the signed <-> unsigned transfer logic.
536   if (CmpInst::isSigned(Pred) &&
537       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
538       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
539     Pred = CmpInst::getUnsignedPredicate(Pred);
540 
541   SmallVector<Value *> NewVariables;
542   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
543   if (R.IsEq || !NewVariables.empty())
544     return {};
545   return R;
546 }
547 
548 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
549   return Coefficients.size() > 0 &&
550          all_of(Preconditions, [&Info](const PreconditionTy &C) {
551            return Info.doesHold(C.Pred, C.Op0, C.Op1);
552          });
553 }
554 
555 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
556                               Value *B) const {
557   auto R = getConstraintForSolving(Pred, A, B);
558   return R.Preconditions.empty() && !R.empty() &&
559          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
560 }
561 
562 void ConstraintInfo::transferToOtherSystem(
563     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
564     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
565   // Check if we can combine facts from the signed and unsigned systems to
566   // derive additional facts.
567   if (!A->getType()->isIntegerTy())
568     return;
569   // FIXME: This currently depends on the order we add facts. Ideally we
570   // would first add all known facts and only then try to add additional
571   // facts.
572   switch (Pred) {
573   default:
574     break;
575   case CmpInst::ICMP_ULT:
576     //  If B is a signed positive constant, A >=s 0 and A <s B.
577     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
578       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
579               NumOut, DFSInStack);
580       addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack);
581     }
582     break;
583   case CmpInst::ICMP_SLT:
584     if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0)))
585       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
586     break;
587   case CmpInst::ICMP_SGT: {
588     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
589       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
590               NumOut, DFSInStack);
591     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0)))
592       addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
593 
594     break;
595   }
596   case CmpInst::ICMP_SGE:
597     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) {
598       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
599     }
600     break;
601   }
602 }
603 
604 namespace {
605 /// Represents either
606 ///  * a condition that holds on entry to a block (=conditional fact)
607 ///  * an assume (=assume fact)
608 ///  * an instruction to simplify.
609 /// It also tracks the Dominator DFS in and out numbers for each entry.
610 struct FactOrCheck {
611   Instruction *Inst;
612   unsigned NumIn;
613   unsigned NumOut;
614   bool IsCheck;
615   bool Not;
616 
617   FactOrCheck(DomTreeNode *DTN, Instruction *Inst, bool IsCheck, bool Not)
618       : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
619         IsCheck(IsCheck), Not(Not) {}
620 
621   static FactOrCheck getFact(DomTreeNode *DTN, Instruction *Inst,
622                              bool Not = false) {
623     return FactOrCheck(DTN, Inst, false, Not);
624   }
625 
626   static FactOrCheck getCheck(DomTreeNode *DTN, Instruction *Inst) {
627     return FactOrCheck(DTN, Inst, true, false);
628   }
629 
630   bool isAssumeFact() const {
631     if (!IsCheck && isa<IntrinsicInst>(Inst)) {
632       assert(match(Inst, m_Intrinsic<Intrinsic::assume>()));
633       return true;
634     }
635     return false;
636   }
637 
638   bool isConditionFact() const { return !IsCheck && isa<CmpInst>(Inst); }
639 };
640 
641 /// Keep state required to build worklist.
642 struct State {
643   DominatorTree &DT;
644   SmallVector<FactOrCheck, 64> WorkList;
645 
646   State(DominatorTree &DT) : DT(DT) {}
647 
648   /// Process block \p BB and add known facts to work-list.
649   void addInfoFor(BasicBlock &BB);
650 
651   /// Returns true if we can add a known condition from BB to its successor
652   /// block Succ.
653   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
654     return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
655   }
656 };
657 
658 } // namespace
659 
660 #ifndef NDEBUG
661 
662 static void dumpConstraint(ArrayRef<int64_t> C,
663                            const DenseMap<Value *, unsigned> &Value2Index) {
664   ConstraintSystem CS(Value2Index);
665   CS.addVariableRowFill(C);
666   CS.dump();
667 }
668 #endif
669 
670 void State::addInfoFor(BasicBlock &BB) {
671   // True as long as long as the current instruction is guaranteed to execute.
672   bool GuaranteedToExecute = true;
673   // Queue conditions and assumes.
674   for (Instruction &I : BB) {
675     if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
676       WorkList.push_back(FactOrCheck::getCheck(DT.getNode(&BB), Cmp));
677       continue;
678     }
679 
680     if (match(&I, m_Intrinsic<Intrinsic::ssub_with_overflow>())) {
681       WorkList.push_back(FactOrCheck::getCheck(DT.getNode(&BB), &I));
682       continue;
683     }
684 
685     Value *Cond;
686     // For now, just handle assumes with a single compare as condition.
687     if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
688         isa<ICmpInst>(Cond)) {
689       if (GuaranteedToExecute) {
690         // The assume is guaranteed to execute when BB is entered, hence Cond
691         // holds on entry to BB.
692         WorkList.emplace_back(FactOrCheck::getFact(DT.getNode(I.getParent()),
693                                                    cast<Instruction>(Cond)));
694       } else {
695         WorkList.emplace_back(
696             FactOrCheck::getFact(DT.getNode(I.getParent()), &I));
697       }
698     }
699     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
700   }
701 
702   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
703   if (!Br || !Br->isConditional())
704     return;
705 
706   Value *Cond = Br->getCondition();
707 
708   // If the condition is a chain of ORs/AND and the successor only has the
709   // current block as predecessor, queue conditions for the successor.
710   Value *Op0, *Op1;
711   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
712       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
713     bool IsOr = match(Cond, m_LogicalOr());
714     bool IsAnd = match(Cond, m_LogicalAnd());
715     // If there's a select that matches both AND and OR, we need to commit to
716     // one of the options. Arbitrarily pick OR.
717     if (IsOr && IsAnd)
718       IsAnd = false;
719 
720     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
721     if (canAddSuccessor(BB, Successor)) {
722       SmallVector<Value *> CondWorkList;
723       SmallPtrSet<Value *, 8> SeenCond;
724       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
725         if (SeenCond.insert(V).second)
726           CondWorkList.push_back(V);
727       };
728       QueueValue(Op1);
729       QueueValue(Op0);
730       while (!CondWorkList.empty()) {
731         Value *Cur = CondWorkList.pop_back_val();
732         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
733           WorkList.emplace_back(
734               FactOrCheck::getFact(DT.getNode(Successor), Cmp, IsOr));
735           continue;
736         }
737         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
738           QueueValue(Op1);
739           QueueValue(Op0);
740           continue;
741         }
742         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
743           QueueValue(Op1);
744           QueueValue(Op0);
745           continue;
746         }
747       }
748     }
749     return;
750   }
751 
752   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
753   if (!CmpI)
754     return;
755   if (canAddSuccessor(BB, Br->getSuccessor(0)))
756     WorkList.emplace_back(
757         FactOrCheck::getFact(DT.getNode(Br->getSuccessor(0)), CmpI));
758   if (canAddSuccessor(BB, Br->getSuccessor(1)))
759     WorkList.emplace_back(
760         FactOrCheck::getFact(DT.getNode(Br->getSuccessor(1)), CmpI, true));
761 }
762 
763 namespace {
764 /// Helper to keep track of a condition and if it should be treated as negated
765 /// for reproducer construction.
766 struct ReproducerEntry {
767   CmpInst *Cond;
768   bool IsNot;
769 
770   ReproducerEntry(CmpInst *Cond, bool IsNot) : Cond(Cond), IsNot(IsNot) {}
771 };
772 } // namespace
773 
774 /// Helper function to generate a reproducer function for simplifying \p Cond.
775 /// The reproducer function contains a series of @llvm.assume calls, one for
776 /// each condition in \p Stack. For each condition, the operand instruction are
777 /// cloned until we reach operands that have an entry in \p Value2Index. Those
778 /// will then be added as function arguments. \p DT is used to order cloned
779 /// instructions. The reproducer function will get added to \p M, if it is
780 /// non-null. Otherwise no reproducer function is generated.
781 static void generateReproducer(CmpInst *Cond, Module *M,
782                                ArrayRef<ReproducerEntry> Stack,
783                                ConstraintInfo &Info, DominatorTree &DT) {
784   if (!M)
785     return;
786 
787   LLVMContext &Ctx = Cond->getContext();
788 
789   LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
790 
791   ValueToValueMapTy Old2New;
792   SmallVector<Value *> Args;
793   SmallPtrSet<Value *, 8> Seen;
794   // Traverse Cond and its operands recursively until we reach a value that's in
795   // Value2Index or not an instruction, or not a operation that
796   // ConstraintElimination can decompose. Such values will be considered as
797   // external inputs to the reproducer, they are collected and added as function
798   // arguments later.
799   auto CollectArguments = [&](CmpInst *Cond) {
800     if (!Cond)
801       return;
802     auto &Value2Index =
803         Info.getValue2Index(CmpInst::isSigned(Cond->getPredicate()));
804     SmallVector<Value *, 4> WorkList;
805     WorkList.push_back(Cond);
806     while (!WorkList.empty()) {
807       Value *V = WorkList.pop_back_val();
808       if (!Seen.insert(V).second)
809         continue;
810       if (Old2New.find(V) != Old2New.end())
811         continue;
812       if (isa<Constant>(V))
813         continue;
814 
815       auto *I = dyn_cast<Instruction>(V);
816       if (Value2Index.contains(V) || !I ||
817           !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
818         Old2New[V] = V;
819         Args.push_back(V);
820         LLVM_DEBUG(dbgs() << "  found external input " << *V << "\n");
821       } else {
822         append_range(WorkList, I->operands());
823       }
824     }
825   };
826 
827   for (auto &Entry : Stack)
828     CollectArguments(Entry.Cond);
829   CollectArguments(Cond);
830 
831   SmallVector<Type *> ParamTys;
832   for (auto *P : Args)
833     ParamTys.push_back(P->getType());
834 
835   FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
836                                         /*isVarArg=*/false);
837   Function *F = Function::Create(FTy, Function::ExternalLinkage,
838                                  Cond->getModule()->getName() +
839                                      Cond->getFunction()->getName() + "repro",
840                                  M);
841   // Add arguments to the reproducer function for each external value collected.
842   for (unsigned I = 0; I < Args.size(); ++I) {
843     F->getArg(I)->setName(Args[I]->getName());
844     Old2New[Args[I]] = F->getArg(I);
845   }
846 
847   BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
848   IRBuilder<> Builder(Entry);
849   Builder.CreateRet(Builder.getTrue());
850   Builder.SetInsertPoint(Entry->getTerminator());
851 
852   // Clone instructions in \p Ops and their operands recursively until reaching
853   // an value in Value2Index (external input to the reproducer). Update Old2New
854   // mapping for the original and cloned instructions. Sort instructions to
855   // clone by dominance, then insert the cloned instructions in the function.
856   auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
857     SmallVector<Value *, 4> WorkList(Ops);
858     SmallVector<Instruction *> ToClone;
859     auto &Value2Index = Info.getValue2Index(IsSigned);
860     while (!WorkList.empty()) {
861       Value *V = WorkList.pop_back_val();
862       if (Old2New.find(V) != Old2New.end())
863         continue;
864 
865       auto *I = dyn_cast<Instruction>(V);
866       if (!Value2Index.contains(V) && I) {
867         Old2New[V] = nullptr;
868         ToClone.push_back(I);
869         append_range(WorkList, I->operands());
870       }
871     }
872 
873     sort(ToClone,
874          [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
875     for (Instruction *I : ToClone) {
876       Instruction *Cloned = I->clone();
877       Old2New[I] = Cloned;
878       Old2New[I]->setName(I->getName());
879       Cloned->insertBefore(&*Builder.GetInsertPoint());
880       Cloned->dropUnknownNonDebugMetadata();
881       Cloned->setDebugLoc({});
882     }
883   };
884 
885   // Materialize the assumptions for the reproducer using the entries in Stack.
886   // That is, first clone the operands of the condition recursively until we
887   // reach an external input to the reproducer and add them to the reproducer
888   // function. Then add an ICmp for the condition (with the inverse predicate if
889   // the entry is negated) and an assert using the ICmp.
890   for (auto &Entry : Stack) {
891     if (!Entry.Cond)
892       continue;
893 
894     LLVM_DEBUG(dbgs() << "  Materializing assumption " << *Entry.Cond << "\n");
895     CmpInst::Predicate Pred = Entry.Cond->getPredicate();
896     if (Entry.IsNot)
897       Pred = CmpInst::getInversePredicate(Pred);
898 
899     CloneInstructions({Entry.Cond->getOperand(0), Entry.Cond->getOperand(1)},
900                       CmpInst::isSigned(Entry.Cond->getPredicate()));
901 
902     auto *Cmp = Builder.CreateICmp(Pred, Entry.Cond->getOperand(0),
903                                    Entry.Cond->getOperand(1));
904     Builder.CreateAssumption(Cmp);
905   }
906 
907   // Finally, clone the condition to reproduce and remap instruction operands in
908   // the reproducer using Old2New.
909   CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
910   Entry->getTerminator()->setOperand(0, Cond);
911   remapInstructionsInBlocks({Entry}, Old2New);
912 
913   assert(!verifyFunction(*F, &dbgs()));
914 }
915 
916 static bool checkAndReplaceCondition(
917     CmpInst *Cmp, ConstraintInfo &Info, Module *ReproducerModule,
918     ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT) {
919   LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n");
920 
921   CmpInst::Predicate Pred = Cmp->getPredicate();
922   Value *A = Cmp->getOperand(0);
923   Value *B = Cmp->getOperand(1);
924 
925   auto R = Info.getConstraintForSolving(Pred, A, B);
926   if (R.empty() || !R.isValid(Info)){
927     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
928     return false;
929   }
930 
931   auto &CSToUse = Info.getCS(R.IsSigned);
932 
933   // If there was extra information collected during decomposition, apply
934   // it now and remove it immediately once we are done with reasoning
935   // about the constraint.
936   for (auto &Row : R.ExtraInfo)
937     CSToUse.addVariableRow(Row);
938   auto InfoRestorer = make_scope_exit([&]() {
939     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
940       CSToUse.popLastConstraint();
941   });
942 
943   bool Changed = false;
944   if (CSToUse.isConditionImplied(R.Coefficients)) {
945     if (!DebugCounter::shouldExecute(EliminatedCounter))
946       return false;
947 
948     LLVM_DEBUG({
949       dbgs() << "Condition " << *Cmp << " implied by dominating constraints\n";
950       CSToUse.dump();
951     });
952     generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
953     Constant *TrueC =
954         ConstantInt::getTrue(CmpInst::makeCmpResultType(Cmp->getType()));
955     Cmp->replaceUsesWithIf(TrueC, [](Use &U) {
956       // Conditions in an assume trivially simplify to true. Skip uses
957       // in assume calls to not destroy the available information.
958       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
959       return !II || II->getIntrinsicID() != Intrinsic::assume;
960     });
961     NumCondsRemoved++;
962     Changed = true;
963   }
964   auto Negated = ConstraintSystem::negate(R.Coefficients);
965   if (!Negated.empty() && CSToUse.isConditionImplied(Negated)) {
966     if (!DebugCounter::shouldExecute(EliminatedCounter))
967       return false;
968 
969     LLVM_DEBUG({
970       dbgs() << "Condition !" << *Cmp << " implied by dominating constraints\n";
971       CSToUse.dump();
972     });
973     generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
974     Constant *FalseC =
975         ConstantInt::getFalse(CmpInst::makeCmpResultType(Cmp->getType()));
976     Cmp->replaceAllUsesWith(FalseC);
977     NumCondsRemoved++;
978     Changed = true;
979   }
980   return Changed;
981 }
982 
983 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
984                              unsigned NumIn, unsigned NumOut,
985                              SmallVectorImpl<StackEntry> &DFSInStack) {
986   // If the constraint has a pre-condition, skip the constraint if it does not
987   // hold.
988   SmallVector<Value *> NewVariables;
989   auto R = getConstraint(Pred, A, B, NewVariables);
990   if (!R.isValid(*this))
991     return;
992 
993   LLVM_DEBUG(dbgs() << "Adding '" << Pred << " ";
994              A->printAsOperand(dbgs(), false); dbgs() << ", ";
995              B->printAsOperand(dbgs(), false); dbgs() << "'\n");
996   bool Added = false;
997   auto &CSToUse = getCS(R.IsSigned);
998   if (R.Coefficients.empty())
999     return;
1000 
1001   Added |= CSToUse.addVariableRowFill(R.Coefficients);
1002 
1003   // If R has been added to the system, add the new variables and queue it for
1004   // removal once it goes out-of-scope.
1005   if (Added) {
1006     SmallVector<Value *, 2> ValuesToRelease;
1007     auto &Value2Index = getValue2Index(R.IsSigned);
1008     for (Value *V : NewVariables) {
1009       Value2Index.insert({V, Value2Index.size() + 1});
1010       ValuesToRelease.push_back(V);
1011     }
1012 
1013     LLVM_DEBUG({
1014       dbgs() << "  constraint: ";
1015       dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1016       dbgs() << "\n";
1017     });
1018 
1019     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1020                             std::move(ValuesToRelease));
1021 
1022     if (R.IsEq) {
1023       // Also add the inverted constraint for equality constraints.
1024       for (auto &Coeff : R.Coefficients)
1025         Coeff *= -1;
1026       CSToUse.addVariableRowFill(R.Coefficients);
1027 
1028       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1029                               SmallVector<Value *, 2>());
1030     }
1031   }
1032 }
1033 
1034 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
1035                                    SmallVectorImpl<Instruction *> &ToRemove) {
1036   bool Changed = false;
1037   IRBuilder<> Builder(II->getParent(), II->getIterator());
1038   Value *Sub = nullptr;
1039   for (User *U : make_early_inc_range(II->users())) {
1040     if (match(U, m_ExtractValue<0>(m_Value()))) {
1041       if (!Sub)
1042         Sub = Builder.CreateSub(A, B);
1043       U->replaceAllUsesWith(Sub);
1044       Changed = true;
1045     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1046       U->replaceAllUsesWith(Builder.getFalse());
1047       Changed = true;
1048     } else
1049       continue;
1050 
1051     if (U->use_empty()) {
1052       auto *I = cast<Instruction>(U);
1053       ToRemove.push_back(I);
1054       I->setOperand(0, PoisonValue::get(II->getType()));
1055       Changed = true;
1056     }
1057   }
1058 
1059   if (II->use_empty()) {
1060     II->eraseFromParent();
1061     Changed = true;
1062   }
1063   return Changed;
1064 }
1065 
1066 static bool
1067 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
1068                           SmallVectorImpl<Instruction *> &ToRemove) {
1069   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
1070                               ConstraintInfo &Info) {
1071     auto R = Info.getConstraintForSolving(Pred, A, B);
1072     if (R.size() < 2 || !R.isValid(Info))
1073       return false;
1074 
1075     auto &CSToUse = Info.getCS(R.IsSigned);
1076     return CSToUse.isConditionImplied(R.Coefficients);
1077   };
1078 
1079   bool Changed = false;
1080   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
1081     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
1082     // can be simplified to a regular sub.
1083     Value *A = II->getArgOperand(0);
1084     Value *B = II->getArgOperand(1);
1085     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
1086         !DoesConditionHold(CmpInst::ICMP_SGE, B,
1087                            ConstantInt::get(A->getType(), 0), Info))
1088       return false;
1089     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
1090   }
1091   return Changed;
1092 }
1093 
1094 static bool eliminateConstraints(Function &F, DominatorTree &DT,
1095                                  OptimizationRemarkEmitter &ORE) {
1096   bool Changed = false;
1097   DT.updateDFSNumbers();
1098   SmallVector<Value *> FunctionArgs;
1099   for (Value &Arg : F.args())
1100     FunctionArgs.push_back(&Arg);
1101   ConstraintInfo Info(F.getParent()->getDataLayout(), FunctionArgs);
1102   State S(DT);
1103   std::unique_ptr<Module> ReproducerModule(
1104       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
1105 
1106   // First, collect conditions implied by branches and blocks with their
1107   // Dominator DFS in and out numbers.
1108   for (BasicBlock &BB : F) {
1109     if (!DT.getNode(&BB))
1110       continue;
1111     S.addInfoFor(BB);
1112   }
1113 
1114   // Next, sort worklist by dominance, so that dominating conditions to check
1115   // and facts come before conditions and facts dominated by them. If a
1116   // condition to check and a fact have the same numbers, conditional facts come
1117   // first. Assume facts and checks are ordered according to their relative
1118   // order in the containing basic block. Also make sure conditions with
1119   // constant operands come before conditions without constant operands. This
1120   // increases the effectiveness of the current signed <-> unsigned fact
1121   // transfer logic.
1122   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1123     auto HasNoConstOp = [](const FactOrCheck &B) {
1124       return !isa<ConstantInt>(B.Inst->getOperand(0)) &&
1125              !isa<ConstantInt>(B.Inst->getOperand(1));
1126     };
1127     // If both entries have the same In numbers, conditional facts come first.
1128     // Otherwise use the relative order in the basic block.
1129     if (A.NumIn == B.NumIn) {
1130       if (A.isConditionFact() && B.isConditionFact()) {
1131         bool NoConstOpA = HasNoConstOp(A);
1132         bool NoConstOpB = HasNoConstOp(B);
1133         return NoConstOpA < NoConstOpB;
1134       }
1135       if (A.isConditionFact())
1136         return true;
1137       if (B.isConditionFact())
1138         return false;
1139       return A.Inst->comesBefore(B.Inst);
1140     }
1141     return A.NumIn < B.NumIn;
1142   });
1143 
1144   SmallVector<Instruction *> ToRemove;
1145 
1146   // Finally, process ordered worklist and eliminate implied conditions.
1147   SmallVector<StackEntry, 16> DFSInStack;
1148   SmallVector<ReproducerEntry> ReproducerCondStack;
1149   for (FactOrCheck &CB : S.WorkList) {
1150     // First, pop entries from the stack that are out-of-scope for CB. Remove
1151     // the corresponding entry from the constraint system.
1152     while (!DFSInStack.empty()) {
1153       auto &E = DFSInStack.back();
1154       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1155                         << "\n");
1156       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1157       assert(E.NumIn <= CB.NumIn);
1158       if (CB.NumOut <= E.NumOut)
1159         break;
1160       LLVM_DEBUG({
1161         dbgs() << "Removing ";
1162         dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
1163                        Info.getValue2Index(E.IsSigned));
1164         dbgs() << "\n";
1165       });
1166 
1167       Info.popLastConstraint(E.IsSigned);
1168       // Remove variables in the system that went out of scope.
1169       auto &Mapping = Info.getValue2Index(E.IsSigned);
1170       for (Value *V : E.ValuesToRelease)
1171         Mapping.erase(V);
1172       Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1173       DFSInStack.pop_back();
1174       if (ReproducerModule)
1175         ReproducerCondStack.pop_back();
1176     }
1177 
1178     LLVM_DEBUG({
1179       dbgs() << "Processing ";
1180       if (CB.IsCheck)
1181         dbgs() << "condition to simplify: " << *CB.Inst;
1182       else
1183         dbgs() << "fact to add to the system: " << *CB.Inst;
1184       dbgs() << "\n";
1185     });
1186 
1187     // For a block, check if any CmpInsts become known based on the current set
1188     // of constraints.
1189     if (CB.IsCheck) {
1190       if (auto *II = dyn_cast<WithOverflowInst>(CB.Inst)) {
1191         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1192       } else if (auto *Cmp = dyn_cast<ICmpInst>(CB.Inst)) {
1193         Changed |= checkAndReplaceCondition(Cmp, Info, ReproducerModule.get(),
1194                                             ReproducerCondStack, S.DT);
1195       }
1196       continue;
1197     }
1198 
1199     ICmpInst::Predicate Pred;
1200     Value *A, *B;
1201     Value *Cmp = CB.Inst;
1202     match(Cmp, m_Intrinsic<Intrinsic::assume>(m_Value(Cmp)));
1203     if (match(Cmp, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
1204       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1205         LLVM_DEBUG(
1206             dbgs()
1207             << "Skip adding constraint because system has too many rows.\n");
1208         continue;
1209       }
1210 
1211       // Use the inverse predicate if required.
1212       if (CB.Not)
1213         Pred = CmpInst::getInversePredicate(Pred);
1214 
1215       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1216       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
1217         ReproducerCondStack.emplace_back(cast<CmpInst>(Cmp), CB.Not);
1218 
1219       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1220       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
1221         // Add dummy entries to ReproducerCondStack to keep it in sync with
1222         // DFSInStack.
1223         for (unsigned I = 0,
1224                       E = (DFSInStack.size() - ReproducerCondStack.size());
1225              I < E; ++I) {
1226           ReproducerCondStack.emplace_back(nullptr, false);
1227         }
1228       }
1229     }
1230   }
1231 
1232   if (ReproducerModule && !ReproducerModule->functions().empty()) {
1233     std::string S;
1234     raw_string_ostream StringS(S);
1235     ReproducerModule->print(StringS, nullptr);
1236     StringS.flush();
1237     OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
1238     Rem << ore::NV("module") << S;
1239     ORE.emit(Rem);
1240   }
1241 
1242 #ifndef NDEBUG
1243   unsigned SignedEntries =
1244       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1245   assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries &&
1246          "updates to CS and DFSInStack are out of sync");
1247   assert(Info.getCS(true).size() == SignedEntries &&
1248          "updates to CS and DFSInStack are out of sync");
1249 #endif
1250 
1251   for (Instruction *I : ToRemove)
1252     I->eraseFromParent();
1253   return Changed;
1254 }
1255 
1256 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1257                                                  FunctionAnalysisManager &AM) {
1258   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1259   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1260   if (!eliminateConstraints(F, DT, ORE))
1261     return PreservedAnalyses::all();
1262 
1263   PreservedAnalyses PA;
1264   PA.preserve<DominatorTreeAnalysis>();
1265   PA.preserveSet<CFGAnalyses>();
1266   return PA;
1267 }
1268