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