xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 0f0c0c36e3e90b4cb04004ed9c930f3863a36422)
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/LoopInfo.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InstrTypes.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/DebugCounter.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Transforms/Utils/Cloning.h"
41 #include "llvm/Transforms/Utils/ValueMapper.h"
42 
43 #include <cmath>
44 #include <optional>
45 #include <string>
46 
47 using namespace llvm;
48 using namespace PatternMatch;
49 
50 #define DEBUG_TYPE "constraint-elimination"
51 
52 STATISTIC(NumCondsRemoved, "Number of instructions removed");
53 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
54               "Controls which conditions are eliminated");
55 
56 static cl::opt<unsigned>
57     MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden,
58             cl::desc("Maximum number of rows to keep in constraint system"));
59 
60 static cl::opt<bool> DumpReproducers(
61     "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden,
62     cl::desc("Dump IR to reproduce successful transformations."));
63 
64 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
65 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
66 
67 // A helper to multiply 2 signed integers where overflowing is allowed.
68 static int64_t multiplyWithOverflow(int64_t A, int64_t B) {
69   int64_t Result;
70   MulOverflow(A, B, Result);
71   return Result;
72 }
73 
74 // A helper to add 2 signed integers where overflowing is allowed.
75 static int64_t addWithOverflow(int64_t A, int64_t B) {
76   int64_t Result;
77   AddOverflow(A, B, Result);
78   return Result;
79 }
80 
81 static Instruction *getContextInstForUse(Use &U) {
82   Instruction *UserI = cast<Instruction>(U.getUser());
83   if (auto *Phi = dyn_cast<PHINode>(UserI))
84     UserI = Phi->getIncomingBlock(U)->getTerminator();
85   return UserI;
86 }
87 
88 namespace {
89 /// Struct to express a condition of the form %Op0 Pred %Op1.
90 struct ConditionTy {
91   CmpInst::Predicate Pred;
92   Value *Op0;
93   Value *Op1;
94 
95   ConditionTy()
96       : Pred(CmpInst::BAD_ICMP_PREDICATE), Op0(nullptr), Op1(nullptr) {}
97   ConditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
98       : Pred(Pred), Op0(Op0), Op1(Op1) {}
99 };
100 
101 /// Represents either
102 ///  * a condition that holds on entry to a block (=condition fact)
103 ///  * an assume (=assume fact)
104 ///  * a use of a compare instruction to simplify.
105 /// It also tracks the Dominator DFS in and out numbers for each entry.
106 struct FactOrCheck {
107   enum class EntryTy {
108     ConditionFact, /// A condition that holds on entry to a block.
109     InstFact,      /// A fact that holds after Inst executed (e.g. an assume or
110                    /// min/mix intrinsic.
111     InstCheck,     /// An instruction to simplify (e.g. an overflow math
112                    /// intrinsics).
113     UseCheck       /// An use of a compare instruction to simplify.
114   };
115 
116   union {
117     Instruction *Inst;
118     Use *U;
119     ConditionTy Cond;
120   };
121 
122   /// A pre-condition that must hold for the current fact to be added to the
123   /// system.
124   ConditionTy DoesHold;
125 
126   unsigned NumIn;
127   unsigned NumOut;
128   EntryTy Ty;
129 
130   FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst)
131       : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
132         Ty(Ty) {}
133 
134   FactOrCheck(DomTreeNode *DTN, Use *U)
135       : U(U), DoesHold(CmpInst::BAD_ICMP_PREDICATE, nullptr, nullptr),
136         NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
137         Ty(EntryTy::UseCheck) {}
138 
139   FactOrCheck(DomTreeNode *DTN, CmpInst::Predicate Pred, Value *Op0, Value *Op1,
140               ConditionTy Precond = ConditionTy())
141       : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()),
142         NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {}
143 
144   static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpInst::Predicate Pred,
145                                       Value *Op0, Value *Op1,
146                                       ConditionTy Precond = ConditionTy()) {
147     return FactOrCheck(DTN, Pred, Op0, Op1, Precond);
148   }
149 
150   static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) {
151     return FactOrCheck(EntryTy::InstFact, DTN, Inst);
152   }
153 
154   static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) {
155     return FactOrCheck(DTN, U);
156   }
157 
158   static FactOrCheck getCheck(DomTreeNode *DTN, CallInst *CI) {
159     return FactOrCheck(EntryTy::InstCheck, DTN, CI);
160   }
161 
162   bool isCheck() const {
163     return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck;
164   }
165 
166   Instruction *getContextInst() const {
167     assert(!isConditionFact());
168     if (Ty == EntryTy::UseCheck)
169       return getContextInstForUse(*U);
170     return Inst;
171   }
172 
173   Instruction *getInstructionToSimplify() const {
174     assert(isCheck());
175     if (Ty == EntryTy::InstCheck)
176       return Inst;
177     // The use may have been simplified to a constant already.
178     return dyn_cast<Instruction>(*U);
179   }
180 
181   bool isConditionFact() const { return Ty == EntryTy::ConditionFact; }
182 };
183 
184 /// Keep state required to build worklist.
185 struct State {
186   DominatorTree &DT;
187   LoopInfo &LI;
188   ScalarEvolution &SE;
189   SmallVector<FactOrCheck, 64> WorkList;
190 
191   State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE)
192       : DT(DT), LI(LI), SE(SE) {}
193 
194   /// Process block \p BB and add known facts to work-list.
195   void addInfoFor(BasicBlock &BB);
196 
197   /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares
198   /// controlling the loop header.
199   void addInfoForInductions(BasicBlock &BB);
200 
201   /// Returns true if we can add a known condition from BB to its successor
202   /// block Succ.
203   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
204     return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
205   }
206 };
207 
208 class ConstraintInfo;
209 
210 struct StackEntry {
211   unsigned NumIn;
212   unsigned NumOut;
213   bool IsSigned = false;
214   /// Variables that can be removed from the system once the stack entry gets
215   /// removed.
216   SmallVector<Value *, 2> ValuesToRelease;
217 
218   StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
219              SmallVector<Value *, 2> ValuesToRelease)
220       : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
221         ValuesToRelease(ValuesToRelease) {}
222 };
223 
224 struct ConstraintTy {
225   SmallVector<int64_t, 8> Coefficients;
226   SmallVector<ConditionTy, 2> Preconditions;
227 
228   SmallVector<SmallVector<int64_t, 8>> ExtraInfo;
229 
230   bool IsSigned = false;
231 
232   ConstraintTy() = default;
233 
234   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned, bool IsEq,
235                bool IsNe)
236       : Coefficients(std::move(Coefficients)), IsSigned(IsSigned), IsEq(IsEq),
237         IsNe(IsNe) {}
238 
239   unsigned size() const { return Coefficients.size(); }
240 
241   unsigned empty() const { return Coefficients.empty(); }
242 
243   /// Returns true if all preconditions for this list of constraints are
244   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
245   bool isValid(const ConstraintInfo &Info) const;
246 
247   bool isEq() const { return IsEq; }
248 
249   bool isNe() const { return IsNe; }
250 
251   /// Check if the current constraint is implied by the given ConstraintSystem.
252   ///
253   /// \return true or false if the constraint is proven to be respectively true,
254   /// or false. When the constraint cannot be proven to be either true or false,
255   /// std::nullopt is returned.
256   std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const;
257 
258 private:
259   bool IsEq = false;
260   bool IsNe = false;
261 };
262 
263 /// Wrapper encapsulating separate constraint systems and corresponding value
264 /// mappings for both unsigned and signed information. Facts are added to and
265 /// conditions are checked against the corresponding system depending on the
266 /// signed-ness of their predicates. While the information is kept separate
267 /// based on signed-ness, certain conditions can be transferred between the two
268 /// systems.
269 class ConstraintInfo {
270 
271   ConstraintSystem UnsignedCS;
272   ConstraintSystem SignedCS;
273 
274   const DataLayout &DL;
275 
276 public:
277   ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
278       : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {
279     auto &Value2Index = getValue2Index(false);
280     // Add Arg > -1 constraints to unsigned system for all function arguments.
281     for (Value *Arg : FunctionArgs) {
282       ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
283                           false, false, false);
284       VarPos.Coefficients[Value2Index[Arg]] = -1;
285       UnsignedCS.addVariableRow(VarPos.Coefficients);
286     }
287   }
288 
289   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
290     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
291   }
292   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
293     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
294   }
295 
296   ConstraintSystem &getCS(bool Signed) {
297     return Signed ? SignedCS : UnsignedCS;
298   }
299   const ConstraintSystem &getCS(bool Signed) const {
300     return Signed ? SignedCS : UnsignedCS;
301   }
302 
303   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
304   void popLastNVariables(bool Signed, unsigned N) {
305     getCS(Signed).popLastNVariables(N);
306   }
307 
308   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
309 
310   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
311                unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
312 
313   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
314   /// constraints, using indices from the corresponding constraint system.
315   /// New variables that need to be added to the system are collected in
316   /// \p NewVariables.
317   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
318                              SmallVectorImpl<Value *> &NewVariables) const;
319 
320   /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
321   /// constraints using getConstraint. Returns an empty constraint if the result
322   /// cannot be used to query the existing constraint system, e.g. because it
323   /// would require adding new variables. Also tries to convert signed
324   /// predicates to unsigned ones if possible to allow using the unsigned system
325   /// which increases the effectiveness of the signed <-> unsigned transfer
326   /// logic.
327   ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
328                                        Value *Op1) const;
329 
330   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
331   /// system if \p Pred is signed/unsigned.
332   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
333                              unsigned NumIn, unsigned NumOut,
334                              SmallVectorImpl<StackEntry> &DFSInStack);
335 };
336 
337 /// Represents a (Coefficient * Variable) entry after IR decomposition.
338 struct DecompEntry {
339   int64_t Coefficient;
340   Value *Variable;
341   /// True if the variable is known positive in the current constraint.
342   bool IsKnownNonNegative;
343 
344   DecompEntry(int64_t Coefficient, Value *Variable,
345               bool IsKnownNonNegative = false)
346       : Coefficient(Coefficient), Variable(Variable),
347         IsKnownNonNegative(IsKnownNonNegative) {}
348 };
349 
350 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
351 struct Decomposition {
352   int64_t Offset = 0;
353   SmallVector<DecompEntry, 3> Vars;
354 
355   Decomposition(int64_t Offset) : Offset(Offset) {}
356   Decomposition(Value *V, bool IsKnownNonNegative = false) {
357     Vars.emplace_back(1, V, IsKnownNonNegative);
358   }
359   Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
360       : Offset(Offset), Vars(Vars) {}
361 
362   void add(int64_t OtherOffset) {
363     Offset = addWithOverflow(Offset, OtherOffset);
364   }
365 
366   void add(const Decomposition &Other) {
367     add(Other.Offset);
368     append_range(Vars, Other.Vars);
369   }
370 
371   void sub(const Decomposition &Other) {
372     Decomposition Tmp = Other;
373     Tmp.mul(-1);
374     add(Tmp.Offset);
375     append_range(Vars, Tmp.Vars);
376   }
377 
378   void mul(int64_t Factor) {
379     Offset = multiplyWithOverflow(Offset, Factor);
380     for (auto &Var : Vars)
381       Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor);
382   }
383 };
384 
385 // Variable and constant offsets for a chain of GEPs, with base pointer BasePtr.
386 struct OffsetResult {
387   Value *BasePtr;
388   APInt ConstantOffset;
389   SmallMapVector<Value *, APInt, 4> VariableOffsets;
390   bool AllInbounds;
391 
392   OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {}
393 
394   OffsetResult(GEPOperator &GEP, const DataLayout &DL)
395       : BasePtr(GEP.getPointerOperand()), AllInbounds(GEP.isInBounds()) {
396     ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0);
397   }
398 };
399 } // namespace
400 
401 // Try to collect variable and constant offsets for \p GEP, partly traversing
402 // nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting
403 // the offset fails.
404 static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL) {
405   OffsetResult Result(GEP, DL);
406   unsigned BitWidth = Result.ConstantOffset.getBitWidth();
407   if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets,
408                          Result.ConstantOffset))
409     return {};
410 
411   // If we have a nested GEP, check if we can combine the constant offset of the
412   // inner GEP with the outer GEP.
413   if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) {
414     SmallMapVector<Value *, APInt, 4> VariableOffsets2;
415     APInt ConstantOffset2(BitWidth, 0);
416     bool CanCollectInner = InnerGEP->collectOffset(
417         DL, BitWidth, VariableOffsets2, ConstantOffset2);
418     // TODO: Support cases with more than 1 variable offset.
419     if (!CanCollectInner || Result.VariableOffsets.size() > 1 ||
420         VariableOffsets2.size() > 1 ||
421         (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) {
422       // More than 1 variable index, use outer result.
423       return Result;
424     }
425     Result.BasePtr = InnerGEP->getPointerOperand();
426     Result.ConstantOffset += ConstantOffset2;
427     if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1)
428       Result.VariableOffsets = VariableOffsets2;
429     Result.AllInbounds &= InnerGEP->isInBounds();
430   }
431   return Result;
432 }
433 
434 static Decomposition decompose(Value *V,
435                                SmallVectorImpl<ConditionTy> &Preconditions,
436                                bool IsSigned, const DataLayout &DL);
437 
438 static bool canUseSExt(ConstantInt *CI) {
439   const APInt &Val = CI->getValue();
440   return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
441 }
442 
443 static Decomposition decomposeGEP(GEPOperator &GEP,
444                                   SmallVectorImpl<ConditionTy> &Preconditions,
445                                   bool IsSigned, const DataLayout &DL) {
446   // Do not reason about pointers where the index size is larger than 64 bits,
447   // as the coefficients used to encode constraints are 64 bit integers.
448   if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
449     return &GEP;
450 
451   assert(!IsSigned && "The logic below only supports decomposition for "
452                       "unsigned predicates at the moment.");
453   const auto &[BasePtr, ConstantOffset, VariableOffsets, AllInbounds] =
454       collectOffsets(GEP, DL);
455   if (!BasePtr || !AllInbounds)
456     return &GEP;
457 
458   Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr));
459   for (auto [Index, Scale] : VariableOffsets) {
460     auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
461     IdxResult.mul(Scale.getSExtValue());
462     Result.add(IdxResult);
463 
464     // If Op0 is signed non-negative, the GEP is increasing monotonically and
465     // can be de-composed.
466     if (!isKnownNonNegative(Index, DL))
467       Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
468                                  ConstantInt::get(Index->getType(), 0));
469   }
470   return Result;
471 }
472 
473 // Decomposes \p V into a constant offset + list of pairs { Coefficient,
474 // Variable } where Coefficient * Variable. The sum of the constant offset and
475 // pairs equals \p V.
476 static Decomposition decompose(Value *V,
477                                SmallVectorImpl<ConditionTy> &Preconditions,
478                                bool IsSigned, const DataLayout &DL) {
479 
480   auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B,
481                                                       bool IsSignedB) {
482     auto ResA = decompose(A, Preconditions, IsSigned, DL);
483     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
484     ResA.add(ResB);
485     return ResA;
486   };
487 
488   Type *Ty = V->getType()->getScalarType();
489   if (Ty->isPointerTy() && !IsSigned) {
490     if (auto *GEP = dyn_cast<GEPOperator>(V))
491       return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
492     if (isa<ConstantPointerNull>(V))
493       return int64_t(0);
494 
495     return V;
496   }
497 
498   // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so
499   // coefficient add/mul may wrap, while the operation in the full bit width
500   // would not.
501   if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
502     return V;
503 
504   bool IsKnownNonNegative = false;
505 
506   // Decompose \p V used with a signed predicate.
507   if (IsSigned) {
508     if (auto *CI = dyn_cast<ConstantInt>(V)) {
509       if (canUseSExt(CI))
510         return CI->getSExtValue();
511     }
512     Value *Op0;
513     Value *Op1;
514 
515     if (match(V, m_SExt(m_Value(Op0))))
516       V = Op0;
517     else if (match(V, m_NNegZExt(m_Value(Op0)))) {
518       V = Op0;
519       IsKnownNonNegative = true;
520     }
521 
522     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
523       return MergeResults(Op0, Op1, IsSigned);
524 
525     ConstantInt *CI;
526     if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) {
527       auto Result = decompose(Op0, Preconditions, IsSigned, DL);
528       Result.mul(CI->getSExtValue());
529       return Result;
530     }
531 
532     // (shl nsw x, shift) is (mul nsw x, (1<<shift)), with the exception of
533     // shift == bw-1.
534     if (match(V, m_NSWShl(m_Value(Op0), m_ConstantInt(CI)))) {
535       uint64_t Shift = CI->getValue().getLimitedValue();
536       if (Shift < Ty->getIntegerBitWidth() - 1) {
537         assert(Shift < 64 && "Would overflow");
538         auto Result = decompose(Op0, Preconditions, IsSigned, DL);
539         Result.mul(int64_t(1) << Shift);
540         return Result;
541       }
542     }
543 
544     return {V, IsKnownNonNegative};
545   }
546 
547   if (auto *CI = dyn_cast<ConstantInt>(V)) {
548     if (CI->uge(MaxConstraintValue))
549       return V;
550     return int64_t(CI->getZExtValue());
551   }
552 
553   Value *Op0;
554   if (match(V, m_ZExt(m_Value(Op0)))) {
555     IsKnownNonNegative = true;
556     V = Op0;
557   }
558 
559   if (match(V, m_SExt(m_Value(Op0)))) {
560     V = Op0;
561     Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
562                                ConstantInt::get(Op0->getType(), 0));
563   }
564 
565   Value *Op1;
566   ConstantInt *CI;
567   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
568     return MergeResults(Op0, Op1, IsSigned);
569   }
570   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
571     if (!isKnownNonNegative(Op0, DL))
572       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
573                                  ConstantInt::get(Op0->getType(), 0));
574     if (!isKnownNonNegative(Op1, DL))
575       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
576                                  ConstantInt::get(Op1->getType(), 0));
577 
578     return MergeResults(Op0, Op1, IsSigned);
579   }
580 
581   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
582       canUseSExt(CI)) {
583     Preconditions.emplace_back(
584         CmpInst::ICMP_UGE, Op0,
585         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
586     return MergeResults(Op0, CI, true);
587   }
588 
589   // Decompose or as an add if there are no common bits between the operands.
590   if (match(V, m_DisjointOr(m_Value(Op0), m_ConstantInt(CI))))
591     return MergeResults(Op0, CI, IsSigned);
592 
593   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
594     if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64)
595       return {V, IsKnownNonNegative};
596     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
597     Result.mul(int64_t{1} << CI->getSExtValue());
598     return Result;
599   }
600 
601   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
602       (!CI->isNegative())) {
603     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
604     Result.mul(CI->getSExtValue());
605     return Result;
606   }
607 
608   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) {
609     auto ResA = decompose(Op0, Preconditions, IsSigned, DL);
610     auto ResB = decompose(Op1, Preconditions, IsSigned, DL);
611     ResA.sub(ResB);
612     return ResA;
613   }
614 
615   return {V, IsKnownNonNegative};
616 }
617 
618 ConstraintTy
619 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
620                               SmallVectorImpl<Value *> &NewVariables) const {
621   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
622   bool IsEq = false;
623   bool IsNe = false;
624 
625   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
626   switch (Pred) {
627   case CmpInst::ICMP_UGT:
628   case CmpInst::ICMP_UGE:
629   case CmpInst::ICMP_SGT:
630   case CmpInst::ICMP_SGE: {
631     Pred = CmpInst::getSwappedPredicate(Pred);
632     std::swap(Op0, Op1);
633     break;
634   }
635   case CmpInst::ICMP_EQ:
636     if (match(Op1, m_Zero())) {
637       Pred = CmpInst::ICMP_ULE;
638     } else {
639       IsEq = true;
640       Pred = CmpInst::ICMP_ULE;
641     }
642     break;
643   case CmpInst::ICMP_NE:
644     if (match(Op1, m_Zero())) {
645       Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
646       std::swap(Op0, Op1);
647     } else {
648       IsNe = true;
649       Pred = CmpInst::ICMP_ULE;
650     }
651     break;
652   default:
653     break;
654   }
655 
656   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
657       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
658     return {};
659 
660   SmallVector<ConditionTy, 4> Preconditions;
661   bool IsSigned = CmpInst::isSigned(Pred);
662   auto &Value2Index = getValue2Index(IsSigned);
663   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
664                         Preconditions, IsSigned, DL);
665   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
666                         Preconditions, IsSigned, DL);
667   int64_t Offset1 = ADec.Offset;
668   int64_t Offset2 = BDec.Offset;
669   Offset1 *= -1;
670 
671   auto &VariablesA = ADec.Vars;
672   auto &VariablesB = BDec.Vars;
673 
674   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
675   // new entry to NewVariables.
676   SmallDenseMap<Value *, unsigned> NewIndexMap;
677   auto GetOrAddIndex = [&Value2Index, &NewVariables,
678                         &NewIndexMap](Value *V) -> unsigned {
679     auto V2I = Value2Index.find(V);
680     if (V2I != Value2Index.end())
681       return V2I->second;
682     auto Insert =
683         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
684     if (Insert.second)
685       NewVariables.push_back(V);
686     return Insert.first->second;
687   };
688 
689   // Make sure all variables have entries in Value2Index or NewVariables.
690   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
691     GetOrAddIndex(KV.Variable);
692 
693   // Build result constraint, by first adding all coefficients from A and then
694   // subtracting all coefficients from B.
695   ConstraintTy Res(
696       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
697       IsSigned, IsEq, IsNe);
698   // Collect variables that are known to be positive in all uses in the
699   // constraint.
700   SmallDenseMap<Value *, bool> KnownNonNegativeVariables;
701   auto &R = Res.Coefficients;
702   for (const auto &KV : VariablesA) {
703     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
704     auto I =
705         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
706     I.first->second &= KV.IsKnownNonNegative;
707   }
708 
709   for (const auto &KV : VariablesB) {
710     if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient,
711                     R[GetOrAddIndex(KV.Variable)]))
712       return {};
713     auto I =
714         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
715     I.first->second &= KV.IsKnownNonNegative;
716   }
717 
718   int64_t OffsetSum;
719   if (AddOverflow(Offset1, Offset2, OffsetSum))
720     return {};
721   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
722     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
723       return {};
724   R[0] = OffsetSum;
725   Res.Preconditions = std::move(Preconditions);
726 
727   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
728   // variables.
729   while (!NewVariables.empty()) {
730     int64_t Last = R.back();
731     if (Last != 0)
732       break;
733     R.pop_back();
734     Value *RemovedV = NewVariables.pop_back_val();
735     NewIndexMap.erase(RemovedV);
736   }
737 
738   // Add extra constraints for variables that are known positive.
739   for (auto &KV : KnownNonNegativeVariables) {
740     if (!KV.second ||
741         (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first)))
742       continue;
743     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
744     C[GetOrAddIndex(KV.first)] = -1;
745     Res.ExtraInfo.push_back(C);
746   }
747   return Res;
748 }
749 
750 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
751                                                      Value *Op0,
752                                                      Value *Op1) const {
753   Constant *NullC = Constant::getNullValue(Op0->getType());
754   // Handle trivially true compares directly to avoid adding V UGE 0 constraints
755   // for all variables in the unsigned system.
756   if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
757       (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
758     auto &Value2Index = getValue2Index(false);
759     // Return constraint that's trivially true.
760     return ConstraintTy(SmallVector<int64_t, 8>(Value2Index.size(), 0), false,
761                         false, false);
762   }
763 
764   // If both operands are known to be non-negative, change signed predicates to
765   // unsigned ones. This increases the reasoning effectiveness in combination
766   // with the signed <-> unsigned transfer logic.
767   if (CmpInst::isSigned(Pred) &&
768       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
769       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
770     Pred = ICmpInst::getUnsignedPredicate(Pred);
771 
772   SmallVector<Value *> NewVariables;
773   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
774   if (!NewVariables.empty())
775     return {};
776   return R;
777 }
778 
779 bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
780   return Coefficients.size() > 0 &&
781          all_of(Preconditions, [&Info](const ConditionTy &C) {
782            return Info.doesHold(C.Pred, C.Op0, C.Op1);
783          });
784 }
785 
786 std::optional<bool>
787 ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
788   bool IsConditionImplied = CS.isConditionImplied(Coefficients);
789 
790   if (IsEq || IsNe) {
791     auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients);
792     bool IsNegatedOrEqualImplied =
793         !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual);
794 
795     // In order to check that `%a == %b` is true (equality), both conditions `%a
796     // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
797     // is true), we return true if they both hold, false in the other cases.
798     if (IsConditionImplied && IsNegatedOrEqualImplied)
799       return IsEq;
800 
801     auto Negated = ConstraintSystem::negate(Coefficients);
802     bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
803 
804     auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients);
805     bool IsStrictLessThanImplied =
806         !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan);
807 
808     // In order to check that `%a != %b` is true (non-equality), either
809     // condition `%a > %b` or `%a < %b` must hold true. When checking for
810     // non-equality (`IsNe` is true), we return true if one of the two holds,
811     // false in the other cases.
812     if (IsNegatedImplied || IsStrictLessThanImplied)
813       return IsNe;
814 
815     return std::nullopt;
816   }
817 
818   if (IsConditionImplied)
819     return true;
820 
821   auto Negated = ConstraintSystem::negate(Coefficients);
822   auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
823   if (IsNegatedImplied)
824     return false;
825 
826   // Neither the condition nor its negated holds, did not prove anything.
827   return std::nullopt;
828 }
829 
830 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
831                               Value *B) const {
832   auto R = getConstraintForSolving(Pred, A, B);
833   return R.isValid(*this) &&
834          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
835 }
836 
837 void ConstraintInfo::transferToOtherSystem(
838     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
839     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
840   auto IsKnownNonNegative = [this](Value *V) {
841     return doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0)) ||
842            isKnownNonNegative(V, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1);
843   };
844   // Check if we can combine facts from the signed and unsigned systems to
845   // derive additional facts.
846   if (!A->getType()->isIntegerTy())
847     return;
848   // FIXME: This currently depends on the order we add facts. Ideally we
849   // would first add all known facts and only then try to add additional
850   // facts.
851   switch (Pred) {
852   default:
853     break;
854   case CmpInst::ICMP_ULT:
855   case CmpInst::ICMP_ULE:
856     //  If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
857     if (IsKnownNonNegative(B)) {
858       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
859               NumOut, DFSInStack);
860       addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
861               DFSInStack);
862     }
863     break;
864   case CmpInst::ICMP_UGE:
865   case CmpInst::ICMP_UGT:
866     //  If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
867     if (IsKnownNonNegative(A)) {
868       addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
869               NumOut, DFSInStack);
870       addFact(ICmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
871               DFSInStack);
872     }
873     break;
874   case CmpInst::ICMP_SLT:
875     if (IsKnownNonNegative(A))
876       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
877     break;
878   case CmpInst::ICMP_SGT: {
879     if (doesHold(CmpInst::ICMP_SGE, B, Constant::getAllOnesValue(B->getType())))
880       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
881               NumOut, DFSInStack);
882     if (IsKnownNonNegative(B))
883       addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
884 
885     break;
886   }
887   case CmpInst::ICMP_SGE:
888     if (IsKnownNonNegative(B))
889       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
890     break;
891   }
892 }
893 
894 #ifndef NDEBUG
895 
896 static void dumpConstraint(ArrayRef<int64_t> C,
897                            const DenseMap<Value *, unsigned> &Value2Index) {
898   ConstraintSystem CS(Value2Index);
899   CS.addVariableRowFill(C);
900   CS.dump();
901 }
902 #endif
903 
904 void State::addInfoForInductions(BasicBlock &BB) {
905   auto *L = LI.getLoopFor(&BB);
906   if (!L || L->getHeader() != &BB)
907     return;
908 
909   Value *A;
910   Value *B;
911   CmpInst::Predicate Pred;
912 
913   if (!match(BB.getTerminator(),
914              m_Br(m_ICmp(Pred, m_Value(A), m_Value(B)), m_Value(), m_Value())))
915     return;
916   PHINode *PN = dyn_cast<PHINode>(A);
917   if (!PN) {
918     Pred = CmpInst::getSwappedPredicate(Pred);
919     std::swap(A, B);
920     PN = dyn_cast<PHINode>(A);
921   }
922 
923   if (!PN || PN->getParent() != &BB || PN->getNumIncomingValues() != 2 ||
924       !SE.isSCEVable(PN->getType()))
925     return;
926 
927   BasicBlock *InLoopSucc = nullptr;
928   if (Pred == CmpInst::ICMP_NE)
929     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(0);
930   else if (Pred == CmpInst::ICMP_EQ)
931     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(1);
932   else
933     return;
934 
935   if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB)
936     return;
937 
938   auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN));
939   BasicBlock *LoopPred = L->getLoopPredecessor();
940   if (!AR || AR->getLoop() != L || !LoopPred)
941     return;
942 
943   const SCEV *StartSCEV = AR->getStart();
944   Value *StartValue = nullptr;
945   if (auto *C = dyn_cast<SCEVConstant>(StartSCEV)) {
946     StartValue = C->getValue();
947   } else {
948     StartValue = PN->getIncomingValueForBlock(LoopPred);
949     assert(SE.getSCEV(StartValue) == StartSCEV && "inconsistent start value");
950   }
951 
952   DomTreeNode *DTN = DT.getNode(InLoopSucc);
953   auto IncUnsigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_UGT);
954   auto IncSigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_SGT);
955   bool MonotonicallyIncreasingUnsigned =
956       IncUnsigned && *IncUnsigned == ScalarEvolution::MonotonicallyIncreasing;
957   bool MonotonicallyIncreasingSigned =
958       IncSigned && *IncSigned == ScalarEvolution::MonotonicallyIncreasing;
959   // If SCEV guarantees that AR does not wrap, PN >= StartValue can be added
960   // unconditionally.
961   if (MonotonicallyIncreasingUnsigned)
962     WorkList.push_back(
963         FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGE, PN, StartValue));
964   if (MonotonicallyIncreasingSigned)
965     WorkList.push_back(
966         FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_SGE, PN, StartValue));
967 
968   APInt StepOffset;
969   if (auto *C = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
970     StepOffset = C->getAPInt();
971   else
972     return;
973 
974   // Make sure the bound B is loop-invariant.
975   if (!L->isLoopInvariant(B))
976     return;
977 
978   // Handle negative steps.
979   if (StepOffset.isNegative()) {
980     // TODO: Extend to allow steps > -1.
981     if (!(-StepOffset).isOne())
982       return;
983 
984     // AR may wrap.
985     // Add StartValue >= PN conditional on B <= StartValue which guarantees that
986     // the loop exits before wrapping with a step of -1.
987     WorkList.push_back(FactOrCheck::getConditionFact(
988         DTN, CmpInst::ICMP_UGE, StartValue, PN,
989         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
990     WorkList.push_back(FactOrCheck::getConditionFact(
991         DTN, CmpInst::ICMP_SGE, StartValue, PN,
992         ConditionTy(CmpInst::ICMP_SLE, B, StartValue)));
993     // Add PN > B conditional on B <= StartValue which guarantees that the loop
994     // exits when reaching B with a step of -1.
995     WorkList.push_back(FactOrCheck::getConditionFact(
996         DTN, CmpInst::ICMP_UGT, PN, B,
997         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
998     WorkList.push_back(FactOrCheck::getConditionFact(
999         DTN, CmpInst::ICMP_SGT, PN, B,
1000         ConditionTy(CmpInst::ICMP_SLE, B, StartValue)));
1001     return;
1002   }
1003 
1004   // Make sure AR either steps by 1 or that the value we compare against is a
1005   // GEP based on the same start value and all offsets are a multiple of the
1006   // step size, to guarantee that the induction will reach the value.
1007   if (StepOffset.isZero() || StepOffset.isNegative())
1008     return;
1009 
1010   if (!StepOffset.isOne()) {
1011     // Check whether B-Start is known to be a multiple of StepOffset.
1012     const SCEV *BMinusStart = SE.getMinusSCEV(SE.getSCEV(B), StartSCEV);
1013     if (isa<SCEVCouldNotCompute>(BMinusStart) ||
1014         !SE.getConstantMultiple(BMinusStart).urem(StepOffset).isZero())
1015       return;
1016   }
1017 
1018   // AR may wrap. Add PN >= StartValue conditional on StartValue <= B which
1019   // guarantees that the loop exits before wrapping in combination with the
1020   // restrictions on B and the step above.
1021   if (!MonotonicallyIncreasingUnsigned)
1022     WorkList.push_back(FactOrCheck::getConditionFact(
1023         DTN, CmpInst::ICMP_UGE, PN, StartValue,
1024         ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
1025   if (!MonotonicallyIncreasingSigned)
1026     WorkList.push_back(FactOrCheck::getConditionFact(
1027         DTN, CmpInst::ICMP_SGE, PN, StartValue,
1028         ConditionTy(CmpInst::ICMP_SLE, StartValue, B)));
1029 
1030   WorkList.push_back(FactOrCheck::getConditionFact(
1031       DTN, CmpInst::ICMP_ULT, PN, B,
1032       ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
1033   WorkList.push_back(FactOrCheck::getConditionFact(
1034       DTN, CmpInst::ICMP_SLT, PN, B,
1035       ConditionTy(CmpInst::ICMP_SLE, StartValue, B)));
1036 
1037   // Try to add condition from header to the dedicated exit blocks. When exiting
1038   // either with EQ or NE in the header, we know that the induction value must
1039   // be u<= B, as other exits may only exit earlier.
1040   assert(!StepOffset.isNegative() && "induction must be increasing");
1041   assert((Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) &&
1042          "unsupported predicate");
1043   ConditionTy Precond = {CmpInst::ICMP_ULE, StartValue, B};
1044   SmallVector<BasicBlock *> ExitBBs;
1045   L->getExitBlocks(ExitBBs);
1046   for (BasicBlock *EB : ExitBBs) {
1047     // Bail out on non-dedicated exits.
1048     if (DT.dominates(&BB, EB)) {
1049       WorkList.emplace_back(FactOrCheck::getConditionFact(
1050           DT.getNode(EB), CmpInst::ICMP_ULE, A, B, Precond));
1051     }
1052   }
1053 }
1054 
1055 void State::addInfoFor(BasicBlock &BB) {
1056   addInfoForInductions(BB);
1057 
1058   // True as long as long as the current instruction is guaranteed to execute.
1059   bool GuaranteedToExecute = true;
1060   // Queue conditions and assumes.
1061   for (Instruction &I : BB) {
1062     if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
1063       for (Use &U : Cmp->uses()) {
1064         auto *UserI = getContextInstForUse(U);
1065         auto *DTN = DT.getNode(UserI->getParent());
1066         if (!DTN)
1067           continue;
1068         WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
1069       }
1070       continue;
1071     }
1072 
1073     auto *II = dyn_cast<IntrinsicInst>(&I);
1074     Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic;
1075     switch (ID) {
1076     case Intrinsic::assume: {
1077       Value *A, *B;
1078       CmpInst::Predicate Pred;
1079       if (!match(I.getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B))))
1080         break;
1081       if (GuaranteedToExecute) {
1082         // The assume is guaranteed to execute when BB is entered, hence Cond
1083         // holds on entry to BB.
1084         WorkList.emplace_back(FactOrCheck::getConditionFact(
1085             DT.getNode(I.getParent()), Pred, A, B));
1086       } else {
1087         WorkList.emplace_back(
1088             FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1089       }
1090       break;
1091     }
1092     // Enqueue ssub_with_overflow for simplification.
1093     case Intrinsic::ssub_with_overflow:
1094     case Intrinsic::ucmp:
1095     case Intrinsic::scmp:
1096       WorkList.push_back(
1097           FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1098       break;
1099     // Enqueue the intrinsics to add extra info.
1100     case Intrinsic::umin:
1101     case Intrinsic::umax:
1102     case Intrinsic::smin:
1103     case Intrinsic::smax:
1104       // TODO: handle llvm.abs as well
1105       WorkList.push_back(
1106           FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1107       // TODO: Check if it is possible to instead only added the min/max facts
1108       // when simplifying uses of the min/max intrinsics.
1109       if (!isGuaranteedNotToBePoison(&I))
1110         break;
1111       [[fallthrough]];
1112     case Intrinsic::abs:
1113       WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1114       break;
1115     }
1116 
1117     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1118   }
1119 
1120   if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
1121     for (auto &Case : Switch->cases()) {
1122       BasicBlock *Succ = Case.getCaseSuccessor();
1123       Value *V = Case.getCaseValue();
1124       if (!canAddSuccessor(BB, Succ))
1125         continue;
1126       WorkList.emplace_back(FactOrCheck::getConditionFact(
1127           DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
1128     }
1129     return;
1130   }
1131 
1132   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
1133   if (!Br || !Br->isConditional())
1134     return;
1135 
1136   Value *Cond = Br->getCondition();
1137 
1138   // If the condition is a chain of ORs/AND and the successor only has the
1139   // current block as predecessor, queue conditions for the successor.
1140   Value *Op0, *Op1;
1141   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1142       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1143     bool IsOr = match(Cond, m_LogicalOr());
1144     bool IsAnd = match(Cond, m_LogicalAnd());
1145     // If there's a select that matches both AND and OR, we need to commit to
1146     // one of the options. Arbitrarily pick OR.
1147     if (IsOr && IsAnd)
1148       IsAnd = false;
1149 
1150     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1151     if (canAddSuccessor(BB, Successor)) {
1152       SmallVector<Value *> CondWorkList;
1153       SmallPtrSet<Value *, 8> SeenCond;
1154       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1155         if (SeenCond.insert(V).second)
1156           CondWorkList.push_back(V);
1157       };
1158       QueueValue(Op1);
1159       QueueValue(Op0);
1160       while (!CondWorkList.empty()) {
1161         Value *Cur = CondWorkList.pop_back_val();
1162         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
1163           WorkList.emplace_back(FactOrCheck::getConditionFact(
1164               DT.getNode(Successor),
1165               IsOr ? CmpInst::getInversePredicate(Cmp->getPredicate())
1166                    : Cmp->getPredicate(),
1167               Cmp->getOperand(0), Cmp->getOperand(1)));
1168           continue;
1169         }
1170         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1171           QueueValue(Op1);
1172           QueueValue(Op0);
1173           continue;
1174         }
1175         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1176           QueueValue(Op1);
1177           QueueValue(Op0);
1178           continue;
1179         }
1180       }
1181     }
1182     return;
1183   }
1184 
1185   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
1186   if (!CmpI)
1187     return;
1188   if (canAddSuccessor(BB, Br->getSuccessor(0)))
1189     WorkList.emplace_back(FactOrCheck::getConditionFact(
1190         DT.getNode(Br->getSuccessor(0)), CmpI->getPredicate(),
1191         CmpI->getOperand(0), CmpI->getOperand(1)));
1192   if (canAddSuccessor(BB, Br->getSuccessor(1)))
1193     WorkList.emplace_back(FactOrCheck::getConditionFact(
1194         DT.getNode(Br->getSuccessor(1)),
1195         CmpInst::getInversePredicate(CmpI->getPredicate()), CmpI->getOperand(0),
1196         CmpI->getOperand(1)));
1197 }
1198 
1199 #ifndef NDEBUG
1200 static void dumpUnpackedICmp(raw_ostream &OS, ICmpInst::Predicate Pred,
1201                              Value *LHS, Value *RHS) {
1202   OS << "icmp " << Pred << ' ';
1203   LHS->printAsOperand(OS, /*PrintType=*/true);
1204   OS << ", ";
1205   RHS->printAsOperand(OS, /*PrintType=*/false);
1206 }
1207 #endif
1208 
1209 namespace {
1210 /// Helper to keep track of a condition and if it should be treated as negated
1211 /// for reproducer construction.
1212 /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
1213 /// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
1214 struct ReproducerEntry {
1215   ICmpInst::Predicate Pred;
1216   Value *LHS;
1217   Value *RHS;
1218 
1219   ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
1220       : Pred(Pred), LHS(LHS), RHS(RHS) {}
1221 };
1222 } // namespace
1223 
1224 /// Helper function to generate a reproducer function for simplifying \p Cond.
1225 /// The reproducer function contains a series of @llvm.assume calls, one for
1226 /// each condition in \p Stack. For each condition, the operand instruction are
1227 /// cloned until we reach operands that have an entry in \p Value2Index. Those
1228 /// will then be added as function arguments. \p DT is used to order cloned
1229 /// instructions. The reproducer function will get added to \p M, if it is
1230 /// non-null. Otherwise no reproducer function is generated.
1231 static void generateReproducer(CmpInst *Cond, Module *M,
1232                                ArrayRef<ReproducerEntry> Stack,
1233                                ConstraintInfo &Info, DominatorTree &DT) {
1234   if (!M)
1235     return;
1236 
1237   LLVMContext &Ctx = Cond->getContext();
1238 
1239   LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
1240 
1241   ValueToValueMapTy Old2New;
1242   SmallVector<Value *> Args;
1243   SmallPtrSet<Value *, 8> Seen;
1244   // Traverse Cond and its operands recursively until we reach a value that's in
1245   // Value2Index or not an instruction, or not a operation that
1246   // ConstraintElimination can decompose. Such values will be considered as
1247   // external inputs to the reproducer, they are collected and added as function
1248   // arguments later.
1249   auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1250     auto &Value2Index = Info.getValue2Index(IsSigned);
1251     SmallVector<Value *, 4> WorkList(Ops);
1252     while (!WorkList.empty()) {
1253       Value *V = WorkList.pop_back_val();
1254       if (!Seen.insert(V).second)
1255         continue;
1256       if (Old2New.find(V) != Old2New.end())
1257         continue;
1258       if (isa<Constant>(V))
1259         continue;
1260 
1261       auto *I = dyn_cast<Instruction>(V);
1262       if (Value2Index.contains(V) || !I ||
1263           !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
1264         Old2New[V] = V;
1265         Args.push_back(V);
1266         LLVM_DEBUG(dbgs() << "  found external input " << *V << "\n");
1267       } else {
1268         append_range(WorkList, I->operands());
1269       }
1270     }
1271   };
1272 
1273   for (auto &Entry : Stack)
1274     if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
1275       CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
1276   CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate()));
1277 
1278   SmallVector<Type *> ParamTys;
1279   for (auto *P : Args)
1280     ParamTys.push_back(P->getType());
1281 
1282   FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
1283                                         /*isVarArg=*/false);
1284   Function *F = Function::Create(FTy, Function::ExternalLinkage,
1285                                  Cond->getModule()->getName() +
1286                                      Cond->getFunction()->getName() + "repro",
1287                                  M);
1288   // Add arguments to the reproducer function for each external value collected.
1289   for (unsigned I = 0; I < Args.size(); ++I) {
1290     F->getArg(I)->setName(Args[I]->getName());
1291     Old2New[Args[I]] = F->getArg(I);
1292   }
1293 
1294   BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
1295   IRBuilder<> Builder(Entry);
1296   Builder.CreateRet(Builder.getTrue());
1297   Builder.SetInsertPoint(Entry->getTerminator());
1298 
1299   // Clone instructions in \p Ops and their operands recursively until reaching
1300   // an value in Value2Index (external input to the reproducer). Update Old2New
1301   // mapping for the original and cloned instructions. Sort instructions to
1302   // clone by dominance, then insert the cloned instructions in the function.
1303   auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1304     SmallVector<Value *, 4> WorkList(Ops);
1305     SmallVector<Instruction *> ToClone;
1306     auto &Value2Index = Info.getValue2Index(IsSigned);
1307     while (!WorkList.empty()) {
1308       Value *V = WorkList.pop_back_val();
1309       if (Old2New.find(V) != Old2New.end())
1310         continue;
1311 
1312       auto *I = dyn_cast<Instruction>(V);
1313       if (!Value2Index.contains(V) && I) {
1314         Old2New[V] = nullptr;
1315         ToClone.push_back(I);
1316         append_range(WorkList, I->operands());
1317       }
1318     }
1319 
1320     sort(ToClone,
1321          [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
1322     for (Instruction *I : ToClone) {
1323       Instruction *Cloned = I->clone();
1324       Old2New[I] = Cloned;
1325       Old2New[I]->setName(I->getName());
1326       Cloned->insertBefore(&*Builder.GetInsertPoint());
1327       Cloned->dropUnknownNonDebugMetadata();
1328       Cloned->setDebugLoc({});
1329     }
1330   };
1331 
1332   // Materialize the assumptions for the reproducer using the entries in Stack.
1333   // That is, first clone the operands of the condition recursively until we
1334   // reach an external input to the reproducer and add them to the reproducer
1335   // function. Then add an ICmp for the condition (with the inverse predicate if
1336   // the entry is negated) and an assert using the ICmp.
1337   for (auto &Entry : Stack) {
1338     if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
1339       continue;
1340 
1341     LLVM_DEBUG(dbgs() << "  Materializing assumption ";
1342                dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS);
1343                dbgs() << "\n");
1344     CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
1345 
1346     auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
1347     Builder.CreateAssumption(Cmp);
1348   }
1349 
1350   // Finally, clone the condition to reproduce and remap instruction operands in
1351   // the reproducer using Old2New.
1352   CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
1353   Entry->getTerminator()->setOperand(0, Cond);
1354   remapInstructionsInBlocks({Entry}, Old2New);
1355 
1356   assert(!verifyFunction(*F, &dbgs()));
1357 }
1358 
1359 static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A,
1360                                           Value *B, Instruction *CheckInst,
1361                                           ConstraintInfo &Info) {
1362   LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n");
1363 
1364   auto R = Info.getConstraintForSolving(Pred, A, B);
1365   if (R.empty() || !R.isValid(Info)){
1366     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
1367     return std::nullopt;
1368   }
1369 
1370   auto &CSToUse = Info.getCS(R.IsSigned);
1371 
1372   // If there was extra information collected during decomposition, apply
1373   // it now and remove it immediately once we are done with reasoning
1374   // about the constraint.
1375   for (auto &Row : R.ExtraInfo)
1376     CSToUse.addVariableRow(Row);
1377   auto InfoRestorer = make_scope_exit([&]() {
1378     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
1379       CSToUse.popLastConstraint();
1380   });
1381 
1382   if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1383     if (!DebugCounter::shouldExecute(EliminatedCounter))
1384       return std::nullopt;
1385 
1386     LLVM_DEBUG({
1387       dbgs() << "Condition ";
1388       dumpUnpackedICmp(
1389           dbgs(), *ImpliedCondition ? Pred : CmpInst::getInversePredicate(Pred),
1390           A, B);
1391       dbgs() << " implied by dominating constraints\n";
1392       CSToUse.dump();
1393     });
1394     return ImpliedCondition;
1395   }
1396 
1397   return std::nullopt;
1398 }
1399 
1400 static bool checkAndReplaceCondition(
1401     CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
1402     Instruction *ContextInst, Module *ReproducerModule,
1403     ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
1404     SmallVectorImpl<Instruction *> &ToRemove) {
1405   auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) {
1406     generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
1407     Constant *ConstantC = ConstantInt::getBool(
1408         CmpInst::makeCmpResultType(Cmp->getType()), IsTrue);
1409     Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut,
1410                                        ContextInst](Use &U) {
1411       auto *UserI = getContextInstForUse(U);
1412       auto *DTN = DT.getNode(UserI->getParent());
1413       if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1414         return false;
1415       if (UserI->getParent() == ContextInst->getParent() &&
1416           UserI->comesBefore(ContextInst))
1417         return false;
1418 
1419       // Conditions in an assume trivially simplify to true. Skip uses
1420       // in assume calls to not destroy the available information.
1421       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1422       return !II || II->getIntrinsicID() != Intrinsic::assume;
1423     });
1424     NumCondsRemoved++;
1425     if (Cmp->use_empty())
1426       ToRemove.push_back(Cmp);
1427     return true;
1428   };
1429 
1430   if (auto ImpliedCondition =
1431           checkCondition(Cmp->getPredicate(), Cmp->getOperand(0),
1432                          Cmp->getOperand(1), Cmp, Info))
1433     return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
1434   return false;
1435 }
1436 
1437 static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info,
1438                                   SmallVectorImpl<Instruction *> &ToRemove) {
1439   auto ReplaceMinMaxWithOperand = [&](MinMaxIntrinsic *MinMax, bool UseLHS) {
1440     // TODO: generate reproducer for min/max.
1441     MinMax->replaceAllUsesWith(MinMax->getOperand(UseLHS ? 0 : 1));
1442     ToRemove.push_back(MinMax);
1443     return true;
1444   };
1445 
1446   ICmpInst::Predicate Pred =
1447       ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1448   if (auto ImpliedCondition = checkCondition(
1449           Pred, MinMax->getOperand(0), MinMax->getOperand(1), MinMax, Info))
1450     return ReplaceMinMaxWithOperand(MinMax, *ImpliedCondition);
1451   if (auto ImpliedCondition = checkCondition(
1452           Pred, MinMax->getOperand(1), MinMax->getOperand(0), MinMax, Info))
1453     return ReplaceMinMaxWithOperand(MinMax, !*ImpliedCondition);
1454   return false;
1455 }
1456 
1457 static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info,
1458                                SmallVectorImpl<Instruction *> &ToRemove) {
1459   Value *LHS = I->getOperand(0);
1460   Value *RHS = I->getOperand(1);
1461   if (checkCondition(I->getGTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1462     I->replaceAllUsesWith(ConstantInt::get(I->getType(), 1));
1463     ToRemove.push_back(I);
1464     return true;
1465   }
1466   if (checkCondition(I->getLTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1467     I->replaceAllUsesWith(ConstantInt::getSigned(I->getType(), -1));
1468     ToRemove.push_back(I);
1469     return true;
1470   }
1471   if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) {
1472     I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0));
1473     ToRemove.push_back(I);
1474     return true;
1475   }
1476   return false;
1477 }
1478 
1479 static void
1480 removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
1481                      Module *ReproducerModule,
1482                      SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1483                      SmallVectorImpl<StackEntry> &DFSInStack) {
1484   Info.popLastConstraint(E.IsSigned);
1485   // Remove variables in the system that went out of scope.
1486   auto &Mapping = Info.getValue2Index(E.IsSigned);
1487   for (Value *V : E.ValuesToRelease)
1488     Mapping.erase(V);
1489   Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1490   DFSInStack.pop_back();
1491   if (ReproducerModule)
1492     ReproducerCondStack.pop_back();
1493 }
1494 
1495 /// Check if either the first condition of an AND or OR is implied by the
1496 /// (negated in case of OR) second condition or vice versa.
1497 static bool checkOrAndOpImpliedByOther(
1498     FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
1499     SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1500     SmallVectorImpl<StackEntry> &DFSInStack) {
1501   Instruction *JoinOp = CB.getContextInst();
1502   CmpInst *CmpToCheck = cast<CmpInst>(CB.getInstructionToSimplify());
1503   unsigned OtherOpIdx = JoinOp->getOperand(0) == CmpToCheck ? 1 : 0;
1504 
1505   // Don't try to simplify the first condition of a select by the second, as
1506   // this may make the select more poisonous than the original one.
1507   // TODO: check if the first operand may be poison.
1508   if (OtherOpIdx != 0 && isa<SelectInst>(JoinOp))
1509     return false;
1510 
1511   unsigned OldSize = DFSInStack.size();
1512   auto InfoRestorer = make_scope_exit([&]() {
1513     // Remove entries again.
1514     while (OldSize < DFSInStack.size()) {
1515       StackEntry E = DFSInStack.back();
1516       removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
1517                            DFSInStack);
1518     }
1519   });
1520   bool IsOr = match(JoinOp, m_LogicalOr());
1521   SmallVector<Value *, 4> Worklist({JoinOp->getOperand(OtherOpIdx)});
1522   // Do a traversal of the AND/OR tree to add facts from leaf compares.
1523   while (!Worklist.empty()) {
1524     Value *Val = Worklist.pop_back_val();
1525     Value *LHS, *RHS;
1526     ICmpInst::Predicate Pred;
1527     if (match(Val, m_ICmp(Pred, m_Value(LHS), m_Value(RHS)))) {
1528       // For OR, check if the negated condition implies CmpToCheck.
1529       if (IsOr)
1530         Pred = CmpInst::getInversePredicate(Pred);
1531       // Optimistically add fact from the other compares in the AND/OR.
1532       Info.addFact(Pred, LHS, RHS, CB.NumIn, CB.NumOut, DFSInStack);
1533       continue;
1534     }
1535     if (IsOr ? match(Val, m_LogicalOr(m_Value(LHS), m_Value(RHS)))
1536              : match(Val, m_LogicalAnd(m_Value(LHS), m_Value(RHS)))) {
1537       Worklist.push_back(LHS);
1538       Worklist.push_back(RHS);
1539     }
1540   }
1541   if (OldSize == DFSInStack.size())
1542     return false;
1543 
1544   // Check if the second condition can be simplified now.
1545   if (auto ImpliedCondition =
1546           checkCondition(CmpToCheck->getPredicate(), CmpToCheck->getOperand(0),
1547                          CmpToCheck->getOperand(1), CmpToCheck, Info)) {
1548     if (IsOr && isa<SelectInst>(JoinOp)) {
1549       JoinOp->setOperand(
1550           OtherOpIdx == 0 ? 2 : 0,
1551           ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1552     } else
1553       JoinOp->setOperand(
1554           1 - OtherOpIdx,
1555           ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1556 
1557     return true;
1558   }
1559 
1560   return false;
1561 }
1562 
1563 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
1564                              unsigned NumIn, unsigned NumOut,
1565                              SmallVectorImpl<StackEntry> &DFSInStack) {
1566   // If the constraint has a pre-condition, skip the constraint if it does not
1567   // hold.
1568   SmallVector<Value *> NewVariables;
1569   auto R = getConstraint(Pred, A, B, NewVariables);
1570 
1571   // TODO: Support non-equality for facts as well.
1572   if (!R.isValid(*this) || R.isNe())
1573     return;
1574 
1575   LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B);
1576              dbgs() << "'\n");
1577   bool Added = false;
1578   auto &CSToUse = getCS(R.IsSigned);
1579   if (R.Coefficients.empty())
1580     return;
1581 
1582   Added |= CSToUse.addVariableRowFill(R.Coefficients);
1583 
1584   // If R has been added to the system, add the new variables and queue it for
1585   // removal once it goes out-of-scope.
1586   if (Added) {
1587     SmallVector<Value *, 2> ValuesToRelease;
1588     auto &Value2Index = getValue2Index(R.IsSigned);
1589     for (Value *V : NewVariables) {
1590       Value2Index.insert({V, Value2Index.size() + 1});
1591       ValuesToRelease.push_back(V);
1592     }
1593 
1594     LLVM_DEBUG({
1595       dbgs() << "  constraint: ";
1596       dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1597       dbgs() << "\n";
1598     });
1599 
1600     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1601                             std::move(ValuesToRelease));
1602 
1603     if (!R.IsSigned) {
1604       for (Value *V : NewVariables) {
1605         ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
1606                             false, false, false);
1607         VarPos.Coefficients[Value2Index[V]] = -1;
1608         CSToUse.addVariableRow(VarPos.Coefficients);
1609         DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1610                                 SmallVector<Value *, 2>());
1611       }
1612     }
1613 
1614     if (R.isEq()) {
1615       // Also add the inverted constraint for equality constraints.
1616       for (auto &Coeff : R.Coefficients)
1617         Coeff *= -1;
1618       CSToUse.addVariableRowFill(R.Coefficients);
1619 
1620       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1621                               SmallVector<Value *, 2>());
1622     }
1623   }
1624 }
1625 
1626 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
1627                                    SmallVectorImpl<Instruction *> &ToRemove) {
1628   bool Changed = false;
1629   IRBuilder<> Builder(II->getParent(), II->getIterator());
1630   Value *Sub = nullptr;
1631   for (User *U : make_early_inc_range(II->users())) {
1632     if (match(U, m_ExtractValue<0>(m_Value()))) {
1633       if (!Sub)
1634         Sub = Builder.CreateSub(A, B);
1635       U->replaceAllUsesWith(Sub);
1636       Changed = true;
1637     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1638       U->replaceAllUsesWith(Builder.getFalse());
1639       Changed = true;
1640     } else
1641       continue;
1642 
1643     if (U->use_empty()) {
1644       auto *I = cast<Instruction>(U);
1645       ToRemove.push_back(I);
1646       I->setOperand(0, PoisonValue::get(II->getType()));
1647       Changed = true;
1648     }
1649   }
1650 
1651   if (II->use_empty()) {
1652     II->eraseFromParent();
1653     Changed = true;
1654   }
1655   return Changed;
1656 }
1657 
1658 static bool
1659 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
1660                           SmallVectorImpl<Instruction *> &ToRemove) {
1661   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
1662                               ConstraintInfo &Info) {
1663     auto R = Info.getConstraintForSolving(Pred, A, B);
1664     if (R.size() < 2 || !R.isValid(Info))
1665       return false;
1666 
1667     auto &CSToUse = Info.getCS(R.IsSigned);
1668     return CSToUse.isConditionImplied(R.Coefficients);
1669   };
1670 
1671   bool Changed = false;
1672   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
1673     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
1674     // can be simplified to a regular sub.
1675     Value *A = II->getArgOperand(0);
1676     Value *B = II->getArgOperand(1);
1677     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
1678         !DoesConditionHold(CmpInst::ICMP_SGE, B,
1679                            ConstantInt::get(A->getType(), 0), Info))
1680       return false;
1681     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
1682   }
1683   return Changed;
1684 }
1685 
1686 static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI,
1687                                  ScalarEvolution &SE,
1688                                  OptimizationRemarkEmitter &ORE) {
1689   bool Changed = false;
1690   DT.updateDFSNumbers();
1691   SmallVector<Value *> FunctionArgs;
1692   for (Value &Arg : F.args())
1693     FunctionArgs.push_back(&Arg);
1694   ConstraintInfo Info(F.getDataLayout(), FunctionArgs);
1695   State S(DT, LI, SE);
1696   std::unique_ptr<Module> ReproducerModule(
1697       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
1698 
1699   // First, collect conditions implied by branches and blocks with their
1700   // Dominator DFS in and out numbers.
1701   for (BasicBlock &BB : F) {
1702     if (!DT.getNode(&BB))
1703       continue;
1704     S.addInfoFor(BB);
1705   }
1706 
1707   // Next, sort worklist by dominance, so that dominating conditions to check
1708   // and facts come before conditions and facts dominated by them. If a
1709   // condition to check and a fact have the same numbers, conditional facts come
1710   // first. Assume facts and checks are ordered according to their relative
1711   // order in the containing basic block. Also make sure conditions with
1712   // constant operands come before conditions without constant operands. This
1713   // increases the effectiveness of the current signed <-> unsigned fact
1714   // transfer logic.
1715   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1716     auto HasNoConstOp = [](const FactOrCheck &B) {
1717       Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
1718       Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
1719       return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
1720     };
1721     // If both entries have the same In numbers, conditional facts come first.
1722     // Otherwise use the relative order in the basic block.
1723     if (A.NumIn == B.NumIn) {
1724       if (A.isConditionFact() && B.isConditionFact()) {
1725         bool NoConstOpA = HasNoConstOp(A);
1726         bool NoConstOpB = HasNoConstOp(B);
1727         return NoConstOpA < NoConstOpB;
1728       }
1729       if (A.isConditionFact())
1730         return true;
1731       if (B.isConditionFact())
1732         return false;
1733       auto *InstA = A.getContextInst();
1734       auto *InstB = B.getContextInst();
1735       return InstA->comesBefore(InstB);
1736     }
1737     return A.NumIn < B.NumIn;
1738   });
1739 
1740   SmallVector<Instruction *> ToRemove;
1741 
1742   // Finally, process ordered worklist and eliminate implied conditions.
1743   SmallVector<StackEntry, 16> DFSInStack;
1744   SmallVector<ReproducerEntry> ReproducerCondStack;
1745   for (FactOrCheck &CB : S.WorkList) {
1746     // First, pop entries from the stack that are out-of-scope for CB. Remove
1747     // the corresponding entry from the constraint system.
1748     while (!DFSInStack.empty()) {
1749       auto &E = DFSInStack.back();
1750       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1751                         << "\n");
1752       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1753       assert(E.NumIn <= CB.NumIn);
1754       if (CB.NumOut <= E.NumOut)
1755         break;
1756       LLVM_DEBUG({
1757         dbgs() << "Removing ";
1758         dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
1759                        Info.getValue2Index(E.IsSigned));
1760         dbgs() << "\n";
1761       });
1762       removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
1763                            DFSInStack);
1764     }
1765 
1766     // For a block, check if any CmpInsts become known based on the current set
1767     // of constraints.
1768     if (CB.isCheck()) {
1769       Instruction *Inst = CB.getInstructionToSimplify();
1770       if (!Inst)
1771         continue;
1772       LLVM_DEBUG(dbgs() << "Processing condition to simplify: " << *Inst
1773                         << "\n");
1774       if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
1775         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1776       } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) {
1777         bool Simplified = checkAndReplaceCondition(
1778             Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
1779             ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
1780         if (!Simplified &&
1781             match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) {
1782           Simplified =
1783               checkOrAndOpImpliedByOther(CB, Info, ReproducerModule.get(),
1784                                          ReproducerCondStack, DFSInStack);
1785         }
1786         Changed |= Simplified;
1787       } else if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Inst)) {
1788         Changed |= checkAndReplaceMinMax(MinMax, Info, ToRemove);
1789       } else if (auto *CmpIntr = dyn_cast<CmpIntrinsic>(Inst)) {
1790         Changed |= checkAndReplaceCmp(CmpIntr, Info, ToRemove);
1791       }
1792       continue;
1793     }
1794 
1795     auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) {
1796       LLVM_DEBUG(dbgs() << "Processing fact to add to the system: ";
1797                  dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n");
1798       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1799         LLVM_DEBUG(
1800             dbgs()
1801             << "Skip adding constraint because system has too many rows.\n");
1802         return;
1803       }
1804 
1805       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1806       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
1807         ReproducerCondStack.emplace_back(Pred, A, B);
1808 
1809       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1810       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
1811         // Add dummy entries to ReproducerCondStack to keep it in sync with
1812         // DFSInStack.
1813         for (unsigned I = 0,
1814                       E = (DFSInStack.size() - ReproducerCondStack.size());
1815              I < E; ++I) {
1816           ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
1817                                            nullptr, nullptr);
1818         }
1819       }
1820     };
1821 
1822     ICmpInst::Predicate Pred;
1823     if (!CB.isConditionFact()) {
1824       Value *X;
1825       if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) {
1826         // If is_int_min_poison is true then we may assume llvm.abs >= 0.
1827         if (cast<ConstantInt>(CB.Inst->getOperand(1))->isOne())
1828           AddFact(CmpInst::ICMP_SGE, CB.Inst,
1829                   ConstantInt::get(CB.Inst->getType(), 0));
1830         AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
1831         continue;
1832       }
1833 
1834       if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
1835         Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1836         AddFact(Pred, MinMax, MinMax->getLHS());
1837         AddFact(Pred, MinMax, MinMax->getRHS());
1838         continue;
1839       }
1840     }
1841 
1842     Value *A = nullptr, *B = nullptr;
1843     if (CB.isConditionFact()) {
1844       Pred = CB.Cond.Pred;
1845       A = CB.Cond.Op0;
1846       B = CB.Cond.Op1;
1847       if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
1848           !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) {
1849         LLVM_DEBUG({
1850           dbgs() << "Not adding fact ";
1851           dumpUnpackedICmp(dbgs(), Pred, A, B);
1852           dbgs() << " because precondition ";
1853           dumpUnpackedICmp(dbgs(), CB.DoesHold.Pred, CB.DoesHold.Op0,
1854                            CB.DoesHold.Op1);
1855           dbgs() << " does not hold.\n";
1856         });
1857         continue;
1858       }
1859     } else {
1860       bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>(
1861                                         m_ICmp(Pred, m_Value(A), m_Value(B))));
1862       (void)Matched;
1863       assert(Matched && "Must have an assume intrinsic with a icmp operand");
1864     }
1865     AddFact(Pred, A, B);
1866   }
1867 
1868   if (ReproducerModule && !ReproducerModule->functions().empty()) {
1869     std::string S;
1870     raw_string_ostream StringS(S);
1871     ReproducerModule->print(StringS, nullptr);
1872     OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
1873     Rem << ore::NV("module") << S;
1874     ORE.emit(Rem);
1875   }
1876 
1877 #ifndef NDEBUG
1878   unsigned SignedEntries =
1879       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1880   assert(Info.getCS(false).size() - FunctionArgs.size() ==
1881              DFSInStack.size() - SignedEntries &&
1882          "updates to CS and DFSInStack are out of sync");
1883   assert(Info.getCS(true).size() == SignedEntries &&
1884          "updates to CS and DFSInStack are out of sync");
1885 #endif
1886 
1887   for (Instruction *I : ToRemove)
1888     I->eraseFromParent();
1889   return Changed;
1890 }
1891 
1892 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1893                                                  FunctionAnalysisManager &AM) {
1894   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1895   auto &LI = AM.getResult<LoopAnalysis>(F);
1896   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1897   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1898   if (!eliminateConstraints(F, DT, LI, SE, ORE))
1899     return PreservedAnalyses::all();
1900 
1901   PreservedAnalyses PA;
1902   PA.preserve<DominatorTreeAnalysis>();
1903   PA.preserve<LoopAnalysis>();
1904   PA.preserve<ScalarEvolutionAnalysis>();
1905   PA.preserveSet<CFGAnalyses>();
1906   return PA;
1907 }
1908