xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 856c47b884ada7dadb1081244821e0acc199cc72)
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 = CmpInst::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(CmpInst::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(CmpInst::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 exit blocks. When exiting either
1038   // with EQ or NE in the header, we know that the induction value must be u<=
1039   // 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     WorkList.emplace_back(FactOrCheck::getConditionFact(
1048         DT.getNode(EB), CmpInst::ICMP_ULE, A, B, Precond));
1049   }
1050 }
1051 
1052 void State::addInfoFor(BasicBlock &BB) {
1053   addInfoForInductions(BB);
1054 
1055   // True as long as long as the current instruction is guaranteed to execute.
1056   bool GuaranteedToExecute = true;
1057   // Queue conditions and assumes.
1058   for (Instruction &I : BB) {
1059     if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
1060       for (Use &U : Cmp->uses()) {
1061         auto *UserI = getContextInstForUse(U);
1062         auto *DTN = DT.getNode(UserI->getParent());
1063         if (!DTN)
1064           continue;
1065         WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
1066       }
1067       continue;
1068     }
1069 
1070     auto *II = dyn_cast<IntrinsicInst>(&I);
1071     Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic;
1072     switch (ID) {
1073     case Intrinsic::assume: {
1074       Value *A, *B;
1075       CmpInst::Predicate Pred;
1076       if (!match(I.getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B))))
1077         break;
1078       if (GuaranteedToExecute) {
1079         // The assume is guaranteed to execute when BB is entered, hence Cond
1080         // holds on entry to BB.
1081         WorkList.emplace_back(FactOrCheck::getConditionFact(
1082             DT.getNode(I.getParent()), Pred, A, B));
1083       } else {
1084         WorkList.emplace_back(
1085             FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1086       }
1087       break;
1088     }
1089     // Enqueue ssub_with_overflow for simplification.
1090     case Intrinsic::ssub_with_overflow:
1091     case Intrinsic::ucmp:
1092     case Intrinsic::scmp:
1093       WorkList.push_back(
1094           FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1095       break;
1096     // Enqueue the intrinsics to add extra info.
1097     case Intrinsic::umin:
1098     case Intrinsic::umax:
1099     case Intrinsic::smin:
1100     case Intrinsic::smax:
1101       // TODO: handle llvm.abs as well
1102       WorkList.push_back(
1103           FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1104       // TODO: Check if it is possible to instead only added the min/max facts
1105       // when simplifying uses of the min/max intrinsics.
1106       if (!isGuaranteedNotToBePoison(&I))
1107         break;
1108       [[fallthrough]];
1109     case Intrinsic::abs:
1110       WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1111       break;
1112     }
1113 
1114     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1115   }
1116 
1117   if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
1118     for (auto &Case : Switch->cases()) {
1119       BasicBlock *Succ = Case.getCaseSuccessor();
1120       Value *V = Case.getCaseValue();
1121       if (!canAddSuccessor(BB, Succ))
1122         continue;
1123       WorkList.emplace_back(FactOrCheck::getConditionFact(
1124           DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
1125     }
1126     return;
1127   }
1128 
1129   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
1130   if (!Br || !Br->isConditional())
1131     return;
1132 
1133   Value *Cond = Br->getCondition();
1134 
1135   // If the condition is a chain of ORs/AND and the successor only has the
1136   // current block as predecessor, queue conditions for the successor.
1137   Value *Op0, *Op1;
1138   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1139       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1140     bool IsOr = match(Cond, m_LogicalOr());
1141     bool IsAnd = match(Cond, m_LogicalAnd());
1142     // If there's a select that matches both AND and OR, we need to commit to
1143     // one of the options. Arbitrarily pick OR.
1144     if (IsOr && IsAnd)
1145       IsAnd = false;
1146 
1147     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1148     if (canAddSuccessor(BB, Successor)) {
1149       SmallVector<Value *> CondWorkList;
1150       SmallPtrSet<Value *, 8> SeenCond;
1151       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1152         if (SeenCond.insert(V).second)
1153           CondWorkList.push_back(V);
1154       };
1155       QueueValue(Op1);
1156       QueueValue(Op0);
1157       while (!CondWorkList.empty()) {
1158         Value *Cur = CondWorkList.pop_back_val();
1159         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
1160           WorkList.emplace_back(FactOrCheck::getConditionFact(
1161               DT.getNode(Successor),
1162               IsOr ? CmpInst::getInversePredicate(Cmp->getPredicate())
1163                    : Cmp->getPredicate(),
1164               Cmp->getOperand(0), Cmp->getOperand(1)));
1165           continue;
1166         }
1167         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1168           QueueValue(Op1);
1169           QueueValue(Op0);
1170           continue;
1171         }
1172         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1173           QueueValue(Op1);
1174           QueueValue(Op0);
1175           continue;
1176         }
1177       }
1178     }
1179     return;
1180   }
1181 
1182   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
1183   if (!CmpI)
1184     return;
1185   if (canAddSuccessor(BB, Br->getSuccessor(0)))
1186     WorkList.emplace_back(FactOrCheck::getConditionFact(
1187         DT.getNode(Br->getSuccessor(0)), CmpI->getPredicate(),
1188         CmpI->getOperand(0), CmpI->getOperand(1)));
1189   if (canAddSuccessor(BB, Br->getSuccessor(1)))
1190     WorkList.emplace_back(FactOrCheck::getConditionFact(
1191         DT.getNode(Br->getSuccessor(1)),
1192         CmpInst::getInversePredicate(CmpI->getPredicate()), CmpI->getOperand(0),
1193         CmpI->getOperand(1)));
1194 }
1195 
1196 #ifndef NDEBUG
1197 static void dumpUnpackedICmp(raw_ostream &OS, ICmpInst::Predicate Pred,
1198                              Value *LHS, Value *RHS) {
1199   OS << "icmp " << Pred << ' ';
1200   LHS->printAsOperand(OS, /*PrintType=*/true);
1201   OS << ", ";
1202   RHS->printAsOperand(OS, /*PrintType=*/false);
1203 }
1204 #endif
1205 
1206 namespace {
1207 /// Helper to keep track of a condition and if it should be treated as negated
1208 /// for reproducer construction.
1209 /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
1210 /// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
1211 struct ReproducerEntry {
1212   ICmpInst::Predicate Pred;
1213   Value *LHS;
1214   Value *RHS;
1215 
1216   ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
1217       : Pred(Pred), LHS(LHS), RHS(RHS) {}
1218 };
1219 } // namespace
1220 
1221 /// Helper function to generate a reproducer function for simplifying \p Cond.
1222 /// The reproducer function contains a series of @llvm.assume calls, one for
1223 /// each condition in \p Stack. For each condition, the operand instruction are
1224 /// cloned until we reach operands that have an entry in \p Value2Index. Those
1225 /// will then be added as function arguments. \p DT is used to order cloned
1226 /// instructions. The reproducer function will get added to \p M, if it is
1227 /// non-null. Otherwise no reproducer function is generated.
1228 static void generateReproducer(CmpInst *Cond, Module *M,
1229                                ArrayRef<ReproducerEntry> Stack,
1230                                ConstraintInfo &Info, DominatorTree &DT) {
1231   if (!M)
1232     return;
1233 
1234   LLVMContext &Ctx = Cond->getContext();
1235 
1236   LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
1237 
1238   ValueToValueMapTy Old2New;
1239   SmallVector<Value *> Args;
1240   SmallPtrSet<Value *, 8> Seen;
1241   // Traverse Cond and its operands recursively until we reach a value that's in
1242   // Value2Index or not an instruction, or not a operation that
1243   // ConstraintElimination can decompose. Such values will be considered as
1244   // external inputs to the reproducer, they are collected and added as function
1245   // arguments later.
1246   auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1247     auto &Value2Index = Info.getValue2Index(IsSigned);
1248     SmallVector<Value *, 4> WorkList(Ops);
1249     while (!WorkList.empty()) {
1250       Value *V = WorkList.pop_back_val();
1251       if (!Seen.insert(V).second)
1252         continue;
1253       if (Old2New.find(V) != Old2New.end())
1254         continue;
1255       if (isa<Constant>(V))
1256         continue;
1257 
1258       auto *I = dyn_cast<Instruction>(V);
1259       if (Value2Index.contains(V) || !I ||
1260           !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
1261         Old2New[V] = V;
1262         Args.push_back(V);
1263         LLVM_DEBUG(dbgs() << "  found external input " << *V << "\n");
1264       } else {
1265         append_range(WorkList, I->operands());
1266       }
1267     }
1268   };
1269 
1270   for (auto &Entry : Stack)
1271     if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
1272       CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
1273   CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate()));
1274 
1275   SmallVector<Type *> ParamTys;
1276   for (auto *P : Args)
1277     ParamTys.push_back(P->getType());
1278 
1279   FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
1280                                         /*isVarArg=*/false);
1281   Function *F = Function::Create(FTy, Function::ExternalLinkage,
1282                                  Cond->getModule()->getName() +
1283                                      Cond->getFunction()->getName() + "repro",
1284                                  M);
1285   // Add arguments to the reproducer function for each external value collected.
1286   for (unsigned I = 0; I < Args.size(); ++I) {
1287     F->getArg(I)->setName(Args[I]->getName());
1288     Old2New[Args[I]] = F->getArg(I);
1289   }
1290 
1291   BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
1292   IRBuilder<> Builder(Entry);
1293   Builder.CreateRet(Builder.getTrue());
1294   Builder.SetInsertPoint(Entry->getTerminator());
1295 
1296   // Clone instructions in \p Ops and their operands recursively until reaching
1297   // an value in Value2Index (external input to the reproducer). Update Old2New
1298   // mapping for the original and cloned instructions. Sort instructions to
1299   // clone by dominance, then insert the cloned instructions in the function.
1300   auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
1301     SmallVector<Value *, 4> WorkList(Ops);
1302     SmallVector<Instruction *> ToClone;
1303     auto &Value2Index = Info.getValue2Index(IsSigned);
1304     while (!WorkList.empty()) {
1305       Value *V = WorkList.pop_back_val();
1306       if (Old2New.find(V) != Old2New.end())
1307         continue;
1308 
1309       auto *I = dyn_cast<Instruction>(V);
1310       if (!Value2Index.contains(V) && I) {
1311         Old2New[V] = nullptr;
1312         ToClone.push_back(I);
1313         append_range(WorkList, I->operands());
1314       }
1315     }
1316 
1317     sort(ToClone,
1318          [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
1319     for (Instruction *I : ToClone) {
1320       Instruction *Cloned = I->clone();
1321       Old2New[I] = Cloned;
1322       Old2New[I]->setName(I->getName());
1323       Cloned->insertBefore(&*Builder.GetInsertPoint());
1324       Cloned->dropUnknownNonDebugMetadata();
1325       Cloned->setDebugLoc({});
1326     }
1327   };
1328 
1329   // Materialize the assumptions for the reproducer using the entries in Stack.
1330   // That is, first clone the operands of the condition recursively until we
1331   // reach an external input to the reproducer and add them to the reproducer
1332   // function. Then add an ICmp for the condition (with the inverse predicate if
1333   // the entry is negated) and an assert using the ICmp.
1334   for (auto &Entry : Stack) {
1335     if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
1336       continue;
1337 
1338     LLVM_DEBUG(dbgs() << "  Materializing assumption ";
1339                dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS);
1340                dbgs() << "\n");
1341     CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
1342 
1343     auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
1344     Builder.CreateAssumption(Cmp);
1345   }
1346 
1347   // Finally, clone the condition to reproduce and remap instruction operands in
1348   // the reproducer using Old2New.
1349   CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
1350   Entry->getTerminator()->setOperand(0, Cond);
1351   remapInstructionsInBlocks({Entry}, Old2New);
1352 
1353   assert(!verifyFunction(*F, &dbgs()));
1354 }
1355 
1356 static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A,
1357                                           Value *B, Instruction *CheckInst,
1358                                           ConstraintInfo &Info) {
1359   LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n");
1360 
1361   auto R = Info.getConstraintForSolving(Pred, A, B);
1362   if (R.empty() || !R.isValid(Info)){
1363     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
1364     return std::nullopt;
1365   }
1366 
1367   auto &CSToUse = Info.getCS(R.IsSigned);
1368 
1369   // If there was extra information collected during decomposition, apply
1370   // it now and remove it immediately once we are done with reasoning
1371   // about the constraint.
1372   for (auto &Row : R.ExtraInfo)
1373     CSToUse.addVariableRow(Row);
1374   auto InfoRestorer = make_scope_exit([&]() {
1375     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
1376       CSToUse.popLastConstraint();
1377   });
1378 
1379   if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1380     if (!DebugCounter::shouldExecute(EliminatedCounter))
1381       return std::nullopt;
1382 
1383     LLVM_DEBUG({
1384       dbgs() << "Condition ";
1385       dumpUnpackedICmp(
1386           dbgs(), *ImpliedCondition ? Pred : CmpInst::getInversePredicate(Pred),
1387           A, B);
1388       dbgs() << " implied by dominating constraints\n";
1389       CSToUse.dump();
1390     });
1391     return ImpliedCondition;
1392   }
1393 
1394   return std::nullopt;
1395 }
1396 
1397 static bool checkAndReplaceCondition(
1398     CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
1399     Instruction *ContextInst, Module *ReproducerModule,
1400     ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
1401     SmallVectorImpl<Instruction *> &ToRemove) {
1402   auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) {
1403     generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
1404     Constant *ConstantC = ConstantInt::getBool(
1405         CmpInst::makeCmpResultType(Cmp->getType()), IsTrue);
1406     Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut,
1407                                        ContextInst](Use &U) {
1408       auto *UserI = getContextInstForUse(U);
1409       auto *DTN = DT.getNode(UserI->getParent());
1410       if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
1411         return false;
1412       if (UserI->getParent() == ContextInst->getParent() &&
1413           UserI->comesBefore(ContextInst))
1414         return false;
1415 
1416       // Conditions in an assume trivially simplify to true. Skip uses
1417       // in assume calls to not destroy the available information.
1418       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1419       return !II || II->getIntrinsicID() != Intrinsic::assume;
1420     });
1421     NumCondsRemoved++;
1422     if (Cmp->use_empty())
1423       ToRemove.push_back(Cmp);
1424     return true;
1425   };
1426 
1427   if (auto ImpliedCondition =
1428           checkCondition(Cmp->getPredicate(), Cmp->getOperand(0),
1429                          Cmp->getOperand(1), Cmp, Info))
1430     return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
1431   return false;
1432 }
1433 
1434 static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info,
1435                                   SmallVectorImpl<Instruction *> &ToRemove) {
1436   auto ReplaceMinMaxWithOperand = [&](MinMaxIntrinsic *MinMax, bool UseLHS) {
1437     // TODO: generate reproducer for min/max.
1438     MinMax->replaceAllUsesWith(MinMax->getOperand(UseLHS ? 0 : 1));
1439     ToRemove.push_back(MinMax);
1440     return true;
1441   };
1442 
1443   ICmpInst::Predicate Pred =
1444       ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1445   if (auto ImpliedCondition = checkCondition(
1446           Pred, MinMax->getOperand(0), MinMax->getOperand(1), MinMax, Info))
1447     return ReplaceMinMaxWithOperand(MinMax, *ImpliedCondition);
1448   if (auto ImpliedCondition = checkCondition(
1449           Pred, MinMax->getOperand(1), MinMax->getOperand(0), MinMax, Info))
1450     return ReplaceMinMaxWithOperand(MinMax, !*ImpliedCondition);
1451   return false;
1452 }
1453 
1454 static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info,
1455                                SmallVectorImpl<Instruction *> &ToRemove) {
1456   Value *LHS = I->getOperand(0);
1457   Value *RHS = I->getOperand(1);
1458   if (checkCondition(I->getGTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1459     I->replaceAllUsesWith(ConstantInt::get(I->getType(), 1));
1460     ToRemove.push_back(I);
1461     return true;
1462   }
1463   if (checkCondition(I->getLTPredicate(), LHS, RHS, I, Info).value_or(false)) {
1464     I->replaceAllUsesWith(ConstantInt::getSigned(I->getType(), -1));
1465     ToRemove.push_back(I);
1466     return true;
1467   }
1468   if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) {
1469     I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0));
1470     ToRemove.push_back(I);
1471     return true;
1472   }
1473   return false;
1474 }
1475 
1476 static void
1477 removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
1478                      Module *ReproducerModule,
1479                      SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1480                      SmallVectorImpl<StackEntry> &DFSInStack) {
1481   Info.popLastConstraint(E.IsSigned);
1482   // Remove variables in the system that went out of scope.
1483   auto &Mapping = Info.getValue2Index(E.IsSigned);
1484   for (Value *V : E.ValuesToRelease)
1485     Mapping.erase(V);
1486   Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
1487   DFSInStack.pop_back();
1488   if (ReproducerModule)
1489     ReproducerCondStack.pop_back();
1490 }
1491 
1492 /// Check if either the first condition of an AND or OR is implied by the
1493 /// (negated in case of OR) second condition or vice versa.
1494 static bool checkOrAndOpImpliedByOther(
1495     FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
1496     SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
1497     SmallVectorImpl<StackEntry> &DFSInStack) {
1498 
1499   CmpInst::Predicate Pred;
1500   Value *A, *B;
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   if (!match(JoinOp->getOperand(OtherOpIdx),
1512              m_ICmp(Pred, m_Value(A), m_Value(B))))
1513     return false;
1514 
1515   // For OR, check if the negated condition implies CmpToCheck.
1516   bool IsOr = match(JoinOp, m_LogicalOr());
1517   if (IsOr)
1518     Pred = CmpInst::getInversePredicate(Pred);
1519 
1520   // Optimistically add fact from first condition.
1521   unsigned OldSize = DFSInStack.size();
1522   Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1523   if (OldSize == DFSInStack.size())
1524     return false;
1525 
1526   bool Changed = false;
1527   // Check if the second condition can be simplified now.
1528   if (auto ImpliedCondition =
1529           checkCondition(CmpToCheck->getPredicate(), CmpToCheck->getOperand(0),
1530                          CmpToCheck->getOperand(1), CmpToCheck, Info)) {
1531     if (IsOr && isa<SelectInst>(JoinOp)) {
1532       JoinOp->setOperand(
1533           OtherOpIdx == 0 ? 2 : 0,
1534           ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1535     } else
1536       JoinOp->setOperand(
1537           1 - OtherOpIdx,
1538           ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1539 
1540     Changed = true;
1541   }
1542 
1543   // Remove entries again.
1544   while (OldSize < DFSInStack.size()) {
1545     StackEntry E = DFSInStack.back();
1546     removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
1547                          DFSInStack);
1548   }
1549   return Changed;
1550 }
1551 
1552 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
1553                              unsigned NumIn, unsigned NumOut,
1554                              SmallVectorImpl<StackEntry> &DFSInStack) {
1555   // If the constraint has a pre-condition, skip the constraint if it does not
1556   // hold.
1557   SmallVector<Value *> NewVariables;
1558   auto R = getConstraint(Pred, A, B, NewVariables);
1559 
1560   // TODO: Support non-equality for facts as well.
1561   if (!R.isValid(*this) || R.isNe())
1562     return;
1563 
1564   LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B);
1565              dbgs() << "'\n");
1566   bool Added = false;
1567   auto &CSToUse = getCS(R.IsSigned);
1568   if (R.Coefficients.empty())
1569     return;
1570 
1571   Added |= CSToUse.addVariableRowFill(R.Coefficients);
1572 
1573   // If R has been added to the system, add the new variables and queue it for
1574   // removal once it goes out-of-scope.
1575   if (Added) {
1576     SmallVector<Value *, 2> ValuesToRelease;
1577     auto &Value2Index = getValue2Index(R.IsSigned);
1578     for (Value *V : NewVariables) {
1579       Value2Index.insert({V, Value2Index.size() + 1});
1580       ValuesToRelease.push_back(V);
1581     }
1582 
1583     LLVM_DEBUG({
1584       dbgs() << "  constraint: ";
1585       dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1586       dbgs() << "\n";
1587     });
1588 
1589     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1590                             std::move(ValuesToRelease));
1591 
1592     if (!R.IsSigned) {
1593       for (Value *V : NewVariables) {
1594         ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
1595                             false, false, false);
1596         VarPos.Coefficients[Value2Index[V]] = -1;
1597         CSToUse.addVariableRow(VarPos.Coefficients);
1598         DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1599                                 SmallVector<Value *, 2>());
1600       }
1601     }
1602 
1603     if (R.isEq()) {
1604       // Also add the inverted constraint for equality constraints.
1605       for (auto &Coeff : R.Coefficients)
1606         Coeff *= -1;
1607       CSToUse.addVariableRowFill(R.Coefficients);
1608 
1609       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1610                               SmallVector<Value *, 2>());
1611     }
1612   }
1613 }
1614 
1615 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
1616                                    SmallVectorImpl<Instruction *> &ToRemove) {
1617   bool Changed = false;
1618   IRBuilder<> Builder(II->getParent(), II->getIterator());
1619   Value *Sub = nullptr;
1620   for (User *U : make_early_inc_range(II->users())) {
1621     if (match(U, m_ExtractValue<0>(m_Value()))) {
1622       if (!Sub)
1623         Sub = Builder.CreateSub(A, B);
1624       U->replaceAllUsesWith(Sub);
1625       Changed = true;
1626     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1627       U->replaceAllUsesWith(Builder.getFalse());
1628       Changed = true;
1629     } else
1630       continue;
1631 
1632     if (U->use_empty()) {
1633       auto *I = cast<Instruction>(U);
1634       ToRemove.push_back(I);
1635       I->setOperand(0, PoisonValue::get(II->getType()));
1636       Changed = true;
1637     }
1638   }
1639 
1640   if (II->use_empty()) {
1641     II->eraseFromParent();
1642     Changed = true;
1643   }
1644   return Changed;
1645 }
1646 
1647 static bool
1648 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
1649                           SmallVectorImpl<Instruction *> &ToRemove) {
1650   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
1651                               ConstraintInfo &Info) {
1652     auto R = Info.getConstraintForSolving(Pred, A, B);
1653     if (R.size() < 2 || !R.isValid(Info))
1654       return false;
1655 
1656     auto &CSToUse = Info.getCS(R.IsSigned);
1657     return CSToUse.isConditionImplied(R.Coefficients);
1658   };
1659 
1660   bool Changed = false;
1661   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
1662     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
1663     // can be simplified to a regular sub.
1664     Value *A = II->getArgOperand(0);
1665     Value *B = II->getArgOperand(1);
1666     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
1667         !DoesConditionHold(CmpInst::ICMP_SGE, B,
1668                            ConstantInt::get(A->getType(), 0), Info))
1669       return false;
1670     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
1671   }
1672   return Changed;
1673 }
1674 
1675 static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI,
1676                                  ScalarEvolution &SE,
1677                                  OptimizationRemarkEmitter &ORE) {
1678   bool Changed = false;
1679   DT.updateDFSNumbers();
1680   SmallVector<Value *> FunctionArgs;
1681   for (Value &Arg : F.args())
1682     FunctionArgs.push_back(&Arg);
1683   ConstraintInfo Info(F.getDataLayout(), FunctionArgs);
1684   State S(DT, LI, SE);
1685   std::unique_ptr<Module> ReproducerModule(
1686       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
1687 
1688   // First, collect conditions implied by branches and blocks with their
1689   // Dominator DFS in and out numbers.
1690   for (BasicBlock &BB : F) {
1691     if (!DT.getNode(&BB))
1692       continue;
1693     S.addInfoFor(BB);
1694   }
1695 
1696   // Next, sort worklist by dominance, so that dominating conditions to check
1697   // and facts come before conditions and facts dominated by them. If a
1698   // condition to check and a fact have the same numbers, conditional facts come
1699   // first. Assume facts and checks are ordered according to their relative
1700   // order in the containing basic block. Also make sure conditions with
1701   // constant operands come before conditions without constant operands. This
1702   // increases the effectiveness of the current signed <-> unsigned fact
1703   // transfer logic.
1704   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1705     auto HasNoConstOp = [](const FactOrCheck &B) {
1706       Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
1707       Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
1708       return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
1709     };
1710     // If both entries have the same In numbers, conditional facts come first.
1711     // Otherwise use the relative order in the basic block.
1712     if (A.NumIn == B.NumIn) {
1713       if (A.isConditionFact() && B.isConditionFact()) {
1714         bool NoConstOpA = HasNoConstOp(A);
1715         bool NoConstOpB = HasNoConstOp(B);
1716         return NoConstOpA < NoConstOpB;
1717       }
1718       if (A.isConditionFact())
1719         return true;
1720       if (B.isConditionFact())
1721         return false;
1722       auto *InstA = A.getContextInst();
1723       auto *InstB = B.getContextInst();
1724       return InstA->comesBefore(InstB);
1725     }
1726     return A.NumIn < B.NumIn;
1727   });
1728 
1729   SmallVector<Instruction *> ToRemove;
1730 
1731   // Finally, process ordered worklist and eliminate implied conditions.
1732   SmallVector<StackEntry, 16> DFSInStack;
1733   SmallVector<ReproducerEntry> ReproducerCondStack;
1734   for (FactOrCheck &CB : S.WorkList) {
1735     // First, pop entries from the stack that are out-of-scope for CB. Remove
1736     // the corresponding entry from the constraint system.
1737     while (!DFSInStack.empty()) {
1738       auto &E = DFSInStack.back();
1739       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1740                         << "\n");
1741       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1742       assert(E.NumIn <= CB.NumIn);
1743       if (CB.NumOut <= E.NumOut)
1744         break;
1745       LLVM_DEBUG({
1746         dbgs() << "Removing ";
1747         dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
1748                        Info.getValue2Index(E.IsSigned));
1749         dbgs() << "\n";
1750       });
1751       removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
1752                            DFSInStack);
1753     }
1754 
1755     // For a block, check if any CmpInsts become known based on the current set
1756     // of constraints.
1757     if (CB.isCheck()) {
1758       Instruction *Inst = CB.getInstructionToSimplify();
1759       if (!Inst)
1760         continue;
1761       LLVM_DEBUG(dbgs() << "Processing condition to simplify: " << *Inst
1762                         << "\n");
1763       if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
1764         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
1765       } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) {
1766         bool Simplified = checkAndReplaceCondition(
1767             Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
1768             ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
1769         if (!Simplified &&
1770             match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) {
1771           Simplified =
1772               checkOrAndOpImpliedByOther(CB, Info, ReproducerModule.get(),
1773                                          ReproducerCondStack, DFSInStack);
1774         }
1775         Changed |= Simplified;
1776       } else if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Inst)) {
1777         Changed |= checkAndReplaceMinMax(MinMax, Info, ToRemove);
1778       } else if (auto *CmpIntr = dyn_cast<CmpIntrinsic>(Inst)) {
1779         Changed |= checkAndReplaceCmp(CmpIntr, Info, ToRemove);
1780       }
1781       continue;
1782     }
1783 
1784     auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) {
1785       LLVM_DEBUG(dbgs() << "Processing fact to add to the system: ";
1786                  dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n");
1787       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1788         LLVM_DEBUG(
1789             dbgs()
1790             << "Skip adding constraint because system has too many rows.\n");
1791         return;
1792       }
1793 
1794       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1795       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
1796         ReproducerCondStack.emplace_back(Pred, A, B);
1797 
1798       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
1799       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
1800         // Add dummy entries to ReproducerCondStack to keep it in sync with
1801         // DFSInStack.
1802         for (unsigned I = 0,
1803                       E = (DFSInStack.size() - ReproducerCondStack.size());
1804              I < E; ++I) {
1805           ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
1806                                            nullptr, nullptr);
1807         }
1808       }
1809     };
1810 
1811     ICmpInst::Predicate Pred;
1812     if (!CB.isConditionFact()) {
1813       Value *X;
1814       if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) {
1815         // If is_int_min_poison is true then we may assume llvm.abs >= 0.
1816         if (cast<ConstantInt>(CB.Inst->getOperand(1))->isOne())
1817           AddFact(CmpInst::ICMP_SGE, CB.Inst,
1818                   ConstantInt::get(CB.Inst->getType(), 0));
1819         AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
1820         continue;
1821       }
1822 
1823       if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
1824         Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
1825         AddFact(Pred, MinMax, MinMax->getLHS());
1826         AddFact(Pred, MinMax, MinMax->getRHS());
1827         continue;
1828       }
1829     }
1830 
1831     Value *A = nullptr, *B = nullptr;
1832     if (CB.isConditionFact()) {
1833       Pred = CB.Cond.Pred;
1834       A = CB.Cond.Op0;
1835       B = CB.Cond.Op1;
1836       if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
1837           !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) {
1838         LLVM_DEBUG({
1839           dbgs() << "Not adding fact ";
1840           dumpUnpackedICmp(dbgs(), Pred, A, B);
1841           dbgs() << " because precondition ";
1842           dumpUnpackedICmp(dbgs(), CB.DoesHold.Pred, CB.DoesHold.Op0,
1843                            CB.DoesHold.Op1);
1844           dbgs() << " does not hold.\n";
1845         });
1846         continue;
1847       }
1848     } else {
1849       bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>(
1850                                         m_ICmp(Pred, m_Value(A), m_Value(B))));
1851       (void)Matched;
1852       assert(Matched && "Must have an assume intrinsic with a icmp operand");
1853     }
1854     AddFact(Pred, A, B);
1855   }
1856 
1857   if (ReproducerModule && !ReproducerModule->functions().empty()) {
1858     std::string S;
1859     raw_string_ostream StringS(S);
1860     ReproducerModule->print(StringS, nullptr);
1861     OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
1862     Rem << ore::NV("module") << S;
1863     ORE.emit(Rem);
1864   }
1865 
1866 #ifndef NDEBUG
1867   unsigned SignedEntries =
1868       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1869   assert(Info.getCS(false).size() - FunctionArgs.size() ==
1870              DFSInStack.size() - SignedEntries &&
1871          "updates to CS and DFSInStack are out of sync");
1872   assert(Info.getCS(true).size() == SignedEntries &&
1873          "updates to CS and DFSInStack are out of sync");
1874 #endif
1875 
1876   for (Instruction *I : ToRemove)
1877     I->eraseFromParent();
1878   return Changed;
1879 }
1880 
1881 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1882                                                  FunctionAnalysisManager &AM) {
1883   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1884   auto &LI = AM.getResult<LoopAnalysis>(F);
1885   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1886   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1887   if (!eliminateConstraints(F, DT, LI, SE, ORE))
1888     return PreservedAnalyses::all();
1889 
1890   PreservedAnalyses PA;
1891   PA.preserve<DominatorTreeAnalysis>();
1892   PA.preserve<LoopAnalysis>();
1893   PA.preserve<ScalarEvolutionAnalysis>();
1894   PA.preserveSet<CFGAnalyses>();
1895   return PA;
1896 }
1897