xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision b3edf4467982447620505a28fc82e38a414c07dc)
1e8d8bef9SDimitry Andric //===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric //
9e8d8bef9SDimitry Andric // Eliminate conditions based on constraints collected from dominating
10e8d8bef9SDimitry Andric // conditions.
11e8d8bef9SDimitry Andric //
12e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
13e8d8bef9SDimitry Andric 
14e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar/ConstraintElimination.h"
15e8d8bef9SDimitry Andric #include "llvm/ADT/STLExtras.h"
16fe6060f1SDimitry Andric #include "llvm/ADT/ScopeExit.h"
17e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h"
18e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h"
19e8d8bef9SDimitry Andric #include "llvm/Analysis/ConstraintSystem.h"
20e8d8bef9SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
215f757f3fSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
2206c3fb27SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
235f757f3fSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
245f757f3fSDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
25349cc55cSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
26bdd1243dSDimitry Andric #include "llvm/IR/DataLayout.h"
27e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h"
28e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
2981ad6265SDimitry Andric #include "llvm/IR/IRBuilder.h"
305f757f3fSDimitry Andric #include "llvm/IR/InstrTypes.h"
31e8d8bef9SDimitry Andric #include "llvm/IR/Instructions.h"
32e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h"
3306c3fb27SDimitry Andric #include "llvm/IR/Verifier.h"
34e8d8bef9SDimitry Andric #include "llvm/Pass.h"
35bdd1243dSDimitry Andric #include "llvm/Support/CommandLine.h"
36e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h"
37e8d8bef9SDimitry Andric #include "llvm/Support/DebugCounter.h"
3881ad6265SDimitry Andric #include "llvm/Support/MathExtras.h"
3906c3fb27SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
4006c3fb27SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
41e8d8bef9SDimitry Andric 
42bdd1243dSDimitry Andric #include <cmath>
4306c3fb27SDimitry Andric #include <optional>
44fe6060f1SDimitry Andric #include <string>
45fe6060f1SDimitry Andric 
46e8d8bef9SDimitry Andric using namespace llvm;
47e8d8bef9SDimitry Andric using namespace PatternMatch;
48e8d8bef9SDimitry Andric 
49e8d8bef9SDimitry Andric #define DEBUG_TYPE "constraint-elimination"
50e8d8bef9SDimitry Andric 
51e8d8bef9SDimitry Andric STATISTIC(NumCondsRemoved, "Number of instructions removed");
52e8d8bef9SDimitry Andric DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
53e8d8bef9SDimitry Andric               "Controls which conditions are eliminated");
54e8d8bef9SDimitry Andric 
55bdd1243dSDimitry Andric static cl::opt<unsigned>
56bdd1243dSDimitry Andric     MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden,
57bdd1243dSDimitry Andric             cl::desc("Maximum number of rows to keep in constraint system"));
58bdd1243dSDimitry Andric 
5906c3fb27SDimitry Andric static cl::opt<bool> DumpReproducers(
6006c3fb27SDimitry Andric     "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden,
6106c3fb27SDimitry Andric     cl::desc("Dump IR to reproduce successful transformations."));
6206c3fb27SDimitry Andric 
63e8d8bef9SDimitry Andric static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
6481ad6265SDimitry Andric static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
65e8d8bef9SDimitry Andric 
66bdd1243dSDimitry Andric // A helper to multiply 2 signed integers where overflowing is allowed.
67bdd1243dSDimitry Andric static int64_t multiplyWithOverflow(int64_t A, int64_t B) {
68bdd1243dSDimitry Andric   int64_t Result;
69bdd1243dSDimitry Andric   MulOverflow(A, B, Result);
70bdd1243dSDimitry Andric   return Result;
71bdd1243dSDimitry Andric }
72bdd1243dSDimitry Andric 
73bdd1243dSDimitry Andric // A helper to add 2 signed integers where overflowing is allowed.
74bdd1243dSDimitry Andric static int64_t addWithOverflow(int64_t A, int64_t B) {
75bdd1243dSDimitry Andric   int64_t Result;
76bdd1243dSDimitry Andric   AddOverflow(A, B, Result);
77bdd1243dSDimitry Andric   return Result;
78bdd1243dSDimitry Andric }
79bdd1243dSDimitry Andric 
8006c3fb27SDimitry Andric static Instruction *getContextInstForUse(Use &U) {
8106c3fb27SDimitry Andric   Instruction *UserI = cast<Instruction>(U.getUser());
8206c3fb27SDimitry Andric   if (auto *Phi = dyn_cast<PHINode>(UserI))
8306c3fb27SDimitry Andric     UserI = Phi->getIncomingBlock(U)->getTerminator();
8406c3fb27SDimitry Andric   return UserI;
8506c3fb27SDimitry Andric }
8606c3fb27SDimitry Andric 
8704eeddc0SDimitry Andric namespace {
885f757f3fSDimitry Andric /// Struct to express a condition of the form %Op0 Pred %Op1.
895f757f3fSDimitry Andric struct ConditionTy {
905f757f3fSDimitry Andric   CmpInst::Predicate Pred;
915f757f3fSDimitry Andric   Value *Op0;
925f757f3fSDimitry Andric   Value *Op1;
935f757f3fSDimitry Andric 
945f757f3fSDimitry Andric   ConditionTy()
955f757f3fSDimitry Andric       : Pred(CmpInst::BAD_ICMP_PREDICATE), Op0(nullptr), Op1(nullptr) {}
965f757f3fSDimitry Andric   ConditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
975f757f3fSDimitry Andric       : Pred(Pred), Op0(Op0), Op1(Op1) {}
985f757f3fSDimitry Andric };
995f757f3fSDimitry Andric 
10006c3fb27SDimitry Andric /// Represents either
1015f757f3fSDimitry Andric ///  * a condition that holds on entry to a block (=condition fact)
10206c3fb27SDimitry Andric ///  * an assume (=assume fact)
10306c3fb27SDimitry Andric ///  * a use of a compare instruction to simplify.
10406c3fb27SDimitry Andric /// It also tracks the Dominator DFS in and out numbers for each entry.
10506c3fb27SDimitry Andric struct FactOrCheck {
1065f757f3fSDimitry Andric   enum class EntryTy {
1075f757f3fSDimitry Andric     ConditionFact, /// A condition that holds on entry to a block.
1085f757f3fSDimitry Andric     InstFact,      /// A fact that holds after Inst executed (e.g. an assume or
1095f757f3fSDimitry Andric                    /// min/mix intrinsic.
1105f757f3fSDimitry Andric     InstCheck,     /// An instruction to simplify (e.g. an overflow math
1115f757f3fSDimitry Andric                    /// intrinsics).
1125f757f3fSDimitry Andric     UseCheck       /// An use of a compare instruction to simplify.
1135f757f3fSDimitry Andric   };
1145f757f3fSDimitry Andric 
11506c3fb27SDimitry Andric   union {
11606c3fb27SDimitry Andric     Instruction *Inst;
11706c3fb27SDimitry Andric     Use *U;
1185f757f3fSDimitry Andric     ConditionTy Cond;
11906c3fb27SDimitry Andric   };
1205f757f3fSDimitry Andric 
1215f757f3fSDimitry Andric   /// A pre-condition that must hold for the current fact to be added to the
1225f757f3fSDimitry Andric   /// system.
1235f757f3fSDimitry Andric   ConditionTy DoesHold;
1245f757f3fSDimitry Andric 
12506c3fb27SDimitry Andric   unsigned NumIn;
12606c3fb27SDimitry Andric   unsigned NumOut;
1275f757f3fSDimitry Andric   EntryTy Ty;
12806c3fb27SDimitry Andric 
1295f757f3fSDimitry Andric   FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst)
13006c3fb27SDimitry Andric       : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
1315f757f3fSDimitry Andric         Ty(Ty) {}
13206c3fb27SDimitry Andric 
13306c3fb27SDimitry Andric   FactOrCheck(DomTreeNode *DTN, Use *U)
1345f757f3fSDimitry Andric       : U(U), DoesHold(CmpInst::BAD_ICMP_PREDICATE, nullptr, nullptr),
1355f757f3fSDimitry Andric         NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
1365f757f3fSDimitry Andric         Ty(EntryTy::UseCheck) {}
13706c3fb27SDimitry Andric 
1385f757f3fSDimitry Andric   FactOrCheck(DomTreeNode *DTN, CmpInst::Predicate Pred, Value *Op0, Value *Op1,
1395f757f3fSDimitry Andric               ConditionTy Precond = ConditionTy())
1405f757f3fSDimitry Andric       : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()),
1415f757f3fSDimitry Andric         NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {}
1425f757f3fSDimitry Andric 
1435f757f3fSDimitry Andric   static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpInst::Predicate Pred,
1445f757f3fSDimitry Andric                                       Value *Op0, Value *Op1,
1455f757f3fSDimitry Andric                                       ConditionTy Precond = ConditionTy()) {
1465f757f3fSDimitry Andric     return FactOrCheck(DTN, Pred, Op0, Op1, Precond);
1475f757f3fSDimitry Andric   }
1485f757f3fSDimitry Andric 
1495f757f3fSDimitry Andric   static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) {
1505f757f3fSDimitry Andric     return FactOrCheck(EntryTy::InstFact, DTN, Inst);
15106c3fb27SDimitry Andric   }
15206c3fb27SDimitry Andric 
15306c3fb27SDimitry Andric   static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) {
15406c3fb27SDimitry Andric     return FactOrCheck(DTN, U);
15506c3fb27SDimitry Andric   }
15606c3fb27SDimitry Andric 
15706c3fb27SDimitry Andric   static FactOrCheck getCheck(DomTreeNode *DTN, CallInst *CI) {
1585f757f3fSDimitry Andric     return FactOrCheck(EntryTy::InstCheck, DTN, CI);
15906c3fb27SDimitry Andric   }
16006c3fb27SDimitry Andric 
16106c3fb27SDimitry Andric   bool isCheck() const {
1625f757f3fSDimitry Andric     return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck;
16306c3fb27SDimitry Andric   }
16406c3fb27SDimitry Andric 
16506c3fb27SDimitry Andric   Instruction *getContextInst() const {
1665f757f3fSDimitry Andric     if (Ty == EntryTy::UseCheck)
16706c3fb27SDimitry Andric       return getContextInstForUse(*U);
1685f757f3fSDimitry Andric     return Inst;
16906c3fb27SDimitry Andric   }
1705f757f3fSDimitry Andric 
17106c3fb27SDimitry Andric   Instruction *getInstructionToSimplify() const {
17206c3fb27SDimitry Andric     assert(isCheck());
1735f757f3fSDimitry Andric     if (Ty == EntryTy::InstCheck)
17406c3fb27SDimitry Andric       return Inst;
17506c3fb27SDimitry Andric     // The use may have been simplified to a constant already.
17606c3fb27SDimitry Andric     return dyn_cast<Instruction>(*U);
17706c3fb27SDimitry Andric   }
1785f757f3fSDimitry Andric 
1795f757f3fSDimitry Andric   bool isConditionFact() const { return Ty == EntryTy::ConditionFact; }
18006c3fb27SDimitry Andric };
18106c3fb27SDimitry Andric 
18206c3fb27SDimitry Andric /// Keep state required to build worklist.
18306c3fb27SDimitry Andric struct State {
18406c3fb27SDimitry Andric   DominatorTree &DT;
1855f757f3fSDimitry Andric   LoopInfo &LI;
1865f757f3fSDimitry Andric   ScalarEvolution &SE;
18706c3fb27SDimitry Andric   SmallVector<FactOrCheck, 64> WorkList;
18806c3fb27SDimitry Andric 
1895f757f3fSDimitry Andric   State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE)
1905f757f3fSDimitry Andric       : DT(DT), LI(LI), SE(SE) {}
19106c3fb27SDimitry Andric 
19206c3fb27SDimitry Andric   /// Process block \p BB and add known facts to work-list.
19306c3fb27SDimitry Andric   void addInfoFor(BasicBlock &BB);
19406c3fb27SDimitry Andric 
1955f757f3fSDimitry Andric   /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares
1965f757f3fSDimitry Andric   /// controlling the loop header.
1975f757f3fSDimitry Andric   void addInfoForInductions(BasicBlock &BB);
1985f757f3fSDimitry Andric 
19906c3fb27SDimitry Andric   /// Returns true if we can add a known condition from BB to its successor
20006c3fb27SDimitry Andric   /// block Succ.
20106c3fb27SDimitry Andric   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
20206c3fb27SDimitry Andric     return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
20306c3fb27SDimitry Andric   }
20406c3fb27SDimitry Andric };
20504eeddc0SDimitry Andric 
20681ad6265SDimitry Andric class ConstraintInfo;
20704eeddc0SDimitry Andric 
20881ad6265SDimitry Andric struct StackEntry {
20981ad6265SDimitry Andric   unsigned NumIn;
21081ad6265SDimitry Andric   unsigned NumOut;
21181ad6265SDimitry Andric   bool IsSigned = false;
21281ad6265SDimitry Andric   /// Variables that can be removed from the system once the stack entry gets
21381ad6265SDimitry Andric   /// removed.
21481ad6265SDimitry Andric   SmallVector<Value *, 2> ValuesToRelease;
21581ad6265SDimitry Andric 
216bdd1243dSDimitry Andric   StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
21781ad6265SDimitry Andric              SmallVector<Value *, 2> ValuesToRelease)
218bdd1243dSDimitry Andric       : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
21981ad6265SDimitry Andric         ValuesToRelease(ValuesToRelease) {}
22004eeddc0SDimitry Andric };
22104eeddc0SDimitry Andric 
22281ad6265SDimitry Andric struct ConstraintTy {
22381ad6265SDimitry Andric   SmallVector<int64_t, 8> Coefficients;
2245f757f3fSDimitry Andric   SmallVector<ConditionTy, 2> Preconditions;
22504eeddc0SDimitry Andric 
226bdd1243dSDimitry Andric   SmallVector<SmallVector<int64_t, 8>> ExtraInfo;
227bdd1243dSDimitry Andric 
22881ad6265SDimitry Andric   bool IsSigned = false;
22904eeddc0SDimitry Andric 
23081ad6265SDimitry Andric   ConstraintTy() = default;
23104eeddc0SDimitry Andric 
23206c3fb27SDimitry Andric   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned, bool IsEq,
23306c3fb27SDimitry Andric                bool IsNe)
23406c3fb27SDimitry Andric       : Coefficients(Coefficients), IsSigned(IsSigned), IsEq(IsEq), IsNe(IsNe) {
23506c3fb27SDimitry Andric   }
23681ad6265SDimitry Andric 
23781ad6265SDimitry Andric   unsigned size() const { return Coefficients.size(); }
23881ad6265SDimitry Andric 
23981ad6265SDimitry Andric   unsigned empty() const { return Coefficients.empty(); }
24004eeddc0SDimitry Andric 
24181ad6265SDimitry Andric   /// Returns true if all preconditions for this list of constraints are
24281ad6265SDimitry Andric   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
24381ad6265SDimitry Andric   bool isValid(const ConstraintInfo &Info) const;
24406c3fb27SDimitry Andric 
24506c3fb27SDimitry Andric   bool isEq() const { return IsEq; }
24606c3fb27SDimitry Andric 
24706c3fb27SDimitry Andric   bool isNe() const { return IsNe; }
24806c3fb27SDimitry Andric 
24906c3fb27SDimitry Andric   /// Check if the current constraint is implied by the given ConstraintSystem.
25006c3fb27SDimitry Andric   ///
25106c3fb27SDimitry Andric   /// \return true or false if the constraint is proven to be respectively true,
25206c3fb27SDimitry Andric   /// or false. When the constraint cannot be proven to be either true or false,
25306c3fb27SDimitry Andric   /// std::nullopt is returned.
25406c3fb27SDimitry Andric   std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const;
25506c3fb27SDimitry Andric 
25606c3fb27SDimitry Andric private:
25706c3fb27SDimitry Andric   bool IsEq = false;
25806c3fb27SDimitry Andric   bool IsNe = false;
25981ad6265SDimitry Andric };
26081ad6265SDimitry Andric 
26181ad6265SDimitry Andric /// Wrapper encapsulating separate constraint systems and corresponding value
26281ad6265SDimitry Andric /// mappings for both unsigned and signed information. Facts are added to and
26381ad6265SDimitry Andric /// conditions are checked against the corresponding system depending on the
26481ad6265SDimitry Andric /// signed-ness of their predicates. While the information is kept separate
26581ad6265SDimitry Andric /// based on signed-ness, certain conditions can be transferred between the two
26681ad6265SDimitry Andric /// systems.
26781ad6265SDimitry Andric class ConstraintInfo {
26881ad6265SDimitry Andric 
26981ad6265SDimitry Andric   ConstraintSystem UnsignedCS;
27081ad6265SDimitry Andric   ConstraintSystem SignedCS;
27181ad6265SDimitry Andric 
272bdd1243dSDimitry Andric   const DataLayout &DL;
273bdd1243dSDimitry Andric 
27481ad6265SDimitry Andric public:
27506c3fb27SDimitry Andric   ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
276cb14a3feSDimitry Andric       : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {
277cb14a3feSDimitry Andric     auto &Value2Index = getValue2Index(false);
278cb14a3feSDimitry Andric     // Add Arg > -1 constraints to unsigned system for all function arguments.
279cb14a3feSDimitry Andric     for (Value *Arg : FunctionArgs) {
280cb14a3feSDimitry Andric       ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
281cb14a3feSDimitry Andric                           false, false, false);
282cb14a3feSDimitry Andric       VarPos.Coefficients[Value2Index[Arg]] = -1;
283cb14a3feSDimitry Andric       UnsignedCS.addVariableRow(VarPos.Coefficients);
284cb14a3feSDimitry Andric     }
285cb14a3feSDimitry Andric   }
286bdd1243dSDimitry Andric 
28781ad6265SDimitry Andric   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
28806c3fb27SDimitry Andric     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
28981ad6265SDimitry Andric   }
29081ad6265SDimitry Andric   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
29106c3fb27SDimitry Andric     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
29281ad6265SDimitry Andric   }
29381ad6265SDimitry Andric 
29481ad6265SDimitry Andric   ConstraintSystem &getCS(bool Signed) {
29581ad6265SDimitry Andric     return Signed ? SignedCS : UnsignedCS;
29681ad6265SDimitry Andric   }
29781ad6265SDimitry Andric   const ConstraintSystem &getCS(bool Signed) const {
29881ad6265SDimitry Andric     return Signed ? SignedCS : UnsignedCS;
29981ad6265SDimitry Andric   }
30081ad6265SDimitry Andric 
30181ad6265SDimitry Andric   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
30281ad6265SDimitry Andric   void popLastNVariables(bool Signed, unsigned N) {
30381ad6265SDimitry Andric     getCS(Signed).popLastNVariables(N);
30481ad6265SDimitry Andric   }
30581ad6265SDimitry Andric 
30681ad6265SDimitry Andric   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
30781ad6265SDimitry Andric 
308bdd1243dSDimitry Andric   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
309bdd1243dSDimitry Andric                unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
31081ad6265SDimitry Andric 
31181ad6265SDimitry Andric   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
31281ad6265SDimitry Andric   /// constraints, using indices from the corresponding constraint system.
313bdd1243dSDimitry Andric   /// New variables that need to be added to the system are collected in
314bdd1243dSDimitry Andric   /// \p NewVariables.
31581ad6265SDimitry Andric   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
316bdd1243dSDimitry Andric                              SmallVectorImpl<Value *> &NewVariables) const;
31781ad6265SDimitry Andric 
318bdd1243dSDimitry Andric   /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
319bdd1243dSDimitry Andric   /// constraints using getConstraint. Returns an empty constraint if the result
320bdd1243dSDimitry Andric   /// cannot be used to query the existing constraint system, e.g. because it
321bdd1243dSDimitry Andric   /// would require adding new variables. Also tries to convert signed
322bdd1243dSDimitry Andric   /// predicates to unsigned ones if possible to allow using the unsigned system
323bdd1243dSDimitry Andric   /// which increases the effectiveness of the signed <-> unsigned transfer
324bdd1243dSDimitry Andric   /// logic.
325bdd1243dSDimitry Andric   ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
326bdd1243dSDimitry Andric                                        Value *Op1) const;
32781ad6265SDimitry Andric 
32881ad6265SDimitry Andric   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
32981ad6265SDimitry Andric   /// system if \p Pred is signed/unsigned.
33081ad6265SDimitry Andric   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
331bdd1243dSDimitry Andric                              unsigned NumIn, unsigned NumOut,
33281ad6265SDimitry Andric                              SmallVectorImpl<StackEntry> &DFSInStack);
33304eeddc0SDimitry Andric };
33404eeddc0SDimitry Andric 
335bdd1243dSDimitry Andric /// Represents a (Coefficient * Variable) entry after IR decomposition.
336bdd1243dSDimitry Andric struct DecompEntry {
337bdd1243dSDimitry Andric   int64_t Coefficient;
338bdd1243dSDimitry Andric   Value *Variable;
339bdd1243dSDimitry Andric   /// True if the variable is known positive in the current constraint.
340bdd1243dSDimitry Andric   bool IsKnownNonNegative;
341bdd1243dSDimitry Andric 
342bdd1243dSDimitry Andric   DecompEntry(int64_t Coefficient, Value *Variable,
343bdd1243dSDimitry Andric               bool IsKnownNonNegative = false)
344bdd1243dSDimitry Andric       : Coefficient(Coefficient), Variable(Variable),
345bdd1243dSDimitry Andric         IsKnownNonNegative(IsKnownNonNegative) {}
346bdd1243dSDimitry Andric };
347bdd1243dSDimitry Andric 
348bdd1243dSDimitry Andric /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
349bdd1243dSDimitry Andric struct Decomposition {
350bdd1243dSDimitry Andric   int64_t Offset = 0;
351bdd1243dSDimitry Andric   SmallVector<DecompEntry, 3> Vars;
352bdd1243dSDimitry Andric 
353bdd1243dSDimitry Andric   Decomposition(int64_t Offset) : Offset(Offset) {}
354bdd1243dSDimitry Andric   Decomposition(Value *V, bool IsKnownNonNegative = false) {
355bdd1243dSDimitry Andric     Vars.emplace_back(1, V, IsKnownNonNegative);
356bdd1243dSDimitry Andric   }
357bdd1243dSDimitry Andric   Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
358bdd1243dSDimitry Andric       : Offset(Offset), Vars(Vars) {}
359bdd1243dSDimitry Andric 
360bdd1243dSDimitry Andric   void add(int64_t OtherOffset) {
361bdd1243dSDimitry Andric     Offset = addWithOverflow(Offset, OtherOffset);
362bdd1243dSDimitry Andric   }
363bdd1243dSDimitry Andric 
364bdd1243dSDimitry Andric   void add(const Decomposition &Other) {
365bdd1243dSDimitry Andric     add(Other.Offset);
366bdd1243dSDimitry Andric     append_range(Vars, Other.Vars);
367bdd1243dSDimitry Andric   }
368bdd1243dSDimitry Andric 
369647cbc5dSDimitry Andric   void sub(const Decomposition &Other) {
370647cbc5dSDimitry Andric     Decomposition Tmp = Other;
371647cbc5dSDimitry Andric     Tmp.mul(-1);
372647cbc5dSDimitry Andric     add(Tmp.Offset);
373647cbc5dSDimitry Andric     append_range(Vars, Tmp.Vars);
374647cbc5dSDimitry Andric   }
375647cbc5dSDimitry Andric 
376bdd1243dSDimitry Andric   void mul(int64_t Factor) {
377bdd1243dSDimitry Andric     Offset = multiplyWithOverflow(Offset, Factor);
378bdd1243dSDimitry Andric     for (auto &Var : Vars)
379bdd1243dSDimitry Andric       Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor);
380bdd1243dSDimitry Andric   }
381bdd1243dSDimitry Andric };
382bdd1243dSDimitry Andric 
3835f757f3fSDimitry Andric // Variable and constant offsets for a chain of GEPs, with base pointer BasePtr.
3845f757f3fSDimitry Andric struct OffsetResult {
3855f757f3fSDimitry Andric   Value *BasePtr;
3865f757f3fSDimitry Andric   APInt ConstantOffset;
3875f757f3fSDimitry Andric   MapVector<Value *, APInt> VariableOffsets;
3885f757f3fSDimitry Andric   bool AllInbounds;
3895f757f3fSDimitry Andric 
3905f757f3fSDimitry Andric   OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {}
3915f757f3fSDimitry Andric 
3925f757f3fSDimitry Andric   OffsetResult(GEPOperator &GEP, const DataLayout &DL)
3935f757f3fSDimitry Andric       : BasePtr(GEP.getPointerOperand()), AllInbounds(GEP.isInBounds()) {
3945f757f3fSDimitry Andric     ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0);
3955f757f3fSDimitry Andric   }
3965f757f3fSDimitry Andric };
39704eeddc0SDimitry Andric } // namespace
39804eeddc0SDimitry Andric 
3995f757f3fSDimitry Andric // Try to collect variable and constant offsets for \p GEP, partly traversing
4005f757f3fSDimitry Andric // nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting
4015f757f3fSDimitry Andric // the offset fails.
4025f757f3fSDimitry Andric static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL) {
4035f757f3fSDimitry Andric   OffsetResult Result(GEP, DL);
4045f757f3fSDimitry Andric   unsigned BitWidth = Result.ConstantOffset.getBitWidth();
4055f757f3fSDimitry Andric   if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets,
4065f757f3fSDimitry Andric                          Result.ConstantOffset))
4075f757f3fSDimitry Andric     return {};
4085f757f3fSDimitry Andric 
4095f757f3fSDimitry Andric   // If we have a nested GEP, check if we can combine the constant offset of the
4105f757f3fSDimitry Andric   // inner GEP with the outer GEP.
4115f757f3fSDimitry Andric   if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) {
4125f757f3fSDimitry Andric     MapVector<Value *, APInt> VariableOffsets2;
4135f757f3fSDimitry Andric     APInt ConstantOffset2(BitWidth, 0);
4145f757f3fSDimitry Andric     bool CanCollectInner = InnerGEP->collectOffset(
4155f757f3fSDimitry Andric         DL, BitWidth, VariableOffsets2, ConstantOffset2);
4165f757f3fSDimitry Andric     // TODO: Support cases with more than 1 variable offset.
4175f757f3fSDimitry Andric     if (!CanCollectInner || Result.VariableOffsets.size() > 1 ||
4185f757f3fSDimitry Andric         VariableOffsets2.size() > 1 ||
4195f757f3fSDimitry Andric         (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) {
4205f757f3fSDimitry Andric       // More than 1 variable index, use outer result.
4215f757f3fSDimitry Andric       return Result;
4225f757f3fSDimitry Andric     }
4235f757f3fSDimitry Andric     Result.BasePtr = InnerGEP->getPointerOperand();
4245f757f3fSDimitry Andric     Result.ConstantOffset += ConstantOffset2;
4255f757f3fSDimitry Andric     if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1)
4265f757f3fSDimitry Andric       Result.VariableOffsets = VariableOffsets2;
4275f757f3fSDimitry Andric     Result.AllInbounds &= InnerGEP->isInBounds();
4285f757f3fSDimitry Andric   }
4295f757f3fSDimitry Andric   return Result;
4305f757f3fSDimitry Andric }
4315f757f3fSDimitry Andric 
432bdd1243dSDimitry Andric static Decomposition decompose(Value *V,
4335f757f3fSDimitry Andric                                SmallVectorImpl<ConditionTy> &Preconditions,
434bdd1243dSDimitry Andric                                bool IsSigned, const DataLayout &DL);
43581ad6265SDimitry Andric 
436bdd1243dSDimitry Andric static bool canUseSExt(ConstantInt *CI) {
43781ad6265SDimitry Andric   const APInt &Val = CI->getValue();
43881ad6265SDimitry Andric   return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
439bdd1243dSDimitry Andric }
440bdd1243dSDimitry Andric 
4415f757f3fSDimitry Andric static Decomposition decomposeGEP(GEPOperator &GEP,
4425f757f3fSDimitry Andric                                   SmallVectorImpl<ConditionTy> &Preconditions,
44306c3fb27SDimitry Andric                                   bool IsSigned, const DataLayout &DL) {
444bdd1243dSDimitry Andric   // Do not reason about pointers where the index size is larger than 64 bits,
445bdd1243dSDimitry Andric   // as the coefficients used to encode constraints are 64 bit integers.
446bdd1243dSDimitry Andric   if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
447bdd1243dSDimitry Andric     return &GEP;
448bdd1243dSDimitry Andric 
449bdd1243dSDimitry Andric   assert(!IsSigned && "The logic below only supports decomposition for "
4505f757f3fSDimitry Andric                       "unsigned predicates at the moment.");
4515f757f3fSDimitry Andric   const auto &[BasePtr, ConstantOffset, VariableOffsets, AllInbounds] =
4525f757f3fSDimitry Andric       collectOffsets(GEP, DL);
4535f757f3fSDimitry Andric   if (!BasePtr || !AllInbounds)
454bdd1243dSDimitry Andric     return &GEP;
455bdd1243dSDimitry Andric 
4565f757f3fSDimitry Andric   Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr));
457bdd1243dSDimitry Andric   for (auto [Index, Scale] : VariableOffsets) {
458bdd1243dSDimitry Andric     auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
459bdd1243dSDimitry Andric     IdxResult.mul(Scale.getSExtValue());
460bdd1243dSDimitry Andric     Result.add(IdxResult);
461bdd1243dSDimitry Andric 
462bdd1243dSDimitry Andric     // If Op0 is signed non-negative, the GEP is increasing monotonically and
463bdd1243dSDimitry Andric     // can be de-composed.
464bdd1243dSDimitry Andric     if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
465bdd1243dSDimitry Andric       Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
466bdd1243dSDimitry Andric                                  ConstantInt::get(Index->getType(), 0));
467bdd1243dSDimitry Andric   }
468bdd1243dSDimitry Andric   return Result;
469bdd1243dSDimitry Andric }
470bdd1243dSDimitry Andric 
471bdd1243dSDimitry Andric // Decomposes \p V into a constant offset + list of pairs { Coefficient,
472bdd1243dSDimitry Andric // Variable } where Coefficient * Variable. The sum of the constant offset and
473bdd1243dSDimitry Andric // pairs equals \p V.
474bdd1243dSDimitry Andric static Decomposition decompose(Value *V,
4755f757f3fSDimitry Andric                                SmallVectorImpl<ConditionTy> &Preconditions,
476bdd1243dSDimitry Andric                                bool IsSigned, const DataLayout &DL) {
477bdd1243dSDimitry Andric 
478bdd1243dSDimitry Andric   auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B,
479bdd1243dSDimitry Andric                                                       bool IsSignedB) {
480bdd1243dSDimitry Andric     auto ResA = decompose(A, Preconditions, IsSigned, DL);
481bdd1243dSDimitry Andric     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
482bdd1243dSDimitry Andric     ResA.add(ResB);
483bdd1243dSDimitry Andric     return ResA;
48481ad6265SDimitry Andric   };
485bdd1243dSDimitry Andric 
486b121cb00SDimitry Andric   Type *Ty = V->getType()->getScalarType();
487b121cb00SDimitry Andric   if (Ty->isPointerTy() && !IsSigned) {
488b121cb00SDimitry Andric     if (auto *GEP = dyn_cast<GEPOperator>(V))
489b121cb00SDimitry Andric       return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
4905f757f3fSDimitry Andric     if (isa<ConstantPointerNull>(V))
4915f757f3fSDimitry Andric       return int64_t(0);
4925f757f3fSDimitry Andric 
493b121cb00SDimitry Andric     return V;
494b121cb00SDimitry Andric   }
495b121cb00SDimitry Andric 
496b121cb00SDimitry Andric   // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so
497b121cb00SDimitry Andric   // coefficient add/mul may wrap, while the operation in the full bit width
498b121cb00SDimitry Andric   // would not.
499b121cb00SDimitry Andric   if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
500b121cb00SDimitry Andric     return V;
501b121cb00SDimitry Andric 
50281ad6265SDimitry Andric   // Decompose \p V used with a signed predicate.
50381ad6265SDimitry Andric   if (IsSigned) {
504e8d8bef9SDimitry Andric     if (auto *CI = dyn_cast<ConstantInt>(V)) {
505bdd1243dSDimitry Andric       if (canUseSExt(CI))
506bdd1243dSDimitry Andric         return CI->getSExtValue();
507e8d8bef9SDimitry Andric     }
508bdd1243dSDimitry Andric     Value *Op0;
509bdd1243dSDimitry Andric     Value *Op1;
510bdd1243dSDimitry Andric     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
511bdd1243dSDimitry Andric       return MergeResults(Op0, Op1, IsSigned);
51281ad6265SDimitry Andric 
51306c3fb27SDimitry Andric     ConstantInt *CI;
5148a4dda33SDimitry Andric     if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) {
51506c3fb27SDimitry Andric       auto Result = decompose(Op0, Preconditions, IsSigned, DL);
51606c3fb27SDimitry Andric       Result.mul(CI->getSExtValue());
51706c3fb27SDimitry Andric       return Result;
51806c3fb27SDimitry Andric     }
51906c3fb27SDimitry Andric 
5201db9f3b2SDimitry Andric     // (shl nsw x, shift) is (mul nsw x, (1<<shift)), with the exception of
5211db9f3b2SDimitry Andric     // shift == bw-1.
5221db9f3b2SDimitry Andric     if (match(V, m_NSWShl(m_Value(Op0), m_ConstantInt(CI)))) {
5231db9f3b2SDimitry Andric       uint64_t Shift = CI->getValue().getLimitedValue();
5241db9f3b2SDimitry Andric       if (Shift < Ty->getIntegerBitWidth() - 1) {
5251db9f3b2SDimitry Andric         assert(Shift < 64 && "Would overflow");
5261db9f3b2SDimitry Andric         auto Result = decompose(Op0, Preconditions, IsSigned, DL);
5271db9f3b2SDimitry Andric         Result.mul(int64_t(1) << Shift);
5281db9f3b2SDimitry Andric         return Result;
5291db9f3b2SDimitry Andric       }
5301db9f3b2SDimitry Andric     }
5311db9f3b2SDimitry Andric 
532bdd1243dSDimitry Andric     return V;
53381ad6265SDimitry Andric   }
53481ad6265SDimitry Andric 
53581ad6265SDimitry Andric   if (auto *CI = dyn_cast<ConstantInt>(V)) {
53681ad6265SDimitry Andric     if (CI->uge(MaxConstraintValue))
537bdd1243dSDimitry Andric       return V;
538bdd1243dSDimitry Andric     return int64_t(CI->getZExtValue());
539fe6060f1SDimitry Andric   }
540fe6060f1SDimitry Andric 
541e8d8bef9SDimitry Andric   Value *Op0;
542bdd1243dSDimitry Andric   bool IsKnownNonNegative = false;
543bdd1243dSDimitry Andric   if (match(V, m_ZExt(m_Value(Op0)))) {
544bdd1243dSDimitry Andric     IsKnownNonNegative = true;
545fe6060f1SDimitry Andric     V = Op0;
546bdd1243dSDimitry Andric   }
547fe6060f1SDimitry Andric 
548e8d8bef9SDimitry Andric   Value *Op1;
549e8d8bef9SDimitry Andric   ConstantInt *CI;
550bdd1243dSDimitry Andric   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
551bdd1243dSDimitry Andric     return MergeResults(Op0, Op1, IsSigned);
552bdd1243dSDimitry Andric   }
553bdd1243dSDimitry Andric   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
554bdd1243dSDimitry Andric     if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
555bdd1243dSDimitry Andric       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
556bdd1243dSDimitry Andric                                  ConstantInt::get(Op0->getType(), 0));
557bdd1243dSDimitry Andric     if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
558bdd1243dSDimitry Andric       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
559bdd1243dSDimitry Andric                                  ConstantInt::get(Op1->getType(), 0));
560bdd1243dSDimitry Andric 
561bdd1243dSDimitry Andric     return MergeResults(Op0, Op1, IsSigned);
562bdd1243dSDimitry Andric   }
563bdd1243dSDimitry Andric 
56481ad6265SDimitry Andric   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
565bdd1243dSDimitry Andric       canUseSExt(CI)) {
56681ad6265SDimitry Andric     Preconditions.emplace_back(
56781ad6265SDimitry Andric         CmpInst::ICMP_UGE, Op0,
56881ad6265SDimitry Andric         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
569bdd1243dSDimitry Andric     return MergeResults(Op0, CI, true);
57081ad6265SDimitry Andric   }
571e8d8bef9SDimitry Andric 
57206c3fb27SDimitry Andric   // Decompose or as an add if there are no common bits between the operands.
5735f757f3fSDimitry Andric   if (match(V, m_DisjointOr(m_Value(Op0), m_ConstantInt(CI))))
57406c3fb27SDimitry Andric     return MergeResults(Op0, CI, IsSigned);
57506c3fb27SDimitry Andric 
576bdd1243dSDimitry Andric   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
57706c3fb27SDimitry Andric     if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64)
57806c3fb27SDimitry Andric       return {V, IsKnownNonNegative};
579bdd1243dSDimitry Andric     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
58006c3fb27SDimitry Andric     Result.mul(int64_t{1} << CI->getSExtValue());
581bdd1243dSDimitry Andric     return Result;
582bdd1243dSDimitry Andric   }
583bdd1243dSDimitry Andric 
584bdd1243dSDimitry Andric   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
585bdd1243dSDimitry Andric       (!CI->isNegative())) {
586bdd1243dSDimitry Andric     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
587bdd1243dSDimitry Andric     Result.mul(CI->getSExtValue());
588bdd1243dSDimitry Andric     return Result;
589bdd1243dSDimitry Andric   }
590bdd1243dSDimitry Andric 
591647cbc5dSDimitry Andric   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) {
592647cbc5dSDimitry Andric     auto ResA = decompose(Op0, Preconditions, IsSigned, DL);
593647cbc5dSDimitry Andric     auto ResB = decompose(Op1, Preconditions, IsSigned, DL);
594647cbc5dSDimitry Andric     ResA.sub(ResB);
595647cbc5dSDimitry Andric     return ResA;
596647cbc5dSDimitry Andric   }
597e8d8bef9SDimitry Andric 
598bdd1243dSDimitry Andric   return {V, IsKnownNonNegative};
599e8d8bef9SDimitry Andric }
600e8d8bef9SDimitry Andric 
60181ad6265SDimitry Andric ConstraintTy
60281ad6265SDimitry Andric ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
603bdd1243dSDimitry Andric                               SmallVectorImpl<Value *> &NewVariables) const {
604bdd1243dSDimitry Andric   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
60581ad6265SDimitry Andric   bool IsEq = false;
60606c3fb27SDimitry Andric   bool IsNe = false;
60706c3fb27SDimitry Andric 
60881ad6265SDimitry Andric   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
60981ad6265SDimitry Andric   switch (Pred) {
61081ad6265SDimitry Andric   case CmpInst::ICMP_UGT:
61181ad6265SDimitry Andric   case CmpInst::ICMP_UGE:
61281ad6265SDimitry Andric   case CmpInst::ICMP_SGT:
61381ad6265SDimitry Andric   case CmpInst::ICMP_SGE: {
61481ad6265SDimitry Andric     Pred = CmpInst::getSwappedPredicate(Pred);
61581ad6265SDimitry Andric     std::swap(Op0, Op1);
61681ad6265SDimitry Andric     break;
61781ad6265SDimitry Andric   }
61881ad6265SDimitry Andric   case CmpInst::ICMP_EQ:
61981ad6265SDimitry Andric     if (match(Op1, m_Zero())) {
62081ad6265SDimitry Andric       Pred = CmpInst::ICMP_ULE;
62181ad6265SDimitry Andric     } else {
62281ad6265SDimitry Andric       IsEq = true;
62381ad6265SDimitry Andric       Pred = CmpInst::ICMP_ULE;
62481ad6265SDimitry Andric     }
62581ad6265SDimitry Andric     break;
62681ad6265SDimitry Andric   case CmpInst::ICMP_NE:
62706c3fb27SDimitry Andric     if (match(Op1, m_Zero())) {
62881ad6265SDimitry Andric       Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
62981ad6265SDimitry Andric       std::swap(Op0, Op1);
63006c3fb27SDimitry Andric     } else {
63106c3fb27SDimitry Andric       IsNe = true;
63206c3fb27SDimitry Andric       Pred = CmpInst::ICMP_ULE;
63306c3fb27SDimitry Andric     }
63481ad6265SDimitry Andric     break;
63581ad6265SDimitry Andric   default:
63681ad6265SDimitry Andric     break;
63781ad6265SDimitry Andric   }
63881ad6265SDimitry Andric 
63981ad6265SDimitry Andric   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
64081ad6265SDimitry Andric       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
64181ad6265SDimitry Andric     return {};
64281ad6265SDimitry Andric 
6435f757f3fSDimitry Andric   SmallVector<ConditionTy, 4> Preconditions;
64481ad6265SDimitry Andric   bool IsSigned = CmpInst::isSigned(Pred);
64581ad6265SDimitry Andric   auto &Value2Index = getValue2Index(IsSigned);
64681ad6265SDimitry Andric   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
647bdd1243dSDimitry Andric                         Preconditions, IsSigned, DL);
64881ad6265SDimitry Andric   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
649bdd1243dSDimitry Andric                         Preconditions, IsSigned, DL);
650bdd1243dSDimitry Andric   int64_t Offset1 = ADec.Offset;
651bdd1243dSDimitry Andric   int64_t Offset2 = BDec.Offset;
65281ad6265SDimitry Andric   Offset1 *= -1;
65381ad6265SDimitry Andric 
654bdd1243dSDimitry Andric   auto &VariablesA = ADec.Vars;
655bdd1243dSDimitry Andric   auto &VariablesB = BDec.Vars;
656e8d8bef9SDimitry Andric 
657bdd1243dSDimitry Andric   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
658bdd1243dSDimitry Andric   // new entry to NewVariables.
6591db9f3b2SDimitry Andric   SmallDenseMap<Value *, unsigned> NewIndexMap;
660bdd1243dSDimitry Andric   auto GetOrAddIndex = [&Value2Index, &NewVariables,
661bdd1243dSDimitry Andric                         &NewIndexMap](Value *V) -> unsigned {
662fe6060f1SDimitry Andric     auto V2I = Value2Index.find(V);
663fe6060f1SDimitry Andric     if (V2I != Value2Index.end())
664fe6060f1SDimitry Andric       return V2I->second;
665fe6060f1SDimitry Andric     auto Insert =
666bdd1243dSDimitry Andric         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
667bdd1243dSDimitry Andric     if (Insert.second)
668bdd1243dSDimitry Andric       NewVariables.push_back(V);
669fe6060f1SDimitry Andric     return Insert.first->second;
670e8d8bef9SDimitry Andric   };
671e8d8bef9SDimitry Andric 
672bdd1243dSDimitry Andric   // Make sure all variables have entries in Value2Index or NewVariables.
673bdd1243dSDimitry Andric   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
674bdd1243dSDimitry Andric     GetOrAddIndex(KV.Variable);
675e8d8bef9SDimitry Andric 
676e8d8bef9SDimitry Andric   // Build result constraint, by first adding all coefficients from A and then
677e8d8bef9SDimitry Andric   // subtracting all coefficients from B.
67881ad6265SDimitry Andric   ConstraintTy Res(
679bdd1243dSDimitry Andric       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
68006c3fb27SDimitry Andric       IsSigned, IsEq, IsNe);
681bdd1243dSDimitry Andric   // Collect variables that are known to be positive in all uses in the
682bdd1243dSDimitry Andric   // constraint.
6831db9f3b2SDimitry Andric   SmallDenseMap<Value *, bool> KnownNonNegativeVariables;
68481ad6265SDimitry Andric   auto &R = Res.Coefficients;
685bdd1243dSDimitry Andric   for (const auto &KV : VariablesA) {
686bdd1243dSDimitry Andric     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
687bdd1243dSDimitry Andric     auto I =
688bdd1243dSDimitry Andric         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
689bdd1243dSDimitry Andric     I.first->second &= KV.IsKnownNonNegative;
690bdd1243dSDimitry Andric   }
691e8d8bef9SDimitry Andric 
692bdd1243dSDimitry Andric   for (const auto &KV : VariablesB) {
69306c3fb27SDimitry Andric     if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient,
69406c3fb27SDimitry Andric                     R[GetOrAddIndex(KV.Variable)]))
69506c3fb27SDimitry Andric       return {};
696bdd1243dSDimitry Andric     auto I =
697bdd1243dSDimitry Andric         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
698bdd1243dSDimitry Andric     I.first->second &= KV.IsKnownNonNegative;
699bdd1243dSDimitry Andric   }
700e8d8bef9SDimitry Andric 
70181ad6265SDimitry Andric   int64_t OffsetSum;
70281ad6265SDimitry Andric   if (AddOverflow(Offset1, Offset2, OffsetSum))
70381ad6265SDimitry Andric     return {};
70481ad6265SDimitry Andric   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
70581ad6265SDimitry Andric     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
70681ad6265SDimitry Andric       return {};
70781ad6265SDimitry Andric   R[0] = OffsetSum;
70881ad6265SDimitry Andric   Res.Preconditions = std::move(Preconditions);
709bdd1243dSDimitry Andric 
710bdd1243dSDimitry Andric   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
711bdd1243dSDimitry Andric   // variables.
712bdd1243dSDimitry Andric   while (!NewVariables.empty()) {
713bdd1243dSDimitry Andric     int64_t Last = R.back();
714bdd1243dSDimitry Andric     if (Last != 0)
715bdd1243dSDimitry Andric       break;
716bdd1243dSDimitry Andric     R.pop_back();
717bdd1243dSDimitry Andric     Value *RemovedV = NewVariables.pop_back_val();
718bdd1243dSDimitry Andric     NewIndexMap.erase(RemovedV);
719bdd1243dSDimitry Andric   }
720bdd1243dSDimitry Andric 
721bdd1243dSDimitry Andric   // Add extra constraints for variables that are known positive.
722bdd1243dSDimitry Andric   for (auto &KV : KnownNonNegativeVariables) {
72306c3fb27SDimitry Andric     if (!KV.second ||
72406c3fb27SDimitry Andric         (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first)))
725bdd1243dSDimitry Andric       continue;
726bdd1243dSDimitry Andric     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
727bdd1243dSDimitry Andric     C[GetOrAddIndex(KV.first)] = -1;
728bdd1243dSDimitry Andric     Res.ExtraInfo.push_back(C);
729bdd1243dSDimitry Andric   }
73081ad6265SDimitry Andric   return Res;
731e8d8bef9SDimitry Andric }
732e8d8bef9SDimitry Andric 
733bdd1243dSDimitry Andric ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
734bdd1243dSDimitry Andric                                                      Value *Op0,
735bdd1243dSDimitry Andric                                                      Value *Op1) const {
7365f757f3fSDimitry Andric   Constant *NullC = Constant::getNullValue(Op0->getType());
7375f757f3fSDimitry Andric   // Handle trivially true compares directly to avoid adding V UGE 0 constraints
7385f757f3fSDimitry Andric   // for all variables in the unsigned system.
7395f757f3fSDimitry Andric   if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
7405f757f3fSDimitry Andric       (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
7415f757f3fSDimitry Andric     auto &Value2Index = getValue2Index(false);
7425f757f3fSDimitry Andric     // Return constraint that's trivially true.
7435f757f3fSDimitry Andric     return ConstraintTy(SmallVector<int64_t, 8>(Value2Index.size(), 0), false,
7445f757f3fSDimitry Andric                         false, false);
7455f757f3fSDimitry Andric   }
7465f757f3fSDimitry Andric 
747bdd1243dSDimitry Andric   // If both operands are known to be non-negative, change signed predicates to
748bdd1243dSDimitry Andric   // unsigned ones. This increases the reasoning effectiveness in combination
749bdd1243dSDimitry Andric   // with the signed <-> unsigned transfer logic.
750bdd1243dSDimitry Andric   if (CmpInst::isSigned(Pred) &&
751bdd1243dSDimitry Andric       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
752bdd1243dSDimitry Andric       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
753bdd1243dSDimitry Andric     Pred = CmpInst::getUnsignedPredicate(Pred);
754bdd1243dSDimitry Andric 
755bdd1243dSDimitry Andric   SmallVector<Value *> NewVariables;
756bdd1243dSDimitry Andric   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
75706c3fb27SDimitry Andric   if (!NewVariables.empty())
758bdd1243dSDimitry Andric     return {};
759bdd1243dSDimitry Andric   return R;
760bdd1243dSDimitry Andric }
761bdd1243dSDimitry Andric 
76281ad6265SDimitry Andric bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
76381ad6265SDimitry Andric   return Coefficients.size() > 0 &&
7645f757f3fSDimitry Andric          all_of(Preconditions, [&Info](const ConditionTy &C) {
76581ad6265SDimitry Andric            return Info.doesHold(C.Pred, C.Op0, C.Op1);
76681ad6265SDimitry Andric          });
76781ad6265SDimitry Andric }
76881ad6265SDimitry Andric 
76906c3fb27SDimitry Andric std::optional<bool>
77006c3fb27SDimitry Andric ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
77106c3fb27SDimitry Andric   bool IsConditionImplied = CS.isConditionImplied(Coefficients);
77206c3fb27SDimitry Andric 
77306c3fb27SDimitry Andric   if (IsEq || IsNe) {
77406c3fb27SDimitry Andric     auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients);
77506c3fb27SDimitry Andric     bool IsNegatedOrEqualImplied =
77606c3fb27SDimitry Andric         !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual);
77706c3fb27SDimitry Andric 
77806c3fb27SDimitry Andric     // In order to check that `%a == %b` is true (equality), both conditions `%a
77906c3fb27SDimitry Andric     // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
78006c3fb27SDimitry Andric     // is true), we return true if they both hold, false in the other cases.
78106c3fb27SDimitry Andric     if (IsConditionImplied && IsNegatedOrEqualImplied)
78206c3fb27SDimitry Andric       return IsEq;
78306c3fb27SDimitry Andric 
78406c3fb27SDimitry Andric     auto Negated = ConstraintSystem::negate(Coefficients);
78506c3fb27SDimitry Andric     bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
78606c3fb27SDimitry Andric 
78706c3fb27SDimitry Andric     auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients);
78806c3fb27SDimitry Andric     bool IsStrictLessThanImplied =
78906c3fb27SDimitry Andric         !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan);
79006c3fb27SDimitry Andric 
79106c3fb27SDimitry Andric     // In order to check that `%a != %b` is true (non-equality), either
79206c3fb27SDimitry Andric     // condition `%a > %b` or `%a < %b` must hold true. When checking for
79306c3fb27SDimitry Andric     // non-equality (`IsNe` is true), we return true if one of the two holds,
79406c3fb27SDimitry Andric     // false in the other cases.
79506c3fb27SDimitry Andric     if (IsNegatedImplied || IsStrictLessThanImplied)
79606c3fb27SDimitry Andric       return IsNe;
79706c3fb27SDimitry Andric 
79806c3fb27SDimitry Andric     return std::nullopt;
79906c3fb27SDimitry Andric   }
80006c3fb27SDimitry Andric 
80106c3fb27SDimitry Andric   if (IsConditionImplied)
80206c3fb27SDimitry Andric     return true;
80306c3fb27SDimitry Andric 
80406c3fb27SDimitry Andric   auto Negated = ConstraintSystem::negate(Coefficients);
80506c3fb27SDimitry Andric   auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
80606c3fb27SDimitry Andric   if (IsNegatedImplied)
80706c3fb27SDimitry Andric     return false;
80806c3fb27SDimitry Andric 
80906c3fb27SDimitry Andric   // Neither the condition nor its negated holds, did not prove anything.
81006c3fb27SDimitry Andric   return std::nullopt;
81106c3fb27SDimitry Andric }
81206c3fb27SDimitry Andric 
81381ad6265SDimitry Andric bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
81481ad6265SDimitry Andric                               Value *B) const {
815bdd1243dSDimitry Andric   auto R = getConstraintForSolving(Pred, A, B);
81606c3fb27SDimitry Andric   return R.isValid(*this) &&
817bdd1243dSDimitry Andric          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
81881ad6265SDimitry Andric }
81981ad6265SDimitry Andric 
82081ad6265SDimitry Andric void ConstraintInfo::transferToOtherSystem(
821bdd1243dSDimitry Andric     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
82281ad6265SDimitry Andric     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
8235f757f3fSDimitry Andric   auto IsKnownNonNegative = [this](Value *V) {
8245f757f3fSDimitry Andric     return doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0)) ||
8255f757f3fSDimitry Andric            isKnownNonNegative(V, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1);
8265f757f3fSDimitry Andric   };
82781ad6265SDimitry Andric   // Check if we can combine facts from the signed and unsigned systems to
82881ad6265SDimitry Andric   // derive additional facts.
82981ad6265SDimitry Andric   if (!A->getType()->isIntegerTy())
83081ad6265SDimitry Andric     return;
83181ad6265SDimitry Andric   // FIXME: This currently depends on the order we add facts. Ideally we
83281ad6265SDimitry Andric   // would first add all known facts and only then try to add additional
83381ad6265SDimitry Andric   // facts.
83481ad6265SDimitry Andric   switch (Pred) {
83581ad6265SDimitry Andric   default:
83681ad6265SDimitry Andric     break;
83781ad6265SDimitry Andric   case CmpInst::ICMP_ULT:
8385f757f3fSDimitry Andric   case CmpInst::ICMP_ULE:
8395f757f3fSDimitry Andric     //  If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
8405f757f3fSDimitry Andric     if (IsKnownNonNegative(B)) {
841bdd1243dSDimitry Andric       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
842bdd1243dSDimitry Andric               NumOut, DFSInStack);
8435f757f3fSDimitry Andric       addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
8445f757f3fSDimitry Andric               DFSInStack);
8455f757f3fSDimitry Andric     }
8465f757f3fSDimitry Andric     break;
8475f757f3fSDimitry Andric   case CmpInst::ICMP_UGE:
8485f757f3fSDimitry Andric   case CmpInst::ICMP_UGT:
8495f757f3fSDimitry Andric     //  If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
8505f757f3fSDimitry Andric     if (IsKnownNonNegative(A)) {
8515f757f3fSDimitry Andric       addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
8525f757f3fSDimitry Andric               NumOut, DFSInStack);
8535f757f3fSDimitry Andric       addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
8545f757f3fSDimitry Andric               DFSInStack);
85581ad6265SDimitry Andric     }
85681ad6265SDimitry Andric     break;
85781ad6265SDimitry Andric   case CmpInst::ICMP_SLT:
8585f757f3fSDimitry Andric     if (IsKnownNonNegative(A))
859bdd1243dSDimitry Andric       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
86081ad6265SDimitry Andric     break;
86106c3fb27SDimitry Andric   case CmpInst::ICMP_SGT: {
86281ad6265SDimitry Andric     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
863bdd1243dSDimitry Andric       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
864bdd1243dSDimitry Andric               NumOut, DFSInStack);
8655f757f3fSDimitry Andric     if (IsKnownNonNegative(B))
86606c3fb27SDimitry Andric       addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
86706c3fb27SDimitry Andric 
86881ad6265SDimitry Andric     break;
86906c3fb27SDimitry Andric   }
87081ad6265SDimitry Andric   case CmpInst::ICMP_SGE:
8715f757f3fSDimitry Andric     if (IsKnownNonNegative(B))
872bdd1243dSDimitry Andric       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
87381ad6265SDimitry Andric     break;
87481ad6265SDimitry Andric   }
875e8d8bef9SDimitry Andric }
876e8d8bef9SDimitry Andric 
877fe6060f1SDimitry Andric #ifndef NDEBUG
87881ad6265SDimitry Andric 
87906c3fb27SDimitry Andric static void dumpConstraint(ArrayRef<int64_t> C,
88006c3fb27SDimitry Andric                            const DenseMap<Value *, unsigned> &Value2Index) {
88106c3fb27SDimitry Andric   ConstraintSystem CS(Value2Index);
88281ad6265SDimitry Andric   CS.addVariableRowFill(C);
88306c3fb27SDimitry Andric   CS.dump();
88481ad6265SDimitry Andric }
885fe6060f1SDimitry Andric #endif
886fe6060f1SDimitry Andric 
8875f757f3fSDimitry Andric void State::addInfoForInductions(BasicBlock &BB) {
8885f757f3fSDimitry Andric   auto *L = LI.getLoopFor(&BB);
8895f757f3fSDimitry Andric   if (!L || L->getHeader() != &BB)
8905f757f3fSDimitry Andric     return;
8915f757f3fSDimitry Andric 
8925f757f3fSDimitry Andric   Value *A;
8935f757f3fSDimitry Andric   Value *B;
8945f757f3fSDimitry Andric   CmpInst::Predicate Pred;
8955f757f3fSDimitry Andric 
8965f757f3fSDimitry Andric   if (!match(BB.getTerminator(),
8975f757f3fSDimitry Andric              m_Br(m_ICmp(Pred, m_Value(A), m_Value(B)), m_Value(), m_Value())))
8985f757f3fSDimitry Andric     return;
8995f757f3fSDimitry Andric   PHINode *PN = dyn_cast<PHINode>(A);
9005f757f3fSDimitry Andric   if (!PN) {
9015f757f3fSDimitry Andric     Pred = CmpInst::getSwappedPredicate(Pred);
9025f757f3fSDimitry Andric     std::swap(A, B);
9035f757f3fSDimitry Andric     PN = dyn_cast<PHINode>(A);
9045f757f3fSDimitry Andric   }
9055f757f3fSDimitry Andric 
9065f757f3fSDimitry Andric   if (!PN || PN->getParent() != &BB || PN->getNumIncomingValues() != 2 ||
9075f757f3fSDimitry Andric       !SE.isSCEVable(PN->getType()))
9085f757f3fSDimitry Andric     return;
9095f757f3fSDimitry Andric 
9105f757f3fSDimitry Andric   BasicBlock *InLoopSucc = nullptr;
9115f757f3fSDimitry Andric   if (Pred == CmpInst::ICMP_NE)
9125f757f3fSDimitry Andric     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(0);
9135f757f3fSDimitry Andric   else if (Pred == CmpInst::ICMP_EQ)
9145f757f3fSDimitry Andric     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(1);
9155f757f3fSDimitry Andric   else
9165f757f3fSDimitry Andric     return;
9175f757f3fSDimitry Andric 
9185f757f3fSDimitry Andric   if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB)
9195f757f3fSDimitry Andric     return;
9205f757f3fSDimitry Andric 
9215f757f3fSDimitry Andric   auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN));
9225f757f3fSDimitry Andric   BasicBlock *LoopPred = L->getLoopPredecessor();
9235f757f3fSDimitry Andric   if (!AR || AR->getLoop() != L || !LoopPred)
9245f757f3fSDimitry Andric     return;
9255f757f3fSDimitry Andric 
9265f757f3fSDimitry Andric   const SCEV *StartSCEV = AR->getStart();
9275f757f3fSDimitry Andric   Value *StartValue = nullptr;
9285f757f3fSDimitry Andric   if (auto *C = dyn_cast<SCEVConstant>(StartSCEV)) {
9295f757f3fSDimitry Andric     StartValue = C->getValue();
9305f757f3fSDimitry Andric   } else {
9315f757f3fSDimitry Andric     StartValue = PN->getIncomingValueForBlock(LoopPred);
9325f757f3fSDimitry Andric     assert(SE.getSCEV(StartValue) == StartSCEV && "inconsistent start value");
9335f757f3fSDimitry Andric   }
9345f757f3fSDimitry Andric 
9355f757f3fSDimitry Andric   DomTreeNode *DTN = DT.getNode(InLoopSucc);
9361db9f3b2SDimitry Andric   auto IncUnsigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_UGT);
9371db9f3b2SDimitry Andric   auto IncSigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_SGT);
9381db9f3b2SDimitry Andric   bool MonotonicallyIncreasingUnsigned =
9391db9f3b2SDimitry Andric       IncUnsigned && *IncUnsigned == ScalarEvolution::MonotonicallyIncreasing;
9401db9f3b2SDimitry Andric   bool MonotonicallyIncreasingSigned =
9411db9f3b2SDimitry Andric       IncSigned && *IncSigned == ScalarEvolution::MonotonicallyIncreasing;
9421db9f3b2SDimitry Andric   // If SCEV guarantees that AR does not wrap, PN >= StartValue can be added
9435f757f3fSDimitry Andric   // unconditionally.
9441db9f3b2SDimitry Andric   if (MonotonicallyIncreasingUnsigned)
9455f757f3fSDimitry Andric     WorkList.push_back(
9465f757f3fSDimitry Andric         FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGE, PN, StartValue));
9471db9f3b2SDimitry Andric   if (MonotonicallyIncreasingSigned)
9481db9f3b2SDimitry Andric     WorkList.push_back(
9491db9f3b2SDimitry Andric         FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_SGE, PN, StartValue));
9505f757f3fSDimitry Andric 
9515f757f3fSDimitry Andric   APInt StepOffset;
9525f757f3fSDimitry Andric   if (auto *C = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
9535f757f3fSDimitry Andric     StepOffset = C->getAPInt();
9545f757f3fSDimitry Andric   else
9555f757f3fSDimitry Andric     return;
9565f757f3fSDimitry Andric 
9575f757f3fSDimitry Andric   // Make sure the bound B is loop-invariant.
9585f757f3fSDimitry Andric   if (!L->isLoopInvariant(B))
9595f757f3fSDimitry Andric     return;
9605f757f3fSDimitry Andric 
9615f757f3fSDimitry Andric   // Handle negative steps.
9625f757f3fSDimitry Andric   if (StepOffset.isNegative()) {
9635f757f3fSDimitry Andric     // TODO: Extend to allow steps > -1.
9645f757f3fSDimitry Andric     if (!(-StepOffset).isOne())
9655f757f3fSDimitry Andric       return;
9665f757f3fSDimitry Andric 
9675f757f3fSDimitry Andric     // AR may wrap.
9685f757f3fSDimitry Andric     // Add StartValue >= PN conditional on B <= StartValue which guarantees that
9695f757f3fSDimitry Andric     // the loop exits before wrapping with a step of -1.
9705f757f3fSDimitry Andric     WorkList.push_back(FactOrCheck::getConditionFact(
9715f757f3fSDimitry Andric         DTN, CmpInst::ICMP_UGE, StartValue, PN,
9725f757f3fSDimitry Andric         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
9731db9f3b2SDimitry Andric     WorkList.push_back(FactOrCheck::getConditionFact(
9741db9f3b2SDimitry Andric         DTN, CmpInst::ICMP_SGE, StartValue, PN,
9751db9f3b2SDimitry Andric         ConditionTy(CmpInst::ICMP_SLE, B, StartValue)));
9765f757f3fSDimitry Andric     // Add PN > B conditional on B <= StartValue which guarantees that the loop
9775f757f3fSDimitry Andric     // exits when reaching B with a step of -1.
9785f757f3fSDimitry Andric     WorkList.push_back(FactOrCheck::getConditionFact(
9795f757f3fSDimitry Andric         DTN, CmpInst::ICMP_UGT, PN, B,
9805f757f3fSDimitry Andric         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
9811db9f3b2SDimitry Andric     WorkList.push_back(FactOrCheck::getConditionFact(
9821db9f3b2SDimitry Andric         DTN, CmpInst::ICMP_SGT, PN, B,
9831db9f3b2SDimitry Andric         ConditionTy(CmpInst::ICMP_SLE, B, StartValue)));
9845f757f3fSDimitry Andric     return;
9855f757f3fSDimitry Andric   }
9865f757f3fSDimitry Andric 
9875f757f3fSDimitry Andric   // Make sure AR either steps by 1 or that the value we compare against is a
9885f757f3fSDimitry Andric   // GEP based on the same start value and all offsets are a multiple of the
9895f757f3fSDimitry Andric   // step size, to guarantee that the induction will reach the value.
9905f757f3fSDimitry Andric   if (StepOffset.isZero() || StepOffset.isNegative())
9915f757f3fSDimitry Andric     return;
9925f757f3fSDimitry Andric 
9935f757f3fSDimitry Andric   if (!StepOffset.isOne()) {
9941db9f3b2SDimitry Andric     // Check whether B-Start is known to be a multiple of StepOffset.
9951db9f3b2SDimitry Andric     const SCEV *BMinusStart = SE.getMinusSCEV(SE.getSCEV(B), StartSCEV);
9961db9f3b2SDimitry Andric     if (isa<SCEVCouldNotCompute>(BMinusStart) ||
9971db9f3b2SDimitry Andric         !SE.getConstantMultiple(BMinusStart).urem(StepOffset).isZero())
9985f757f3fSDimitry Andric       return;
9995f757f3fSDimitry Andric   }
10005f757f3fSDimitry Andric 
10015f757f3fSDimitry Andric   // AR may wrap. Add PN >= StartValue conditional on StartValue <= B which
10025f757f3fSDimitry Andric   // guarantees that the loop exits before wrapping in combination with the
10035f757f3fSDimitry Andric   // restrictions on B and the step above.
10041db9f3b2SDimitry Andric   if (!MonotonicallyIncreasingUnsigned)
10055f757f3fSDimitry Andric     WorkList.push_back(FactOrCheck::getConditionFact(
10065f757f3fSDimitry Andric         DTN, CmpInst::ICMP_UGE, PN, StartValue,
10075f757f3fSDimitry Andric         ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
10081db9f3b2SDimitry Andric   if (!MonotonicallyIncreasingSigned)
10091db9f3b2SDimitry Andric     WorkList.push_back(FactOrCheck::getConditionFact(
10101db9f3b2SDimitry Andric         DTN, CmpInst::ICMP_SGE, PN, StartValue,
10111db9f3b2SDimitry Andric         ConditionTy(CmpInst::ICMP_SLE, StartValue, B)));
10121db9f3b2SDimitry Andric 
10135f757f3fSDimitry Andric   WorkList.push_back(FactOrCheck::getConditionFact(
10145f757f3fSDimitry Andric       DTN, CmpInst::ICMP_ULT, PN, B,
10155f757f3fSDimitry Andric       ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
10161db9f3b2SDimitry Andric   WorkList.push_back(FactOrCheck::getConditionFact(
10171db9f3b2SDimitry Andric       DTN, CmpInst::ICMP_SLT, PN, B,
10181db9f3b2SDimitry Andric       ConditionTy(CmpInst::ICMP_SLE, StartValue, B)));
10195f757f3fSDimitry Andric }
10205f757f3fSDimitry Andric 
102181ad6265SDimitry Andric void State::addInfoFor(BasicBlock &BB) {
10225f757f3fSDimitry Andric   addInfoForInductions(BB);
10235f757f3fSDimitry Andric 
1024349cc55cSDimitry Andric   // True as long as long as the current instruction is guaranteed to execute.
1025349cc55cSDimitry Andric   bool GuaranteedToExecute = true;
1026bdd1243dSDimitry Andric   // Queue conditions and assumes.
1027349cc55cSDimitry Andric   for (Instruction &I : BB) {
1028bdd1243dSDimitry Andric     if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
102906c3fb27SDimitry Andric       for (Use &U : Cmp->uses()) {
103006c3fb27SDimitry Andric         auto *UserI = getContextInstForUse(U);
103106c3fb27SDimitry Andric         auto *DTN = DT.getNode(UserI->getParent());
103206c3fb27SDimitry Andric         if (!DTN)
103306c3fb27SDimitry Andric           continue;
103406c3fb27SDimitry Andric         WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
103506c3fb27SDimitry Andric       }
1036bdd1243dSDimitry Andric       continue;
1037bdd1243dSDimitry Andric     }
1038bdd1243dSDimitry Andric 
1039647cbc5dSDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(&I);
1040647cbc5dSDimitry Andric     Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic;
1041647cbc5dSDimitry Andric     switch (ID) {
1042647cbc5dSDimitry Andric     case Intrinsic::assume: {
10435f757f3fSDimitry Andric       Value *A, *B;
10445f757f3fSDimitry Andric       CmpInst::Predicate Pred;
1045647cbc5dSDimitry Andric       if (!match(I.getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B))))
1046647cbc5dSDimitry Andric         break;
1047349cc55cSDimitry Andric       if (GuaranteedToExecute) {
1048349cc55cSDimitry Andric         // The assume is guaranteed to execute when BB is entered, hence Cond
1049349cc55cSDimitry Andric         // holds on entry to BB.
10505f757f3fSDimitry Andric         WorkList.emplace_back(FactOrCheck::getConditionFact(
10515f757f3fSDimitry Andric             DT.getNode(I.getParent()), Pred, A, B));
1052349cc55cSDimitry Andric       } else {
1053bdd1243dSDimitry Andric         WorkList.emplace_back(
10545f757f3fSDimitry Andric             FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1055349cc55cSDimitry Andric       }
1056647cbc5dSDimitry Andric       break;
1057349cc55cSDimitry Andric     }
1058647cbc5dSDimitry Andric     // Enqueue ssub_with_overflow for simplification.
1059647cbc5dSDimitry Andric     case Intrinsic::ssub_with_overflow:
1060647cbc5dSDimitry Andric       WorkList.push_back(
1061647cbc5dSDimitry Andric           FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1062647cbc5dSDimitry Andric       break;
1063647cbc5dSDimitry Andric     // Enqueue the intrinsics to add extra info.
1064647cbc5dSDimitry Andric     case Intrinsic::umin:
1065647cbc5dSDimitry Andric     case Intrinsic::umax:
1066647cbc5dSDimitry Andric     case Intrinsic::smin:
1067647cbc5dSDimitry Andric     case Intrinsic::smax:
1068*b3edf446SDimitry Andric       // TODO: Check if it is possible to instead only added the min/max facts
1069*b3edf446SDimitry Andric       // when simplifying uses of the min/max intrinsics.
1070*b3edf446SDimitry Andric       if (!isGuaranteedNotToBePoison(&I))
1071*b3edf446SDimitry Andric         break;
1072*b3edf446SDimitry Andric       [[fallthrough]];
1073*b3edf446SDimitry Andric     case Intrinsic::abs:
1074647cbc5dSDimitry Andric       WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1075647cbc5dSDimitry Andric       break;
1076647cbc5dSDimitry Andric     }
1077647cbc5dSDimitry Andric 
1078349cc55cSDimitry Andric     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1079349cc55cSDimitry Andric   }
1080349cc55cSDimitry Andric 
10815f757f3fSDimitry Andric   if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
10825f757f3fSDimitry Andric     for (auto &Case : Switch->cases()) {
10835f757f3fSDimitry Andric       BasicBlock *Succ = Case.getCaseSuccessor();
10845f757f3fSDimitry Andric       Value *V = Case.getCaseValue();
10855f757f3fSDimitry Andric       if (!canAddSuccessor(BB, Succ))
10865f757f3fSDimitry Andric         continue;
10875f757f3fSDimitry Andric       WorkList.emplace_back(FactOrCheck::getConditionFact(
10885f757f3fSDimitry Andric           DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
10895f757f3fSDimitry Andric     }
10905f757f3fSDimitry Andric     return;
10915f757f3fSDimitry Andric   }
10925f757f3fSDimitry Andric 
1093e8d8bef9SDimitry Andric   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
1094e8d8bef9SDimitry Andric   if (!Br || !Br->isConditional())
109581ad6265SDimitry Andric     return;
1096e8d8bef9SDimitry Andric 
1097bdd1243dSDimitry Andric   Value *Cond = Br->getCondition();
1098e8d8bef9SDimitry Andric 
1099bdd1243dSDimitry Andric   // If the condition is a chain of ORs/AND and the successor only has the
1100bdd1243dSDimitry Andric   // current block as predecessor, queue conditions for the successor.
1101bdd1243dSDimitry Andric   Value *Op0, *Op1;
1102bdd1243dSDimitry Andric   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1103bdd1243dSDimitry Andric       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1104bdd1243dSDimitry Andric     bool IsOr = match(Cond, m_LogicalOr());
1105bdd1243dSDimitry Andric     bool IsAnd = match(Cond, m_LogicalAnd());
1106bdd1243dSDimitry Andric     // If there's a select that matches both AND and OR, we need to commit to
1107bdd1243dSDimitry Andric     // one of the options. Arbitrarily pick OR.
1108bdd1243dSDimitry Andric     if (IsOr && IsAnd)
1109bdd1243dSDimitry Andric       IsAnd = false;
1110bdd1243dSDimitry Andric 
1111bdd1243dSDimitry Andric     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1112bdd1243dSDimitry Andric     if (canAddSuccessor(BB, Successor)) {
1113bdd1243dSDimitry Andric       SmallVector<Value *> CondWorkList;
1114bdd1243dSDimitry Andric       SmallPtrSet<Value *, 8> SeenCond;
1115bdd1243dSDimitry Andric       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1116bdd1243dSDimitry Andric         if (SeenCond.insert(V).second)
1117bdd1243dSDimitry Andric           CondWorkList.push_back(V);
1118bdd1243dSDimitry Andric       };
1119bdd1243dSDimitry Andric       QueueValue(Op1);
1120bdd1243dSDimitry Andric       QueueValue(Op0);
1121bdd1243dSDimitry Andric       while (!CondWorkList.empty()) {
1122bdd1243dSDimitry Andric         Value *Cur = CondWorkList.pop_back_val();
1123bdd1243dSDimitry Andric         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
11245f757f3fSDimitry Andric           WorkList.emplace_back(FactOrCheck::getConditionFact(
11255f757f3fSDimitry Andric               DT.getNode(Successor),
11265f757f3fSDimitry Andric               IsOr ? CmpInst::getInversePredicate(Cmp->getPredicate())
11275f757f3fSDimitry Andric                    : Cmp->getPredicate(),
11285f757f3fSDimitry Andric               Cmp->getOperand(0), Cmp->getOperand(1)));
1129bdd1243dSDimitry Andric           continue;
1130bdd1243dSDimitry Andric         }
1131bdd1243dSDimitry Andric         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1132bdd1243dSDimitry Andric           QueueValue(Op1);
1133bdd1243dSDimitry Andric           QueueValue(Op0);
1134bdd1243dSDimitry Andric           continue;
1135bdd1243dSDimitry Andric         }
1136bdd1243dSDimitry Andric         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1137bdd1243dSDimitry Andric           QueueValue(Op1);
1138bdd1243dSDimitry Andric           QueueValue(Op0);
1139bdd1243dSDimitry Andric           continue;
1140bdd1243dSDimitry Andric         }
1141bdd1243dSDimitry Andric       }
1142e8d8bef9SDimitry Andric     }
114381ad6265SDimitry Andric     return;
1144e8d8bef9SDimitry Andric   }
1145e8d8bef9SDimitry Andric 
114681ad6265SDimitry Andric   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
1147e8d8bef9SDimitry Andric   if (!CmpI)
114881ad6265SDimitry Andric     return;
114981ad6265SDimitry Andric   if (canAddSuccessor(BB, Br->getSuccessor(0)))
11505f757f3fSDimitry Andric     WorkList.emplace_back(FactOrCheck::getConditionFact(
11515f757f3fSDimitry Andric         DT.getNode(Br->getSuccessor(0)), CmpI->getPredicate(),
11525f757f3fSDimitry Andric         CmpI->getOperand(0), CmpI->getOperand(1)));
115381ad6265SDimitry Andric   if (canAddSuccessor(BB, Br->getSuccessor(1)))
11545f757f3fSDimitry Andric     WorkList.emplace_back(FactOrCheck::getConditionFact(
11555f757f3fSDimitry Andric         DT.getNode(Br->getSuccessor(1)),
11565f757f3fSDimitry Andric         CmpInst::getInversePredicate(CmpI->getPredicate()), CmpI->getOperand(0),
11575f757f3fSDimitry Andric         CmpI->getOperand(1)));
1158bdd1243dSDimitry Andric }
1159bdd1243dSDimitry Andric 
11605f757f3fSDimitry Andric #ifndef NDEBUG
11615f757f3fSDimitry Andric static void dumpUnpackedICmp(raw_ostream &OS, ICmpInst::Predicate Pred,
11625f757f3fSDimitry Andric                              Value *LHS, Value *RHS) {
11635f757f3fSDimitry Andric   OS << "icmp " << Pred << ' ';
11645f757f3fSDimitry Andric   LHS->printAsOperand(OS, /*PrintType=*/true);
11655f757f3fSDimitry Andric   OS << ", ";
11665f757f3fSDimitry Andric   RHS->printAsOperand(OS, /*PrintType=*/false);
11675f757f3fSDimitry Andric }
11685f757f3fSDimitry Andric #endif
11695f757f3fSDimitry Andric 
117006c3fb27SDimitry Andric namespace {
117106c3fb27SDimitry Andric /// Helper to keep track of a condition and if it should be treated as negated
117206c3fb27SDimitry Andric /// for reproducer construction.
117306c3fb27SDimitry Andric /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
117406c3fb27SDimitry Andric /// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
117506c3fb27SDimitry Andric struct ReproducerEntry {
117606c3fb27SDimitry Andric   ICmpInst::Predicate Pred;
117706c3fb27SDimitry Andric   Value *LHS;
117806c3fb27SDimitry Andric   Value *RHS;
117906c3fb27SDimitry Andric 
118006c3fb27SDimitry Andric   ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
118106c3fb27SDimitry Andric       : Pred(Pred), LHS(LHS), RHS(RHS) {}
118206c3fb27SDimitry Andric };
118306c3fb27SDimitry Andric } // namespace
118406c3fb27SDimitry Andric 
118506c3fb27SDimitry Andric /// Helper function to generate a reproducer function for simplifying \p Cond.
118606c3fb27SDimitry Andric /// The reproducer function contains a series of @llvm.assume calls, one for
118706c3fb27SDimitry Andric /// each condition in \p Stack. For each condition, the operand instruction are
118806c3fb27SDimitry Andric /// cloned until we reach operands that have an entry in \p Value2Index. Those
118906c3fb27SDimitry Andric /// will then be added as function arguments. \p DT is used to order cloned
119006c3fb27SDimitry Andric /// instructions. The reproducer function will get added to \p M, if it is
119106c3fb27SDimitry Andric /// non-null. Otherwise no reproducer function is generated.
119206c3fb27SDimitry Andric static void generateReproducer(CmpInst *Cond, Module *M,
119306c3fb27SDimitry Andric                                ArrayRef<ReproducerEntry> Stack,
119406c3fb27SDimitry Andric                                ConstraintInfo &Info, DominatorTree &DT) {
119506c3fb27SDimitry Andric   if (!M)
119606c3fb27SDimitry Andric     return;
119706c3fb27SDimitry Andric 
119806c3fb27SDimitry Andric   LLVMContext &Ctx = Cond->getContext();
119906c3fb27SDimitry Andric 
120006c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
120106c3fb27SDimitry Andric 
120206c3fb27SDimitry Andric   ValueToValueMapTy Old2New;
120306c3fb27SDimitry Andric   SmallVector<Value *> Args;
120406c3fb27SDimitry Andric   SmallPtrSet<Value *, 8> Seen;
120506c3fb27SDimitry Andric   // Traverse Cond and its operands recursively until we reach a value that's in
120606c3fb27SDimitry Andric   // Value2Index or not an instruction, or not a operation that
120706c3fb27SDimitry Andric   // ConstraintElimination can decompose. Such values will be considered as
120806c3fb27SDimitry Andric   // external inputs to the reproducer, they are collected and added as function
120906c3fb27SDimitry Andric   // arguments later.
121006c3fb27SDimitry Andric   auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
121106c3fb27SDimitry Andric     auto &Value2Index = Info.getValue2Index(IsSigned);
121206c3fb27SDimitry Andric     SmallVector<Value *, 4> WorkList(Ops);
121306c3fb27SDimitry Andric     while (!WorkList.empty()) {
121406c3fb27SDimitry Andric       Value *V = WorkList.pop_back_val();
121506c3fb27SDimitry Andric       if (!Seen.insert(V).second)
121606c3fb27SDimitry Andric         continue;
121706c3fb27SDimitry Andric       if (Old2New.find(V) != Old2New.end())
121806c3fb27SDimitry Andric         continue;
121906c3fb27SDimitry Andric       if (isa<Constant>(V))
122006c3fb27SDimitry Andric         continue;
122106c3fb27SDimitry Andric 
122206c3fb27SDimitry Andric       auto *I = dyn_cast<Instruction>(V);
122306c3fb27SDimitry Andric       if (Value2Index.contains(V) || !I ||
122406c3fb27SDimitry Andric           !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
122506c3fb27SDimitry Andric         Old2New[V] = V;
122606c3fb27SDimitry Andric         Args.push_back(V);
122706c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "  found external input " << *V << "\n");
122806c3fb27SDimitry Andric       } else {
122906c3fb27SDimitry Andric         append_range(WorkList, I->operands());
123006c3fb27SDimitry Andric       }
123106c3fb27SDimitry Andric     }
123206c3fb27SDimitry Andric   };
123306c3fb27SDimitry Andric 
123406c3fb27SDimitry Andric   for (auto &Entry : Stack)
123506c3fb27SDimitry Andric     if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
123606c3fb27SDimitry Andric       CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
123706c3fb27SDimitry Andric   CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate()));
123806c3fb27SDimitry Andric 
123906c3fb27SDimitry Andric   SmallVector<Type *> ParamTys;
124006c3fb27SDimitry Andric   for (auto *P : Args)
124106c3fb27SDimitry Andric     ParamTys.push_back(P->getType());
124206c3fb27SDimitry Andric 
124306c3fb27SDimitry Andric   FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
124406c3fb27SDimitry Andric                                         /*isVarArg=*/false);
124506c3fb27SDimitry Andric   Function *F = Function::Create(FTy, Function::ExternalLinkage,
124606c3fb27SDimitry Andric                                  Cond->getModule()->getName() +
124706c3fb27SDimitry Andric                                      Cond->getFunction()->getName() + "repro",
124806c3fb27SDimitry Andric                                  M);
124906c3fb27SDimitry Andric   // Add arguments to the reproducer function for each external value collected.
125006c3fb27SDimitry Andric   for (unsigned I = 0; I < Args.size(); ++I) {
125106c3fb27SDimitry Andric     F->getArg(I)->setName(Args[I]->getName());
125206c3fb27SDimitry Andric     Old2New[Args[I]] = F->getArg(I);
125306c3fb27SDimitry Andric   }
125406c3fb27SDimitry Andric 
125506c3fb27SDimitry Andric   BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
125606c3fb27SDimitry Andric   IRBuilder<> Builder(Entry);
125706c3fb27SDimitry Andric   Builder.CreateRet(Builder.getTrue());
125806c3fb27SDimitry Andric   Builder.SetInsertPoint(Entry->getTerminator());
125906c3fb27SDimitry Andric 
126006c3fb27SDimitry Andric   // Clone instructions in \p Ops and their operands recursively until reaching
126106c3fb27SDimitry Andric   // an value in Value2Index (external input to the reproducer). Update Old2New
126206c3fb27SDimitry Andric   // mapping for the original and cloned instructions. Sort instructions to
126306c3fb27SDimitry Andric   // clone by dominance, then insert the cloned instructions in the function.
126406c3fb27SDimitry Andric   auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
126506c3fb27SDimitry Andric     SmallVector<Value *, 4> WorkList(Ops);
126606c3fb27SDimitry Andric     SmallVector<Instruction *> ToClone;
126706c3fb27SDimitry Andric     auto &Value2Index = Info.getValue2Index(IsSigned);
126806c3fb27SDimitry Andric     while (!WorkList.empty()) {
126906c3fb27SDimitry Andric       Value *V = WorkList.pop_back_val();
127006c3fb27SDimitry Andric       if (Old2New.find(V) != Old2New.end())
127106c3fb27SDimitry Andric         continue;
127206c3fb27SDimitry Andric 
127306c3fb27SDimitry Andric       auto *I = dyn_cast<Instruction>(V);
127406c3fb27SDimitry Andric       if (!Value2Index.contains(V) && I) {
127506c3fb27SDimitry Andric         Old2New[V] = nullptr;
127606c3fb27SDimitry Andric         ToClone.push_back(I);
127706c3fb27SDimitry Andric         append_range(WorkList, I->operands());
127806c3fb27SDimitry Andric       }
127906c3fb27SDimitry Andric     }
128006c3fb27SDimitry Andric 
128106c3fb27SDimitry Andric     sort(ToClone,
128206c3fb27SDimitry Andric          [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
128306c3fb27SDimitry Andric     for (Instruction *I : ToClone) {
128406c3fb27SDimitry Andric       Instruction *Cloned = I->clone();
128506c3fb27SDimitry Andric       Old2New[I] = Cloned;
128606c3fb27SDimitry Andric       Old2New[I]->setName(I->getName());
128706c3fb27SDimitry Andric       Cloned->insertBefore(&*Builder.GetInsertPoint());
128806c3fb27SDimitry Andric       Cloned->dropUnknownNonDebugMetadata();
128906c3fb27SDimitry Andric       Cloned->setDebugLoc({});
129006c3fb27SDimitry Andric     }
129106c3fb27SDimitry Andric   };
129206c3fb27SDimitry Andric 
129306c3fb27SDimitry Andric   // Materialize the assumptions for the reproducer using the entries in Stack.
129406c3fb27SDimitry Andric   // That is, first clone the operands of the condition recursively until we
129506c3fb27SDimitry Andric   // reach an external input to the reproducer and add them to the reproducer
129606c3fb27SDimitry Andric   // function. Then add an ICmp for the condition (with the inverse predicate if
129706c3fb27SDimitry Andric   // the entry is negated) and an assert using the ICmp.
129806c3fb27SDimitry Andric   for (auto &Entry : Stack) {
129906c3fb27SDimitry Andric     if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
130006c3fb27SDimitry Andric       continue;
130106c3fb27SDimitry Andric 
13025f757f3fSDimitry Andric     LLVM_DEBUG(dbgs() << "  Materializing assumption ";
13035f757f3fSDimitry Andric                dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS);
13045f757f3fSDimitry Andric                dbgs() << "\n");
130506c3fb27SDimitry Andric     CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
130606c3fb27SDimitry Andric 
130706c3fb27SDimitry Andric     auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
130806c3fb27SDimitry Andric     Builder.CreateAssumption(Cmp);
130906c3fb27SDimitry Andric   }
131006c3fb27SDimitry Andric 
131106c3fb27SDimitry Andric   // Finally, clone the condition to reproduce and remap instruction operands in
131206c3fb27SDimitry Andric   // the reproducer using Old2New.
131306c3fb27SDimitry Andric   CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
131406c3fb27SDimitry Andric   Entry->getTerminator()->setOperand(0, Cond);
131506c3fb27SDimitry Andric   remapInstructionsInBlocks({Entry}, Old2New);
131606c3fb27SDimitry Andric 
131706c3fb27SDimitry Andric   assert(!verifyFunction(*F, &dbgs()));
131806c3fb27SDimitry Andric }
131906c3fb27SDimitry Andric 
13205f757f3fSDimitry Andric static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A,
13215f757f3fSDimitry Andric                                           Value *B, Instruction *CheckInst,
13227a6dacacSDimitry Andric                                           ConstraintInfo &Info) {
13235f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n");
1324bdd1243dSDimitry Andric 
1325bdd1243dSDimitry Andric   auto R = Info.getConstraintForSolving(Pred, A, B);
1326bdd1243dSDimitry Andric   if (R.empty() || !R.isValid(Info)){
1327bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
132806c3fb27SDimitry Andric     return std::nullopt;
1329bdd1243dSDimitry Andric   }
1330bdd1243dSDimitry Andric 
1331bdd1243dSDimitry Andric   auto &CSToUse = Info.getCS(R.IsSigned);
1332bdd1243dSDimitry Andric 
1333bdd1243dSDimitry Andric   // If there was extra information collected during decomposition, apply
1334bdd1243dSDimitry Andric   // it now and remove it immediately once we are done with reasoning
1335bdd1243dSDimitry Andric   // about the constraint.
1336bdd1243dSDimitry Andric   for (auto &Row : R.ExtraInfo)
1337bdd1243dSDimitry Andric     CSToUse.addVariableRow(Row);
1338bdd1243dSDimitry Andric   auto InfoRestorer = make_scope_exit([&]() {
1339bdd1243dSDimitry Andric     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
1340bdd1243dSDimitry Andric       CSToUse.popLastConstraint();
1341bdd1243dSDimitry Andric   });
1342bdd1243dSDimitry Andric 
134306c3fb27SDimitry Andric   if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1344bdd1243dSDimitry Andric     if (!DebugCounter::shouldExecute(EliminatedCounter))
134506c3fb27SDimitry Andric       return std::nullopt;
1346bdd1243dSDimitry Andric 
1347bdd1243dSDimitry Andric     LLVM_DEBUG({
13485f757f3fSDimitry Andric       dbgs() << "Condition ";
13495f757f3fSDimitry Andric       dumpUnpackedICmp(
13505f757f3fSDimitry Andric           dbgs(), *ImpliedCondition ? Pred : CmpInst::getInversePredicate(Pred),
13515f757f3fSDimitry Andric           A, B);
135206c3fb27SDimitry Andric       dbgs() << " implied by dominating constraints\n";
135306c3fb27SDimitry Andric       CSToUse.dump();
1354bdd1243dSDimitry Andric     });
135506c3fb27SDimitry Andric     return ImpliedCondition;
135606c3fb27SDimitry Andric   }
135706c3fb27SDimitry Andric 
135806c3fb27SDimitry Andric   return std::nullopt;
135906c3fb27SDimitry Andric }
136006c3fb27SDimitry Andric 
136106c3fb27SDimitry Andric static bool checkAndReplaceCondition(
136206c3fb27SDimitry Andric     CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
136306c3fb27SDimitry Andric     Instruction *ContextInst, Module *ReproducerModule,
13645f757f3fSDimitry Andric     ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
13655f757f3fSDimitry Andric     SmallVectorImpl<Instruction *> &ToRemove) {
136606c3fb27SDimitry Andric   auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) {
136706c3fb27SDimitry Andric     generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
136806c3fb27SDimitry Andric     Constant *ConstantC = ConstantInt::getBool(
136906c3fb27SDimitry Andric         CmpInst::makeCmpResultType(Cmp->getType()), IsTrue);
137006c3fb27SDimitry Andric     Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut,
137106c3fb27SDimitry Andric                                        ContextInst](Use &U) {
137206c3fb27SDimitry Andric       auto *UserI = getContextInstForUse(U);
137306c3fb27SDimitry Andric       auto *DTN = DT.getNode(UserI->getParent());
137406c3fb27SDimitry Andric       if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
137506c3fb27SDimitry Andric         return false;
137606c3fb27SDimitry Andric       if (UserI->getParent() == ContextInst->getParent() &&
137706c3fb27SDimitry Andric           UserI->comesBefore(ContextInst))
137806c3fb27SDimitry Andric         return false;
137906c3fb27SDimitry Andric 
1380bdd1243dSDimitry Andric       // Conditions in an assume trivially simplify to true. Skip uses
1381bdd1243dSDimitry Andric       // in assume calls to not destroy the available information.
1382bdd1243dSDimitry Andric       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1383bdd1243dSDimitry Andric       return !II || II->getIntrinsicID() != Intrinsic::assume;
1384bdd1243dSDimitry Andric     });
1385bdd1243dSDimitry Andric     NumCondsRemoved++;
13865f757f3fSDimitry Andric     if (Cmp->use_empty())
13875f757f3fSDimitry Andric       ToRemove.push_back(Cmp);
138806c3fb27SDimitry Andric     return true;
138906c3fb27SDimitry Andric   };
139006c3fb27SDimitry Andric 
13917a6dacacSDimitry Andric   if (auto ImpliedCondition =
13927a6dacacSDimitry Andric           checkCondition(Cmp->getPredicate(), Cmp->getOperand(0),
13937a6dacacSDimitry Andric                          Cmp->getOperand(1), Cmp, Info))
139406c3fb27SDimitry Andric     return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
139506c3fb27SDimitry Andric   return false;
1396bdd1243dSDimitry Andric }
139706c3fb27SDimitry Andric 
139806c3fb27SDimitry Andric static void
139906c3fb27SDimitry Andric removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
140006c3fb27SDimitry Andric                      Module *ReproducerModule,
140106c3fb27SDimitry Andric                      SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
140206c3fb27SDimitry Andric                      SmallVectorImpl<StackEntry> &DFSInStack) {
140306c3fb27SDimitry Andric   Info.popLastConstraint(E.IsSigned);
140406c3fb27SDimitry Andric   // Remove variables in the system that went out of scope.
140506c3fb27SDimitry Andric   auto &Mapping = Info.getValue2Index(E.IsSigned);
140606c3fb27SDimitry Andric   for (Value *V : E.ValuesToRelease)
140706c3fb27SDimitry Andric     Mapping.erase(V);
140806c3fb27SDimitry Andric   Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
140906c3fb27SDimitry Andric   DFSInStack.pop_back();
141006c3fb27SDimitry Andric   if (ReproducerModule)
141106c3fb27SDimitry Andric     ReproducerCondStack.pop_back();
141206c3fb27SDimitry Andric }
141306c3fb27SDimitry Andric 
1414cb14a3feSDimitry Andric /// Check if either the first condition of an AND or OR is implied by the
1415cb14a3feSDimitry Andric /// (negated in case of OR) second condition or vice versa.
1416cb14a3feSDimitry Andric static bool checkOrAndOpImpliedByOther(
141706c3fb27SDimitry Andric     FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
141806c3fb27SDimitry Andric     SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
141906c3fb27SDimitry Andric     SmallVectorImpl<StackEntry> &DFSInStack) {
14205f757f3fSDimitry Andric 
142106c3fb27SDimitry Andric   CmpInst::Predicate Pred;
142206c3fb27SDimitry Andric   Value *A, *B;
1423cb14a3feSDimitry Andric   Instruction *JoinOp = CB.getContextInst();
1424cb14a3feSDimitry Andric   CmpInst *CmpToCheck = cast<CmpInst>(CB.getInstructionToSimplify());
1425cb14a3feSDimitry Andric   unsigned OtherOpIdx = JoinOp->getOperand(0) == CmpToCheck ? 1 : 0;
1426cb14a3feSDimitry Andric 
1427cb14a3feSDimitry Andric   // Don't try to simplify the first condition of a select by the second, as
1428cb14a3feSDimitry Andric   // this may make the select more poisonous than the original one.
1429cb14a3feSDimitry Andric   // TODO: check if the first operand may be poison.
1430cb14a3feSDimitry Andric   if (OtherOpIdx != 0 && isa<SelectInst>(JoinOp))
1431bdd1243dSDimitry Andric     return false;
1432bdd1243dSDimitry Andric 
1433cb14a3feSDimitry Andric   if (!match(JoinOp->getOperand(OtherOpIdx),
1434cb14a3feSDimitry Andric              m_ICmp(Pred, m_Value(A), m_Value(B))))
1435cb14a3feSDimitry Andric     return false;
1436cb14a3feSDimitry Andric 
1437cb14a3feSDimitry Andric   // For OR, check if the negated condition implies CmpToCheck.
1438cb14a3feSDimitry Andric   bool IsOr = match(JoinOp, m_LogicalOr());
1439cb14a3feSDimitry Andric   if (IsOr)
1440cb14a3feSDimitry Andric     Pred = CmpInst::getInversePredicate(Pred);
1441cb14a3feSDimitry Andric 
144206c3fb27SDimitry Andric   // Optimistically add fact from first condition.
144306c3fb27SDimitry Andric   unsigned OldSize = DFSInStack.size();
144406c3fb27SDimitry Andric   Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
144506c3fb27SDimitry Andric   if (OldSize == DFSInStack.size())
144606c3fb27SDimitry Andric     return false;
144706c3fb27SDimitry Andric 
144806c3fb27SDimitry Andric   bool Changed = false;
144906c3fb27SDimitry Andric   // Check if the second condition can be simplified now.
1450cb14a3feSDimitry Andric   if (auto ImpliedCondition =
1451cb14a3feSDimitry Andric           checkCondition(CmpToCheck->getPredicate(), CmpToCheck->getOperand(0),
14527a6dacacSDimitry Andric                          CmpToCheck->getOperand(1), CmpToCheck, Info)) {
1453cb14a3feSDimitry Andric     if (IsOr && isa<SelectInst>(JoinOp)) {
1454cb14a3feSDimitry Andric       JoinOp->setOperand(
1455cb14a3feSDimitry Andric           OtherOpIdx == 0 ? 2 : 0,
1456cb14a3feSDimitry Andric           ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1457cb14a3feSDimitry Andric     } else
1458cb14a3feSDimitry Andric       JoinOp->setOperand(
1459cb14a3feSDimitry Andric           1 - OtherOpIdx,
1460cb14a3feSDimitry Andric           ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1461cb14a3feSDimitry Andric 
1462bdd1243dSDimitry Andric     Changed = true;
1463bdd1243dSDimitry Andric   }
146406c3fb27SDimitry Andric 
146506c3fb27SDimitry Andric   // Remove entries again.
146606c3fb27SDimitry Andric   while (OldSize < DFSInStack.size()) {
146706c3fb27SDimitry Andric     StackEntry E = DFSInStack.back();
146806c3fb27SDimitry Andric     removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
146906c3fb27SDimitry Andric                          DFSInStack);
147006c3fb27SDimitry Andric   }
1471bdd1243dSDimitry Andric   return Changed;
1472e8d8bef9SDimitry Andric }
1473e8d8bef9SDimitry Andric 
147481ad6265SDimitry Andric void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
1475bdd1243dSDimitry Andric                              unsigned NumIn, unsigned NumOut,
147681ad6265SDimitry Andric                              SmallVectorImpl<StackEntry> &DFSInStack) {
147781ad6265SDimitry Andric   // If the constraint has a pre-condition, skip the constraint if it does not
147881ad6265SDimitry Andric   // hold.
1479bdd1243dSDimitry Andric   SmallVector<Value *> NewVariables;
1480bdd1243dSDimitry Andric   auto R = getConstraint(Pred, A, B, NewVariables);
148106c3fb27SDimitry Andric 
148206c3fb27SDimitry Andric   // TODO: Support non-equality for facts as well.
148306c3fb27SDimitry Andric   if (!R.isValid(*this) || R.isNe())
148481ad6265SDimitry Andric     return;
148581ad6265SDimitry Andric 
14865f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B);
14875f757f3fSDimitry Andric              dbgs() << "'\n");
148881ad6265SDimitry Andric   bool Added = false;
148981ad6265SDimitry Andric   auto &CSToUse = getCS(R.IsSigned);
149081ad6265SDimitry Andric   if (R.Coefficients.empty())
149181ad6265SDimitry Andric     return;
149281ad6265SDimitry Andric 
149381ad6265SDimitry Andric   Added |= CSToUse.addVariableRowFill(R.Coefficients);
149481ad6265SDimitry Andric 
1495bdd1243dSDimitry Andric   // If R has been added to the system, add the new variables and queue it for
1496bdd1243dSDimitry Andric   // removal once it goes out-of-scope.
149781ad6265SDimitry Andric   if (Added) {
149881ad6265SDimitry Andric     SmallVector<Value *, 2> ValuesToRelease;
1499bdd1243dSDimitry Andric     auto &Value2Index = getValue2Index(R.IsSigned);
1500bdd1243dSDimitry Andric     for (Value *V : NewVariables) {
1501bdd1243dSDimitry Andric       Value2Index.insert({V, Value2Index.size() + 1});
1502bdd1243dSDimitry Andric       ValuesToRelease.push_back(V);
150381ad6265SDimitry Andric     }
150481ad6265SDimitry Andric 
150581ad6265SDimitry Andric     LLVM_DEBUG({
150681ad6265SDimitry Andric       dbgs() << "  constraint: ";
150706c3fb27SDimitry Andric       dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1508bdd1243dSDimitry Andric       dbgs() << "\n";
150981ad6265SDimitry Andric     });
151081ad6265SDimitry Andric 
1511bdd1243dSDimitry Andric     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1512bdd1243dSDimitry Andric                             std::move(ValuesToRelease));
151381ad6265SDimitry Andric 
1514cb14a3feSDimitry Andric     if (!R.IsSigned) {
1515cb14a3feSDimitry Andric       for (Value *V : NewVariables) {
1516cb14a3feSDimitry Andric         ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
1517cb14a3feSDimitry Andric                             false, false, false);
1518cb14a3feSDimitry Andric         VarPos.Coefficients[Value2Index[V]] = -1;
1519cb14a3feSDimitry Andric         CSToUse.addVariableRow(VarPos.Coefficients);
1520cb14a3feSDimitry Andric         DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1521cb14a3feSDimitry Andric                                 SmallVector<Value *, 2>());
1522cb14a3feSDimitry Andric       }
1523cb14a3feSDimitry Andric     }
1524cb14a3feSDimitry Andric 
152506c3fb27SDimitry Andric     if (R.isEq()) {
152681ad6265SDimitry Andric       // Also add the inverted constraint for equality constraints.
152781ad6265SDimitry Andric       for (auto &Coeff : R.Coefficients)
152881ad6265SDimitry Andric         Coeff *= -1;
152981ad6265SDimitry Andric       CSToUse.addVariableRowFill(R.Coefficients);
153081ad6265SDimitry Andric 
1531bdd1243dSDimitry Andric       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
153281ad6265SDimitry Andric                               SmallVector<Value *, 2>());
153381ad6265SDimitry Andric     }
153481ad6265SDimitry Andric   }
153581ad6265SDimitry Andric }
153681ad6265SDimitry Andric 
1537bdd1243dSDimitry Andric static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
1538bdd1243dSDimitry Andric                                    SmallVectorImpl<Instruction *> &ToRemove) {
1539bdd1243dSDimitry Andric   bool Changed = false;
1540bdd1243dSDimitry Andric   IRBuilder<> Builder(II->getParent(), II->getIterator());
1541bdd1243dSDimitry Andric   Value *Sub = nullptr;
1542bdd1243dSDimitry Andric   for (User *U : make_early_inc_range(II->users())) {
1543bdd1243dSDimitry Andric     if (match(U, m_ExtractValue<0>(m_Value()))) {
1544bdd1243dSDimitry Andric       if (!Sub)
1545bdd1243dSDimitry Andric         Sub = Builder.CreateSub(A, B);
1546bdd1243dSDimitry Andric       U->replaceAllUsesWith(Sub);
1547bdd1243dSDimitry Andric       Changed = true;
1548bdd1243dSDimitry Andric     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1549bdd1243dSDimitry Andric       U->replaceAllUsesWith(Builder.getFalse());
1550bdd1243dSDimitry Andric       Changed = true;
1551bdd1243dSDimitry Andric     } else
1552bdd1243dSDimitry Andric       continue;
1553bdd1243dSDimitry Andric 
1554bdd1243dSDimitry Andric     if (U->use_empty()) {
1555bdd1243dSDimitry Andric       auto *I = cast<Instruction>(U);
1556bdd1243dSDimitry Andric       ToRemove.push_back(I);
1557bdd1243dSDimitry Andric       I->setOperand(0, PoisonValue::get(II->getType()));
1558bdd1243dSDimitry Andric       Changed = true;
1559bdd1243dSDimitry Andric     }
1560bdd1243dSDimitry Andric   }
1561bdd1243dSDimitry Andric 
1562bdd1243dSDimitry Andric   if (II->use_empty()) {
1563bdd1243dSDimitry Andric     II->eraseFromParent();
1564bdd1243dSDimitry Andric     Changed = true;
1565bdd1243dSDimitry Andric   }
1566bdd1243dSDimitry Andric   return Changed;
1567bdd1243dSDimitry Andric }
1568bdd1243dSDimitry Andric 
1569bdd1243dSDimitry Andric static bool
157081ad6265SDimitry Andric tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
157181ad6265SDimitry Andric                           SmallVectorImpl<Instruction *> &ToRemove) {
157281ad6265SDimitry Andric   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
157381ad6265SDimitry Andric                               ConstraintInfo &Info) {
1574bdd1243dSDimitry Andric     auto R = Info.getConstraintForSolving(Pred, A, B);
1575bdd1243dSDimitry Andric     if (R.size() < 2 || !R.isValid(Info))
157681ad6265SDimitry Andric       return false;
157781ad6265SDimitry Andric 
1578bdd1243dSDimitry Andric     auto &CSToUse = Info.getCS(R.IsSigned);
157981ad6265SDimitry Andric     return CSToUse.isConditionImplied(R.Coefficients);
158081ad6265SDimitry Andric   };
158181ad6265SDimitry Andric 
1582bdd1243dSDimitry Andric   bool Changed = false;
158381ad6265SDimitry Andric   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
158481ad6265SDimitry Andric     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
158581ad6265SDimitry Andric     // can be simplified to a regular sub.
158681ad6265SDimitry Andric     Value *A = II->getArgOperand(0);
158781ad6265SDimitry Andric     Value *B = II->getArgOperand(1);
158881ad6265SDimitry Andric     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
158981ad6265SDimitry Andric         !DoesConditionHold(CmpInst::ICMP_SGE, B,
159081ad6265SDimitry Andric                            ConstantInt::get(A->getType(), 0), Info))
1591bdd1243dSDimitry Andric       return false;
1592bdd1243dSDimitry Andric     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
159381ad6265SDimitry Andric   }
1594bdd1243dSDimitry Andric   return Changed;
159581ad6265SDimitry Andric }
159681ad6265SDimitry Andric 
15975f757f3fSDimitry Andric static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI,
15985f757f3fSDimitry Andric                                  ScalarEvolution &SE,
159906c3fb27SDimitry Andric                                  OptimizationRemarkEmitter &ORE) {
160081ad6265SDimitry Andric   bool Changed = false;
160181ad6265SDimitry Andric   DT.updateDFSNumbers();
160206c3fb27SDimitry Andric   SmallVector<Value *> FunctionArgs;
160306c3fb27SDimitry Andric   for (Value &Arg : F.args())
160406c3fb27SDimitry Andric     FunctionArgs.push_back(&Arg);
160506c3fb27SDimitry Andric   ConstraintInfo Info(F.getParent()->getDataLayout(), FunctionArgs);
16065f757f3fSDimitry Andric   State S(DT, LI, SE);
160706c3fb27SDimitry Andric   std::unique_ptr<Module> ReproducerModule(
160806c3fb27SDimitry Andric       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
160981ad6265SDimitry Andric 
161081ad6265SDimitry Andric   // First, collect conditions implied by branches and blocks with their
161181ad6265SDimitry Andric   // Dominator DFS in and out numbers.
161281ad6265SDimitry Andric   for (BasicBlock &BB : F) {
161381ad6265SDimitry Andric     if (!DT.getNode(&BB))
161481ad6265SDimitry Andric       continue;
161581ad6265SDimitry Andric     S.addInfoFor(BB);
161681ad6265SDimitry Andric   }
161781ad6265SDimitry Andric 
1618bdd1243dSDimitry Andric   // Next, sort worklist by dominance, so that dominating conditions to check
1619bdd1243dSDimitry Andric   // and facts come before conditions and facts dominated by them. If a
1620bdd1243dSDimitry Andric   // condition to check and a fact have the same numbers, conditional facts come
1621bdd1243dSDimitry Andric   // first. Assume facts and checks are ordered according to their relative
1622bdd1243dSDimitry Andric   // order in the containing basic block. Also make sure conditions with
1623bdd1243dSDimitry Andric   // constant operands come before conditions without constant operands. This
1624bdd1243dSDimitry Andric   // increases the effectiveness of the current signed <-> unsigned fact
1625bdd1243dSDimitry Andric   // transfer logic.
1626bdd1243dSDimitry Andric   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1627bdd1243dSDimitry Andric     auto HasNoConstOp = [](const FactOrCheck &B) {
16285f757f3fSDimitry Andric       Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
16295f757f3fSDimitry Andric       Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
16305f757f3fSDimitry Andric       return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
1631bdd1243dSDimitry Andric     };
1632bdd1243dSDimitry Andric     // If both entries have the same In numbers, conditional facts come first.
1633bdd1243dSDimitry Andric     // Otherwise use the relative order in the basic block.
1634bdd1243dSDimitry Andric     if (A.NumIn == B.NumIn) {
1635bdd1243dSDimitry Andric       if (A.isConditionFact() && B.isConditionFact()) {
1636bdd1243dSDimitry Andric         bool NoConstOpA = HasNoConstOp(A);
1637bdd1243dSDimitry Andric         bool NoConstOpB = HasNoConstOp(B);
1638bdd1243dSDimitry Andric         return NoConstOpA < NoConstOpB;
1639bdd1243dSDimitry Andric       }
1640bdd1243dSDimitry Andric       if (A.isConditionFact())
1641bdd1243dSDimitry Andric         return true;
1642bdd1243dSDimitry Andric       if (B.isConditionFact())
1643bdd1243dSDimitry Andric         return false;
164406c3fb27SDimitry Andric       auto *InstA = A.getContextInst();
164506c3fb27SDimitry Andric       auto *InstB = B.getContextInst();
164606c3fb27SDimitry Andric       return InstA->comesBefore(InstB);
1647bdd1243dSDimitry Andric     }
1648bdd1243dSDimitry Andric     return A.NumIn < B.NumIn;
1649e8d8bef9SDimitry Andric   });
1650e8d8bef9SDimitry Andric 
165181ad6265SDimitry Andric   SmallVector<Instruction *> ToRemove;
165281ad6265SDimitry Andric 
1653e8d8bef9SDimitry Andric   // Finally, process ordered worklist and eliminate implied conditions.
1654e8d8bef9SDimitry Andric   SmallVector<StackEntry, 16> DFSInStack;
165506c3fb27SDimitry Andric   SmallVector<ReproducerEntry> ReproducerCondStack;
1656bdd1243dSDimitry Andric   for (FactOrCheck &CB : S.WorkList) {
1657e8d8bef9SDimitry Andric     // First, pop entries from the stack that are out-of-scope for CB. Remove
1658e8d8bef9SDimitry Andric     // the corresponding entry from the constraint system.
1659e8d8bef9SDimitry Andric     while (!DFSInStack.empty()) {
1660e8d8bef9SDimitry Andric       auto &E = DFSInStack.back();
1661e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1662e8d8bef9SDimitry Andric                         << "\n");
1663e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1664e8d8bef9SDimitry Andric       assert(E.NumIn <= CB.NumIn);
1665e8d8bef9SDimitry Andric       if (CB.NumOut <= E.NumOut)
1666e8d8bef9SDimitry Andric         break;
166781ad6265SDimitry Andric       LLVM_DEBUG({
166881ad6265SDimitry Andric         dbgs() << "Removing ";
166906c3fb27SDimitry Andric         dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
167081ad6265SDimitry Andric                        Info.getValue2Index(E.IsSigned));
167181ad6265SDimitry Andric         dbgs() << "\n";
167281ad6265SDimitry Andric       });
167306c3fb27SDimitry Andric       removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
167406c3fb27SDimitry Andric                            DFSInStack);
1675e8d8bef9SDimitry Andric     }
1676e8d8bef9SDimitry Andric 
1677e8d8bef9SDimitry Andric     // For a block, check if any CmpInsts become known based on the current set
1678e8d8bef9SDimitry Andric     // of constraints.
167906c3fb27SDimitry Andric     if (CB.isCheck()) {
168006c3fb27SDimitry Andric       Instruction *Inst = CB.getInstructionToSimplify();
168106c3fb27SDimitry Andric       if (!Inst)
168206c3fb27SDimitry Andric         continue;
16831db9f3b2SDimitry Andric       LLVM_DEBUG(dbgs() << "Processing condition to simplify: " << *Inst
16841db9f3b2SDimitry Andric                         << "\n");
168506c3fb27SDimitry Andric       if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
1686bdd1243dSDimitry Andric         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
168706c3fb27SDimitry Andric       } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) {
168806c3fb27SDimitry Andric         bool Simplified = checkAndReplaceCondition(
168906c3fb27SDimitry Andric             Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
16905f757f3fSDimitry Andric             ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
1691cb14a3feSDimitry Andric         if (!Simplified &&
1692cb14a3feSDimitry Andric             match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) {
169306c3fb27SDimitry Andric           Simplified =
1694cb14a3feSDimitry Andric               checkOrAndOpImpliedByOther(CB, Info, ReproducerModule.get(),
169506c3fb27SDimitry Andric                                          ReproducerCondStack, DFSInStack);
169606c3fb27SDimitry Andric         }
169706c3fb27SDimitry Andric         Changed |= Simplified;
1698e8d8bef9SDimitry Andric       }
1699e8d8bef9SDimitry Andric       continue;
1700e8d8bef9SDimitry Andric     }
1701e8d8bef9SDimitry Andric 
170206c3fb27SDimitry Andric     auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) {
17031db9f3b2SDimitry Andric       LLVM_DEBUG(dbgs() << "Processing fact to add to the system: ";
17045f757f3fSDimitry Andric                  dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n");
1705bdd1243dSDimitry Andric       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1706bdd1243dSDimitry Andric         LLVM_DEBUG(
1707bdd1243dSDimitry Andric             dbgs()
1708bdd1243dSDimitry Andric             << "Skip adding constraint because system has too many rows.\n");
170906c3fb27SDimitry Andric         return;
171006c3fb27SDimitry Andric       }
171106c3fb27SDimitry Andric 
171206c3fb27SDimitry Andric       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
171306c3fb27SDimitry Andric       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
171406c3fb27SDimitry Andric         ReproducerCondStack.emplace_back(Pred, A, B);
171506c3fb27SDimitry Andric 
171606c3fb27SDimitry Andric       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
171706c3fb27SDimitry Andric       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
171806c3fb27SDimitry Andric         // Add dummy entries to ReproducerCondStack to keep it in sync with
171906c3fb27SDimitry Andric         // DFSInStack.
172006c3fb27SDimitry Andric         for (unsigned I = 0,
172106c3fb27SDimitry Andric                       E = (DFSInStack.size() - ReproducerCondStack.size());
172206c3fb27SDimitry Andric              I < E; ++I) {
172306c3fb27SDimitry Andric           ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
172406c3fb27SDimitry Andric                                            nullptr, nullptr);
172506c3fb27SDimitry Andric         }
172606c3fb27SDimitry Andric       }
172706c3fb27SDimitry Andric     };
172806c3fb27SDimitry Andric 
172906c3fb27SDimitry Andric     ICmpInst::Predicate Pred;
17305f757f3fSDimitry Andric     if (!CB.isConditionFact()) {
1731647cbc5dSDimitry Andric       Value *X;
1732647cbc5dSDimitry Andric       if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) {
1733647cbc5dSDimitry Andric         // TODO: Add CB.Inst >= 0 fact.
1734647cbc5dSDimitry Andric         AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
1735647cbc5dSDimitry Andric         continue;
1736647cbc5dSDimitry Andric       }
1737647cbc5dSDimitry Andric 
173806c3fb27SDimitry Andric       if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
173906c3fb27SDimitry Andric         Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
174006c3fb27SDimitry Andric         AddFact(Pred, MinMax, MinMax->getLHS());
174106c3fb27SDimitry Andric         AddFact(Pred, MinMax, MinMax->getRHS());
1742bdd1243dSDimitry Andric         continue;
1743bdd1243dSDimitry Andric       }
1744e8d8bef9SDimitry Andric     }
17455f757f3fSDimitry Andric 
17465f757f3fSDimitry Andric     Value *A = nullptr, *B = nullptr;
17475f757f3fSDimitry Andric     if (CB.isConditionFact()) {
17485f757f3fSDimitry Andric       Pred = CB.Cond.Pred;
17495f757f3fSDimitry Andric       A = CB.Cond.Op0;
17505f757f3fSDimitry Andric       B = CB.Cond.Op1;
17515f757f3fSDimitry Andric       if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
17521db9f3b2SDimitry Andric           !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) {
17531db9f3b2SDimitry Andric         LLVM_DEBUG({
17541db9f3b2SDimitry Andric           dbgs() << "Not adding fact ";
17551db9f3b2SDimitry Andric           dumpUnpackedICmp(dbgs(), Pred, A, B);
17561db9f3b2SDimitry Andric           dbgs() << " because precondition ";
17571db9f3b2SDimitry Andric           dumpUnpackedICmp(dbgs(), CB.DoesHold.Pred, CB.DoesHold.Op0,
17581db9f3b2SDimitry Andric                            CB.DoesHold.Op1);
17591db9f3b2SDimitry Andric           dbgs() << " does not hold.\n";
17601db9f3b2SDimitry Andric         });
17615f757f3fSDimitry Andric         continue;
17621db9f3b2SDimitry Andric       }
17635f757f3fSDimitry Andric     } else {
17645f757f3fSDimitry Andric       bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>(
17655f757f3fSDimitry Andric                                         m_ICmp(Pred, m_Value(A), m_Value(B))));
17665f757f3fSDimitry Andric       (void)Matched;
17675f757f3fSDimitry Andric       assert(Matched && "Must have an assume intrinsic with a icmp operand");
17685f757f3fSDimitry Andric     }
17695f757f3fSDimitry Andric     AddFact(Pred, A, B);
1770fe6060f1SDimitry Andric   }
1771e8d8bef9SDimitry Andric 
177206c3fb27SDimitry Andric   if (ReproducerModule && !ReproducerModule->functions().empty()) {
177306c3fb27SDimitry Andric     std::string S;
177406c3fb27SDimitry Andric     raw_string_ostream StringS(S);
177506c3fb27SDimitry Andric     ReproducerModule->print(StringS, nullptr);
177606c3fb27SDimitry Andric     StringS.flush();
177706c3fb27SDimitry Andric     OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
177806c3fb27SDimitry Andric     Rem << ore::NV("module") << S;
177906c3fb27SDimitry Andric     ORE.emit(Rem);
178006c3fb27SDimitry Andric   }
178106c3fb27SDimitry Andric 
178281ad6265SDimitry Andric #ifndef NDEBUG
178381ad6265SDimitry Andric   unsigned SignedEntries =
178481ad6265SDimitry Andric       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1785cb14a3feSDimitry Andric   assert(Info.getCS(false).size() - FunctionArgs.size() ==
1786cb14a3feSDimitry Andric              DFSInStack.size() - SignedEntries &&
1787fe6060f1SDimitry Andric          "updates to CS and DFSInStack are out of sync");
178881ad6265SDimitry Andric   assert(Info.getCS(true).size() == SignedEntries &&
178981ad6265SDimitry Andric          "updates to CS and DFSInStack are out of sync");
179081ad6265SDimitry Andric #endif
179181ad6265SDimitry Andric 
179281ad6265SDimitry Andric   for (Instruction *I : ToRemove)
179381ad6265SDimitry Andric     I->eraseFromParent();
1794e8d8bef9SDimitry Andric   return Changed;
1795e8d8bef9SDimitry Andric }
1796e8d8bef9SDimitry Andric 
1797e8d8bef9SDimitry Andric PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1798e8d8bef9SDimitry Andric                                                  FunctionAnalysisManager &AM) {
1799e8d8bef9SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
18005f757f3fSDimitry Andric   auto &LI = AM.getResult<LoopAnalysis>(F);
18015f757f3fSDimitry Andric   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
180206c3fb27SDimitry Andric   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
18035f757f3fSDimitry Andric   if (!eliminateConstraints(F, DT, LI, SE, ORE))
1804e8d8bef9SDimitry Andric     return PreservedAnalyses::all();
1805e8d8bef9SDimitry Andric 
1806e8d8bef9SDimitry Andric   PreservedAnalyses PA;
1807e8d8bef9SDimitry Andric   PA.preserve<DominatorTreeAnalysis>();
18085f757f3fSDimitry Andric   PA.preserve<LoopAnalysis>();
18095f757f3fSDimitry Andric   PA.preserve<ScalarEvolutionAnalysis>();
1810e8d8bef9SDimitry Andric   PA.preserveSet<CFGAnalyses>();
1811e8d8bef9SDimitry Andric   return PA;
1812e8d8bef9SDimitry Andric }
1813