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