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