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" 320fca6ea1SDimitry Andric #include "llvm/IR/Module.h" 33e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h" 3406c3fb27SDimitry Andric #include "llvm/IR/Verifier.h" 35e8d8bef9SDimitry Andric #include "llvm/Pass.h" 36bdd1243dSDimitry Andric #include "llvm/Support/CommandLine.h" 37e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 38e8d8bef9SDimitry Andric #include "llvm/Support/DebugCounter.h" 3981ad6265SDimitry Andric #include "llvm/Support/MathExtras.h" 4006c3fb27SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h" 4106c3fb27SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h" 42e8d8bef9SDimitry Andric 43bdd1243dSDimitry Andric #include <cmath> 4406c3fb27SDimitry Andric #include <optional> 45fe6060f1SDimitry Andric #include <string> 46fe6060f1SDimitry Andric 47e8d8bef9SDimitry Andric using namespace llvm; 48e8d8bef9SDimitry Andric using namespace PatternMatch; 49e8d8bef9SDimitry Andric 50e8d8bef9SDimitry Andric #define DEBUG_TYPE "constraint-elimination" 51e8d8bef9SDimitry Andric 52e8d8bef9SDimitry Andric STATISTIC(NumCondsRemoved, "Number of instructions removed"); 53e8d8bef9SDimitry Andric DEBUG_COUNTER(EliminatedCounter, "conds-eliminated", 54e8d8bef9SDimitry Andric "Controls which conditions are eliminated"); 55e8d8bef9SDimitry Andric 56bdd1243dSDimitry Andric static cl::opt<unsigned> 57bdd1243dSDimitry Andric MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden, 58bdd1243dSDimitry Andric cl::desc("Maximum number of rows to keep in constraint system")); 59bdd1243dSDimitry Andric 6006c3fb27SDimitry Andric static cl::opt<bool> DumpReproducers( 6106c3fb27SDimitry Andric "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden, 6206c3fb27SDimitry Andric cl::desc("Dump IR to reproduce successful transformations.")); 6306c3fb27SDimitry Andric 64e8d8bef9SDimitry Andric static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max(); 6581ad6265SDimitry Andric static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min(); 66e8d8bef9SDimitry Andric 67bdd1243dSDimitry Andric // A helper to multiply 2 signed integers where overflowing is allowed. 68bdd1243dSDimitry Andric static int64_t multiplyWithOverflow(int64_t A, int64_t B) { 69bdd1243dSDimitry Andric int64_t Result; 70bdd1243dSDimitry Andric MulOverflow(A, B, Result); 71bdd1243dSDimitry Andric return Result; 72bdd1243dSDimitry Andric } 73bdd1243dSDimitry Andric 74bdd1243dSDimitry Andric // A helper to add 2 signed integers where overflowing is allowed. 75bdd1243dSDimitry Andric static int64_t addWithOverflow(int64_t A, int64_t B) { 76bdd1243dSDimitry Andric int64_t Result; 77bdd1243dSDimitry Andric AddOverflow(A, B, Result); 78bdd1243dSDimitry Andric return Result; 79bdd1243dSDimitry Andric } 80bdd1243dSDimitry Andric 8106c3fb27SDimitry Andric static Instruction *getContextInstForUse(Use &U) { 8206c3fb27SDimitry Andric Instruction *UserI = cast<Instruction>(U.getUser()); 8306c3fb27SDimitry Andric if (auto *Phi = dyn_cast<PHINode>(UserI)) 8406c3fb27SDimitry Andric UserI = Phi->getIncomingBlock(U)->getTerminator(); 8506c3fb27SDimitry Andric return UserI; 8606c3fb27SDimitry Andric } 8706c3fb27SDimitry Andric 8804eeddc0SDimitry Andric namespace { 895f757f3fSDimitry Andric /// Struct to express a condition of the form %Op0 Pred %Op1. 905f757f3fSDimitry Andric struct ConditionTy { 915f757f3fSDimitry Andric CmpInst::Predicate Pred; 925f757f3fSDimitry Andric Value *Op0; 935f757f3fSDimitry Andric Value *Op1; 945f757f3fSDimitry Andric 955f757f3fSDimitry Andric ConditionTy() 965f757f3fSDimitry Andric : Pred(CmpInst::BAD_ICMP_PREDICATE), Op0(nullptr), Op1(nullptr) {} 975f757f3fSDimitry Andric ConditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1) 985f757f3fSDimitry Andric : Pred(Pred), Op0(Op0), Op1(Op1) {} 995f757f3fSDimitry Andric }; 1005f757f3fSDimitry Andric 10106c3fb27SDimitry Andric /// Represents either 1025f757f3fSDimitry Andric /// * a condition that holds on entry to a block (=condition fact) 10306c3fb27SDimitry Andric /// * an assume (=assume fact) 10406c3fb27SDimitry Andric /// * a use of a compare instruction to simplify. 10506c3fb27SDimitry Andric /// It also tracks the Dominator DFS in and out numbers for each entry. 10606c3fb27SDimitry Andric struct FactOrCheck { 1075f757f3fSDimitry Andric enum class EntryTy { 1085f757f3fSDimitry Andric ConditionFact, /// A condition that holds on entry to a block. 1095f757f3fSDimitry Andric InstFact, /// A fact that holds after Inst executed (e.g. an assume or 1105f757f3fSDimitry Andric /// min/mix intrinsic. 1115f757f3fSDimitry Andric InstCheck, /// An instruction to simplify (e.g. an overflow math 1125f757f3fSDimitry Andric /// intrinsics). 1135f757f3fSDimitry Andric UseCheck /// An use of a compare instruction to simplify. 1145f757f3fSDimitry Andric }; 1155f757f3fSDimitry Andric 11606c3fb27SDimitry Andric union { 11706c3fb27SDimitry Andric Instruction *Inst; 11806c3fb27SDimitry Andric Use *U; 1195f757f3fSDimitry Andric ConditionTy Cond; 12006c3fb27SDimitry Andric }; 1215f757f3fSDimitry Andric 1225f757f3fSDimitry Andric /// A pre-condition that must hold for the current fact to be added to the 1235f757f3fSDimitry Andric /// system. 1245f757f3fSDimitry Andric ConditionTy DoesHold; 1255f757f3fSDimitry Andric 12606c3fb27SDimitry Andric unsigned NumIn; 12706c3fb27SDimitry Andric unsigned NumOut; 1285f757f3fSDimitry Andric EntryTy Ty; 12906c3fb27SDimitry Andric 1305f757f3fSDimitry Andric FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst) 13106c3fb27SDimitry Andric : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), 1325f757f3fSDimitry Andric Ty(Ty) {} 13306c3fb27SDimitry Andric 13406c3fb27SDimitry Andric FactOrCheck(DomTreeNode *DTN, Use *U) 1355f757f3fSDimitry Andric : U(U), DoesHold(CmpInst::BAD_ICMP_PREDICATE, nullptr, nullptr), 1365f757f3fSDimitry Andric NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), 1375f757f3fSDimitry Andric Ty(EntryTy::UseCheck) {} 13806c3fb27SDimitry Andric 1395f757f3fSDimitry Andric FactOrCheck(DomTreeNode *DTN, CmpInst::Predicate Pred, Value *Op0, Value *Op1, 1405f757f3fSDimitry Andric ConditionTy Precond = ConditionTy()) 1415f757f3fSDimitry Andric : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()), 1425f757f3fSDimitry Andric NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {} 1435f757f3fSDimitry Andric 1445f757f3fSDimitry Andric static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpInst::Predicate Pred, 1455f757f3fSDimitry Andric Value *Op0, Value *Op1, 1465f757f3fSDimitry Andric ConditionTy Precond = ConditionTy()) { 1475f757f3fSDimitry Andric return FactOrCheck(DTN, Pred, Op0, Op1, Precond); 1485f757f3fSDimitry Andric } 1495f757f3fSDimitry Andric 1505f757f3fSDimitry Andric static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) { 1515f757f3fSDimitry Andric return FactOrCheck(EntryTy::InstFact, DTN, Inst); 15206c3fb27SDimitry Andric } 15306c3fb27SDimitry Andric 15406c3fb27SDimitry Andric static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) { 15506c3fb27SDimitry Andric return FactOrCheck(DTN, U); 15606c3fb27SDimitry Andric } 15706c3fb27SDimitry Andric 15806c3fb27SDimitry Andric static FactOrCheck getCheck(DomTreeNode *DTN, CallInst *CI) { 1595f757f3fSDimitry Andric return FactOrCheck(EntryTy::InstCheck, DTN, CI); 16006c3fb27SDimitry Andric } 16106c3fb27SDimitry Andric 16206c3fb27SDimitry Andric bool isCheck() const { 1635f757f3fSDimitry Andric return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck; 16406c3fb27SDimitry Andric } 16506c3fb27SDimitry Andric 16606c3fb27SDimitry Andric Instruction *getContextInst() const { 1675f757f3fSDimitry Andric if (Ty == EntryTy::UseCheck) 16806c3fb27SDimitry Andric return getContextInstForUse(*U); 1695f757f3fSDimitry Andric return Inst; 17006c3fb27SDimitry Andric } 1715f757f3fSDimitry Andric 17206c3fb27SDimitry Andric Instruction *getInstructionToSimplify() const { 17306c3fb27SDimitry Andric assert(isCheck()); 1745f757f3fSDimitry Andric if (Ty == EntryTy::InstCheck) 17506c3fb27SDimitry Andric return Inst; 17606c3fb27SDimitry Andric // The use may have been simplified to a constant already. 17706c3fb27SDimitry Andric return dyn_cast<Instruction>(*U); 17806c3fb27SDimitry Andric } 1795f757f3fSDimitry Andric 1805f757f3fSDimitry Andric bool isConditionFact() const { return Ty == EntryTy::ConditionFact; } 18106c3fb27SDimitry Andric }; 18206c3fb27SDimitry Andric 18306c3fb27SDimitry Andric /// Keep state required to build worklist. 18406c3fb27SDimitry Andric struct State { 18506c3fb27SDimitry Andric DominatorTree &DT; 1865f757f3fSDimitry Andric LoopInfo &LI; 1875f757f3fSDimitry Andric ScalarEvolution &SE; 18806c3fb27SDimitry Andric SmallVector<FactOrCheck, 64> WorkList; 18906c3fb27SDimitry Andric 1905f757f3fSDimitry Andric State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE) 1915f757f3fSDimitry Andric : DT(DT), LI(LI), SE(SE) {} 19206c3fb27SDimitry Andric 19306c3fb27SDimitry Andric /// Process block \p BB and add known facts to work-list. 19406c3fb27SDimitry Andric void addInfoFor(BasicBlock &BB); 19506c3fb27SDimitry Andric 1965f757f3fSDimitry Andric /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares 1975f757f3fSDimitry Andric /// controlling the loop header. 1985f757f3fSDimitry Andric void addInfoForInductions(BasicBlock &BB); 1995f757f3fSDimitry Andric 20006c3fb27SDimitry Andric /// Returns true if we can add a known condition from BB to its successor 20106c3fb27SDimitry Andric /// block Succ. 20206c3fb27SDimitry Andric bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const { 20306c3fb27SDimitry Andric return DT.dominates(BasicBlockEdge(&BB, Succ), Succ); 20406c3fb27SDimitry Andric } 20506c3fb27SDimitry Andric }; 20604eeddc0SDimitry Andric 20781ad6265SDimitry Andric class ConstraintInfo; 20804eeddc0SDimitry Andric 20981ad6265SDimitry Andric struct StackEntry { 21081ad6265SDimitry Andric unsigned NumIn; 21181ad6265SDimitry Andric unsigned NumOut; 21281ad6265SDimitry Andric bool IsSigned = false; 21381ad6265SDimitry Andric /// Variables that can be removed from the system once the stack entry gets 21481ad6265SDimitry Andric /// removed. 21581ad6265SDimitry Andric SmallVector<Value *, 2> ValuesToRelease; 21681ad6265SDimitry Andric 217bdd1243dSDimitry Andric StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned, 21881ad6265SDimitry Andric SmallVector<Value *, 2> ValuesToRelease) 219bdd1243dSDimitry Andric : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned), 22081ad6265SDimitry Andric ValuesToRelease(ValuesToRelease) {} 22104eeddc0SDimitry Andric }; 22204eeddc0SDimitry Andric 22381ad6265SDimitry Andric struct ConstraintTy { 22481ad6265SDimitry Andric SmallVector<int64_t, 8> Coefficients; 2255f757f3fSDimitry Andric SmallVector<ConditionTy, 2> Preconditions; 22604eeddc0SDimitry Andric 227bdd1243dSDimitry Andric SmallVector<SmallVector<int64_t, 8>> ExtraInfo; 228bdd1243dSDimitry Andric 22981ad6265SDimitry Andric bool IsSigned = false; 23004eeddc0SDimitry Andric 23181ad6265SDimitry Andric ConstraintTy() = default; 23204eeddc0SDimitry Andric 23306c3fb27SDimitry Andric ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned, bool IsEq, 23406c3fb27SDimitry Andric bool IsNe) 2350fca6ea1SDimitry Andric : Coefficients(std::move(Coefficients)), IsSigned(IsSigned), IsEq(IsEq), 2360fca6ea1SDimitry Andric IsNe(IsNe) {} 23781ad6265SDimitry Andric 23881ad6265SDimitry Andric unsigned size() const { return Coefficients.size(); } 23981ad6265SDimitry Andric 24081ad6265SDimitry Andric unsigned empty() const { return Coefficients.empty(); } 24104eeddc0SDimitry Andric 24281ad6265SDimitry Andric /// Returns true if all preconditions for this list of constraints are 24381ad6265SDimitry Andric /// satisfied given \p CS and the corresponding \p Value2Index mapping. 24481ad6265SDimitry Andric bool isValid(const ConstraintInfo &Info) const; 24506c3fb27SDimitry Andric 24606c3fb27SDimitry Andric bool isEq() const { return IsEq; } 24706c3fb27SDimitry Andric 24806c3fb27SDimitry Andric bool isNe() const { return IsNe; } 24906c3fb27SDimitry Andric 25006c3fb27SDimitry Andric /// Check if the current constraint is implied by the given ConstraintSystem. 25106c3fb27SDimitry Andric /// 25206c3fb27SDimitry Andric /// \return true or false if the constraint is proven to be respectively true, 25306c3fb27SDimitry Andric /// or false. When the constraint cannot be proven to be either true or false, 25406c3fb27SDimitry Andric /// std::nullopt is returned. 25506c3fb27SDimitry Andric std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const; 25606c3fb27SDimitry Andric 25706c3fb27SDimitry Andric private: 25806c3fb27SDimitry Andric bool IsEq = false; 25906c3fb27SDimitry Andric bool IsNe = false; 26081ad6265SDimitry Andric }; 26181ad6265SDimitry Andric 26281ad6265SDimitry Andric /// Wrapper encapsulating separate constraint systems and corresponding value 26381ad6265SDimitry Andric /// mappings for both unsigned and signed information. Facts are added to and 26481ad6265SDimitry Andric /// conditions are checked against the corresponding system depending on the 26581ad6265SDimitry Andric /// signed-ness of their predicates. While the information is kept separate 26681ad6265SDimitry Andric /// based on signed-ness, certain conditions can be transferred between the two 26781ad6265SDimitry Andric /// systems. 26881ad6265SDimitry Andric class ConstraintInfo { 26981ad6265SDimitry Andric 27081ad6265SDimitry Andric ConstraintSystem UnsignedCS; 27181ad6265SDimitry Andric ConstraintSystem SignedCS; 27281ad6265SDimitry Andric 273bdd1243dSDimitry Andric const DataLayout &DL; 274bdd1243dSDimitry Andric 27581ad6265SDimitry Andric public: 27606c3fb27SDimitry Andric ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs) 277cb14a3feSDimitry Andric : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) { 278cb14a3feSDimitry Andric auto &Value2Index = getValue2Index(false); 279cb14a3feSDimitry Andric // Add Arg > -1 constraints to unsigned system for all function arguments. 280cb14a3feSDimitry Andric for (Value *Arg : FunctionArgs) { 281cb14a3feSDimitry Andric ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0), 282cb14a3feSDimitry Andric false, false, false); 283cb14a3feSDimitry Andric VarPos.Coefficients[Value2Index[Arg]] = -1; 284cb14a3feSDimitry Andric UnsignedCS.addVariableRow(VarPos.Coefficients); 285cb14a3feSDimitry Andric } 286cb14a3feSDimitry Andric } 287bdd1243dSDimitry Andric 28881ad6265SDimitry Andric DenseMap<Value *, unsigned> &getValue2Index(bool Signed) { 28906c3fb27SDimitry Andric return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index(); 29081ad6265SDimitry Andric } 29181ad6265SDimitry Andric const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const { 29206c3fb27SDimitry Andric return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index(); 29381ad6265SDimitry Andric } 29481ad6265SDimitry Andric 29581ad6265SDimitry Andric ConstraintSystem &getCS(bool Signed) { 29681ad6265SDimitry Andric return Signed ? SignedCS : UnsignedCS; 29781ad6265SDimitry Andric } 29881ad6265SDimitry Andric const ConstraintSystem &getCS(bool Signed) const { 29981ad6265SDimitry Andric return Signed ? SignedCS : UnsignedCS; 30081ad6265SDimitry Andric } 30181ad6265SDimitry Andric 30281ad6265SDimitry Andric void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); } 30381ad6265SDimitry Andric void popLastNVariables(bool Signed, unsigned N) { 30481ad6265SDimitry Andric getCS(Signed).popLastNVariables(N); 30581ad6265SDimitry Andric } 30681ad6265SDimitry Andric 30781ad6265SDimitry Andric bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const; 30881ad6265SDimitry Andric 309bdd1243dSDimitry Andric void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 310bdd1243dSDimitry Andric unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack); 31181ad6265SDimitry Andric 31281ad6265SDimitry Andric /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 31381ad6265SDimitry Andric /// constraints, using indices from the corresponding constraint system. 314bdd1243dSDimitry Andric /// New variables that need to be added to the system are collected in 315bdd1243dSDimitry Andric /// \p NewVariables. 31681ad6265SDimitry Andric ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 317bdd1243dSDimitry Andric SmallVectorImpl<Value *> &NewVariables) const; 31881ad6265SDimitry Andric 319bdd1243dSDimitry Andric /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 320bdd1243dSDimitry Andric /// constraints using getConstraint. Returns an empty constraint if the result 321bdd1243dSDimitry Andric /// cannot be used to query the existing constraint system, e.g. because it 322bdd1243dSDimitry Andric /// would require adding new variables. Also tries to convert signed 323bdd1243dSDimitry Andric /// predicates to unsigned ones if possible to allow using the unsigned system 324bdd1243dSDimitry Andric /// which increases the effectiveness of the signed <-> unsigned transfer 325bdd1243dSDimitry Andric /// logic. 326bdd1243dSDimitry Andric ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0, 327bdd1243dSDimitry Andric Value *Op1) const; 32881ad6265SDimitry Andric 32981ad6265SDimitry Andric /// Try to add information from \p A \p Pred \p B to the unsigned/signed 33081ad6265SDimitry Andric /// system if \p Pred is signed/unsigned. 33181ad6265SDimitry Andric void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B, 332bdd1243dSDimitry Andric unsigned NumIn, unsigned NumOut, 33381ad6265SDimitry Andric SmallVectorImpl<StackEntry> &DFSInStack); 33404eeddc0SDimitry Andric }; 33504eeddc0SDimitry Andric 336bdd1243dSDimitry Andric /// Represents a (Coefficient * Variable) entry after IR decomposition. 337bdd1243dSDimitry Andric struct DecompEntry { 338bdd1243dSDimitry Andric int64_t Coefficient; 339bdd1243dSDimitry Andric Value *Variable; 340bdd1243dSDimitry Andric /// True if the variable is known positive in the current constraint. 341bdd1243dSDimitry Andric bool IsKnownNonNegative; 342bdd1243dSDimitry Andric 343bdd1243dSDimitry Andric DecompEntry(int64_t Coefficient, Value *Variable, 344bdd1243dSDimitry Andric bool IsKnownNonNegative = false) 345bdd1243dSDimitry Andric : Coefficient(Coefficient), Variable(Variable), 346bdd1243dSDimitry Andric IsKnownNonNegative(IsKnownNonNegative) {} 347bdd1243dSDimitry Andric }; 348bdd1243dSDimitry Andric 349bdd1243dSDimitry Andric /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition. 350bdd1243dSDimitry Andric struct Decomposition { 351bdd1243dSDimitry Andric int64_t Offset = 0; 352bdd1243dSDimitry Andric SmallVector<DecompEntry, 3> Vars; 353bdd1243dSDimitry Andric 354bdd1243dSDimitry Andric Decomposition(int64_t Offset) : Offset(Offset) {} 355bdd1243dSDimitry Andric Decomposition(Value *V, bool IsKnownNonNegative = false) { 356bdd1243dSDimitry Andric Vars.emplace_back(1, V, IsKnownNonNegative); 357bdd1243dSDimitry Andric } 358bdd1243dSDimitry Andric Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars) 359bdd1243dSDimitry Andric : Offset(Offset), Vars(Vars) {} 360bdd1243dSDimitry Andric 361bdd1243dSDimitry Andric void add(int64_t OtherOffset) { 362bdd1243dSDimitry Andric Offset = addWithOverflow(Offset, OtherOffset); 363bdd1243dSDimitry Andric } 364bdd1243dSDimitry Andric 365bdd1243dSDimitry Andric void add(const Decomposition &Other) { 366bdd1243dSDimitry Andric add(Other.Offset); 367bdd1243dSDimitry Andric append_range(Vars, Other.Vars); 368bdd1243dSDimitry Andric } 369bdd1243dSDimitry Andric 370647cbc5dSDimitry Andric void sub(const Decomposition &Other) { 371647cbc5dSDimitry Andric Decomposition Tmp = Other; 372647cbc5dSDimitry Andric Tmp.mul(-1); 373647cbc5dSDimitry Andric add(Tmp.Offset); 374647cbc5dSDimitry Andric append_range(Vars, Tmp.Vars); 375647cbc5dSDimitry Andric } 376647cbc5dSDimitry Andric 377bdd1243dSDimitry Andric void mul(int64_t Factor) { 378bdd1243dSDimitry Andric Offset = multiplyWithOverflow(Offset, Factor); 379bdd1243dSDimitry Andric for (auto &Var : Vars) 380bdd1243dSDimitry Andric Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor); 381bdd1243dSDimitry Andric } 382bdd1243dSDimitry Andric }; 383bdd1243dSDimitry Andric 3845f757f3fSDimitry Andric // Variable and constant offsets for a chain of GEPs, with base pointer BasePtr. 3855f757f3fSDimitry Andric struct OffsetResult { 3865f757f3fSDimitry Andric Value *BasePtr; 3875f757f3fSDimitry Andric APInt ConstantOffset; 3885f757f3fSDimitry Andric MapVector<Value *, APInt> VariableOffsets; 3895f757f3fSDimitry Andric bool AllInbounds; 3905f757f3fSDimitry Andric 3915f757f3fSDimitry Andric OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {} 3925f757f3fSDimitry Andric 3935f757f3fSDimitry Andric OffsetResult(GEPOperator &GEP, const DataLayout &DL) 3945f757f3fSDimitry Andric : BasePtr(GEP.getPointerOperand()), AllInbounds(GEP.isInBounds()) { 3955f757f3fSDimitry Andric ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0); 3965f757f3fSDimitry Andric } 3975f757f3fSDimitry Andric }; 39804eeddc0SDimitry Andric } // namespace 39904eeddc0SDimitry Andric 4005f757f3fSDimitry Andric // Try to collect variable and constant offsets for \p GEP, partly traversing 4015f757f3fSDimitry Andric // nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting 4025f757f3fSDimitry Andric // the offset fails. 4035f757f3fSDimitry Andric static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL) { 4045f757f3fSDimitry Andric OffsetResult Result(GEP, DL); 4055f757f3fSDimitry Andric unsigned BitWidth = Result.ConstantOffset.getBitWidth(); 4065f757f3fSDimitry Andric if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets, 4075f757f3fSDimitry Andric Result.ConstantOffset)) 4085f757f3fSDimitry Andric return {}; 4095f757f3fSDimitry Andric 4105f757f3fSDimitry Andric // If we have a nested GEP, check if we can combine the constant offset of the 4115f757f3fSDimitry Andric // inner GEP with the outer GEP. 4125f757f3fSDimitry Andric if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) { 4135f757f3fSDimitry Andric MapVector<Value *, APInt> VariableOffsets2; 4145f757f3fSDimitry Andric APInt ConstantOffset2(BitWidth, 0); 4155f757f3fSDimitry Andric bool CanCollectInner = InnerGEP->collectOffset( 4165f757f3fSDimitry Andric DL, BitWidth, VariableOffsets2, ConstantOffset2); 4175f757f3fSDimitry Andric // TODO: Support cases with more than 1 variable offset. 4185f757f3fSDimitry Andric if (!CanCollectInner || Result.VariableOffsets.size() > 1 || 4195f757f3fSDimitry Andric VariableOffsets2.size() > 1 || 4205f757f3fSDimitry Andric (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) { 4215f757f3fSDimitry Andric // More than 1 variable index, use outer result. 4225f757f3fSDimitry Andric return Result; 4235f757f3fSDimitry Andric } 4245f757f3fSDimitry Andric Result.BasePtr = InnerGEP->getPointerOperand(); 4255f757f3fSDimitry Andric Result.ConstantOffset += ConstantOffset2; 4265f757f3fSDimitry Andric if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1) 4275f757f3fSDimitry Andric Result.VariableOffsets = VariableOffsets2; 4285f757f3fSDimitry Andric Result.AllInbounds &= InnerGEP->isInBounds(); 4295f757f3fSDimitry Andric } 4305f757f3fSDimitry Andric return Result; 4315f757f3fSDimitry Andric } 4325f757f3fSDimitry Andric 433bdd1243dSDimitry Andric static Decomposition decompose(Value *V, 4345f757f3fSDimitry Andric SmallVectorImpl<ConditionTy> &Preconditions, 435bdd1243dSDimitry Andric bool IsSigned, const DataLayout &DL); 43681ad6265SDimitry Andric 437bdd1243dSDimitry Andric static bool canUseSExt(ConstantInt *CI) { 43881ad6265SDimitry Andric const APInt &Val = CI->getValue(); 43981ad6265SDimitry Andric return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue); 440bdd1243dSDimitry Andric } 441bdd1243dSDimitry Andric 4425f757f3fSDimitry Andric static Decomposition decomposeGEP(GEPOperator &GEP, 4435f757f3fSDimitry Andric SmallVectorImpl<ConditionTy> &Preconditions, 44406c3fb27SDimitry Andric bool IsSigned, const DataLayout &DL) { 445bdd1243dSDimitry Andric // Do not reason about pointers where the index size is larger than 64 bits, 446bdd1243dSDimitry Andric // as the coefficients used to encode constraints are 64 bit integers. 447bdd1243dSDimitry Andric if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64) 448bdd1243dSDimitry Andric return &GEP; 449bdd1243dSDimitry Andric 450bdd1243dSDimitry Andric assert(!IsSigned && "The logic below only supports decomposition for " 4515f757f3fSDimitry Andric "unsigned predicates at the moment."); 4525f757f3fSDimitry Andric const auto &[BasePtr, ConstantOffset, VariableOffsets, AllInbounds] = 4535f757f3fSDimitry Andric collectOffsets(GEP, DL); 4545f757f3fSDimitry Andric if (!BasePtr || !AllInbounds) 455bdd1243dSDimitry Andric return &GEP; 456bdd1243dSDimitry Andric 4575f757f3fSDimitry Andric Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr)); 458bdd1243dSDimitry Andric for (auto [Index, Scale] : VariableOffsets) { 459bdd1243dSDimitry Andric auto IdxResult = decompose(Index, Preconditions, IsSigned, DL); 460bdd1243dSDimitry Andric IdxResult.mul(Scale.getSExtValue()); 461bdd1243dSDimitry Andric Result.add(IdxResult); 462bdd1243dSDimitry Andric 463bdd1243dSDimitry Andric // If Op0 is signed non-negative, the GEP is increasing monotonically and 464bdd1243dSDimitry Andric // can be de-composed. 4650fca6ea1SDimitry Andric if (!isKnownNonNegative(Index, DL)) 466bdd1243dSDimitry Andric Preconditions.emplace_back(CmpInst::ICMP_SGE, Index, 467bdd1243dSDimitry Andric ConstantInt::get(Index->getType(), 0)); 468bdd1243dSDimitry Andric } 469bdd1243dSDimitry Andric return Result; 470bdd1243dSDimitry Andric } 471bdd1243dSDimitry Andric 472bdd1243dSDimitry Andric // Decomposes \p V into a constant offset + list of pairs { Coefficient, 473bdd1243dSDimitry Andric // Variable } where Coefficient * Variable. The sum of the constant offset and 474bdd1243dSDimitry Andric // pairs equals \p V. 475bdd1243dSDimitry Andric static Decomposition decompose(Value *V, 4765f757f3fSDimitry Andric SmallVectorImpl<ConditionTy> &Preconditions, 477bdd1243dSDimitry Andric bool IsSigned, const DataLayout &DL) { 478bdd1243dSDimitry Andric 479bdd1243dSDimitry Andric auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B, 480bdd1243dSDimitry Andric bool IsSignedB) { 481bdd1243dSDimitry Andric auto ResA = decompose(A, Preconditions, IsSigned, DL); 482bdd1243dSDimitry Andric auto ResB = decompose(B, Preconditions, IsSignedB, DL); 483bdd1243dSDimitry Andric ResA.add(ResB); 484bdd1243dSDimitry Andric return ResA; 48581ad6265SDimitry Andric }; 486bdd1243dSDimitry Andric 487b121cb00SDimitry Andric Type *Ty = V->getType()->getScalarType(); 488b121cb00SDimitry Andric if (Ty->isPointerTy() && !IsSigned) { 489b121cb00SDimitry Andric if (auto *GEP = dyn_cast<GEPOperator>(V)) 490b121cb00SDimitry Andric return decomposeGEP(*GEP, Preconditions, IsSigned, DL); 4915f757f3fSDimitry Andric if (isa<ConstantPointerNull>(V)) 4925f757f3fSDimitry Andric return int64_t(0); 4935f757f3fSDimitry Andric 494b121cb00SDimitry Andric return V; 495b121cb00SDimitry Andric } 496b121cb00SDimitry Andric 497b121cb00SDimitry Andric // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so 498b121cb00SDimitry Andric // coefficient add/mul may wrap, while the operation in the full bit width 499b121cb00SDimitry Andric // would not. 500b121cb00SDimitry Andric if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64) 501b121cb00SDimitry Andric return V; 502b121cb00SDimitry Andric 5030fca6ea1SDimitry Andric bool IsKnownNonNegative = false; 5040fca6ea1SDimitry Andric 50581ad6265SDimitry Andric // Decompose \p V used with a signed predicate. 50681ad6265SDimitry Andric if (IsSigned) { 507e8d8bef9SDimitry Andric if (auto *CI = dyn_cast<ConstantInt>(V)) { 508bdd1243dSDimitry Andric if (canUseSExt(CI)) 509bdd1243dSDimitry Andric return CI->getSExtValue(); 510e8d8bef9SDimitry Andric } 511bdd1243dSDimitry Andric Value *Op0; 512bdd1243dSDimitry Andric Value *Op1; 5130fca6ea1SDimitry Andric 5140fca6ea1SDimitry Andric if (match(V, m_SExt(m_Value(Op0)))) 5150fca6ea1SDimitry Andric V = Op0; 5160fca6ea1SDimitry Andric else if (match(V, m_NNegZExt(m_Value(Op0)))) { 5170fca6ea1SDimitry Andric V = Op0; 5180fca6ea1SDimitry Andric IsKnownNonNegative = true; 5190fca6ea1SDimitry Andric } 5200fca6ea1SDimitry Andric 521bdd1243dSDimitry Andric if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) 522bdd1243dSDimitry Andric return MergeResults(Op0, Op1, IsSigned); 52381ad6265SDimitry Andric 52406c3fb27SDimitry Andric ConstantInt *CI; 5258a4dda33SDimitry Andric if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) { 52606c3fb27SDimitry Andric auto Result = decompose(Op0, Preconditions, IsSigned, DL); 52706c3fb27SDimitry Andric Result.mul(CI->getSExtValue()); 52806c3fb27SDimitry Andric return Result; 52906c3fb27SDimitry Andric } 53006c3fb27SDimitry Andric 5311db9f3b2SDimitry Andric // (shl nsw x, shift) is (mul nsw x, (1<<shift)), with the exception of 5321db9f3b2SDimitry Andric // shift == bw-1. 5331db9f3b2SDimitry Andric if (match(V, m_NSWShl(m_Value(Op0), m_ConstantInt(CI)))) { 5341db9f3b2SDimitry Andric uint64_t Shift = CI->getValue().getLimitedValue(); 5351db9f3b2SDimitry Andric if (Shift < Ty->getIntegerBitWidth() - 1) { 5361db9f3b2SDimitry Andric assert(Shift < 64 && "Would overflow"); 5371db9f3b2SDimitry Andric auto Result = decompose(Op0, Preconditions, IsSigned, DL); 5381db9f3b2SDimitry Andric Result.mul(int64_t(1) << Shift); 5391db9f3b2SDimitry Andric return Result; 5401db9f3b2SDimitry Andric } 5411db9f3b2SDimitry Andric } 5421db9f3b2SDimitry Andric 5430fca6ea1SDimitry Andric return {V, IsKnownNonNegative}; 54481ad6265SDimitry Andric } 54581ad6265SDimitry Andric 54681ad6265SDimitry Andric if (auto *CI = dyn_cast<ConstantInt>(V)) { 54781ad6265SDimitry Andric if (CI->uge(MaxConstraintValue)) 548bdd1243dSDimitry Andric return V; 549bdd1243dSDimitry Andric return int64_t(CI->getZExtValue()); 550fe6060f1SDimitry Andric } 551fe6060f1SDimitry Andric 552e8d8bef9SDimitry Andric Value *Op0; 553bdd1243dSDimitry Andric if (match(V, m_ZExt(m_Value(Op0)))) { 554bdd1243dSDimitry Andric IsKnownNonNegative = true; 555fe6060f1SDimitry Andric V = Op0; 556bdd1243dSDimitry Andric } 557fe6060f1SDimitry Andric 5580fca6ea1SDimitry Andric if (match(V, m_SExt(m_Value(Op0)))) { 5590fca6ea1SDimitry Andric V = Op0; 5600fca6ea1SDimitry Andric Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0, 5610fca6ea1SDimitry Andric ConstantInt::get(Op0->getType(), 0)); 5620fca6ea1SDimitry Andric } 5630fca6ea1SDimitry Andric 564e8d8bef9SDimitry Andric Value *Op1; 565e8d8bef9SDimitry Andric ConstantInt *CI; 566bdd1243dSDimitry Andric if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) { 567bdd1243dSDimitry Andric return MergeResults(Op0, Op1, IsSigned); 568bdd1243dSDimitry Andric } 569bdd1243dSDimitry Andric if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) { 5700fca6ea1SDimitry Andric if (!isKnownNonNegative(Op0, DL)) 571bdd1243dSDimitry Andric Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0, 572bdd1243dSDimitry Andric ConstantInt::get(Op0->getType(), 0)); 5730fca6ea1SDimitry Andric if (!isKnownNonNegative(Op1, DL)) 574bdd1243dSDimitry Andric Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1, 575bdd1243dSDimitry Andric ConstantInt::get(Op1->getType(), 0)); 576bdd1243dSDimitry Andric 577bdd1243dSDimitry Andric return MergeResults(Op0, Op1, IsSigned); 578bdd1243dSDimitry Andric } 579bdd1243dSDimitry Andric 58081ad6265SDimitry Andric if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() && 581bdd1243dSDimitry Andric canUseSExt(CI)) { 58281ad6265SDimitry Andric Preconditions.emplace_back( 58381ad6265SDimitry Andric CmpInst::ICMP_UGE, Op0, 58481ad6265SDimitry Andric ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1)); 585bdd1243dSDimitry Andric return MergeResults(Op0, CI, true); 58681ad6265SDimitry Andric } 587e8d8bef9SDimitry Andric 58806c3fb27SDimitry Andric // Decompose or as an add if there are no common bits between the operands. 5895f757f3fSDimitry Andric if (match(V, m_DisjointOr(m_Value(Op0), m_ConstantInt(CI)))) 59006c3fb27SDimitry Andric return MergeResults(Op0, CI, IsSigned); 59106c3fb27SDimitry Andric 592bdd1243dSDimitry Andric if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) { 59306c3fb27SDimitry Andric if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64) 59406c3fb27SDimitry Andric return {V, IsKnownNonNegative}; 595bdd1243dSDimitry Andric auto Result = decompose(Op1, Preconditions, IsSigned, DL); 59606c3fb27SDimitry Andric Result.mul(int64_t{1} << CI->getSExtValue()); 597bdd1243dSDimitry Andric return Result; 598bdd1243dSDimitry Andric } 599bdd1243dSDimitry Andric 600bdd1243dSDimitry Andric if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) && 601bdd1243dSDimitry Andric (!CI->isNegative())) { 602bdd1243dSDimitry Andric auto Result = decompose(Op1, Preconditions, IsSigned, DL); 603bdd1243dSDimitry Andric Result.mul(CI->getSExtValue()); 604bdd1243dSDimitry Andric return Result; 605bdd1243dSDimitry Andric } 606bdd1243dSDimitry Andric 607647cbc5dSDimitry Andric if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) { 608647cbc5dSDimitry Andric auto ResA = decompose(Op0, Preconditions, IsSigned, DL); 609647cbc5dSDimitry Andric auto ResB = decompose(Op1, Preconditions, IsSigned, DL); 610647cbc5dSDimitry Andric ResA.sub(ResB); 611647cbc5dSDimitry Andric return ResA; 612647cbc5dSDimitry Andric } 613e8d8bef9SDimitry Andric 614bdd1243dSDimitry Andric return {V, IsKnownNonNegative}; 615e8d8bef9SDimitry Andric } 616e8d8bef9SDimitry Andric 61781ad6265SDimitry Andric ConstraintTy 61881ad6265SDimitry Andric ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 619bdd1243dSDimitry Andric SmallVectorImpl<Value *> &NewVariables) const { 620bdd1243dSDimitry Andric assert(NewVariables.empty() && "NewVariables must be empty when passed in"); 62181ad6265SDimitry Andric bool IsEq = false; 62206c3fb27SDimitry Andric bool IsNe = false; 62306c3fb27SDimitry Andric 62481ad6265SDimitry Andric // Try to convert Pred to one of ULE/SLT/SLE/SLT. 62581ad6265SDimitry Andric switch (Pred) { 62681ad6265SDimitry Andric case CmpInst::ICMP_UGT: 62781ad6265SDimitry Andric case CmpInst::ICMP_UGE: 62881ad6265SDimitry Andric case CmpInst::ICMP_SGT: 62981ad6265SDimitry Andric case CmpInst::ICMP_SGE: { 63081ad6265SDimitry Andric Pred = CmpInst::getSwappedPredicate(Pred); 63181ad6265SDimitry Andric std::swap(Op0, Op1); 63281ad6265SDimitry Andric break; 63381ad6265SDimitry Andric } 63481ad6265SDimitry Andric case CmpInst::ICMP_EQ: 63581ad6265SDimitry Andric if (match(Op1, m_Zero())) { 63681ad6265SDimitry Andric Pred = CmpInst::ICMP_ULE; 63781ad6265SDimitry Andric } else { 63881ad6265SDimitry Andric IsEq = true; 63981ad6265SDimitry Andric Pred = CmpInst::ICMP_ULE; 64081ad6265SDimitry Andric } 64181ad6265SDimitry Andric break; 64281ad6265SDimitry Andric case CmpInst::ICMP_NE: 64306c3fb27SDimitry Andric if (match(Op1, m_Zero())) { 64481ad6265SDimitry Andric Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT); 64581ad6265SDimitry Andric std::swap(Op0, Op1); 64606c3fb27SDimitry Andric } else { 64706c3fb27SDimitry Andric IsNe = true; 64806c3fb27SDimitry Andric Pred = CmpInst::ICMP_ULE; 64906c3fb27SDimitry Andric } 65081ad6265SDimitry Andric break; 65181ad6265SDimitry Andric default: 65281ad6265SDimitry Andric break; 65381ad6265SDimitry Andric } 65481ad6265SDimitry Andric 65581ad6265SDimitry Andric if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT && 65681ad6265SDimitry Andric Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT) 65781ad6265SDimitry Andric return {}; 65881ad6265SDimitry Andric 6595f757f3fSDimitry Andric SmallVector<ConditionTy, 4> Preconditions; 66081ad6265SDimitry Andric bool IsSigned = CmpInst::isSigned(Pred); 66181ad6265SDimitry Andric auto &Value2Index = getValue2Index(IsSigned); 66281ad6265SDimitry Andric auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), 663bdd1243dSDimitry Andric Preconditions, IsSigned, DL); 66481ad6265SDimitry Andric auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), 665bdd1243dSDimitry Andric Preconditions, IsSigned, DL); 666bdd1243dSDimitry Andric int64_t Offset1 = ADec.Offset; 667bdd1243dSDimitry Andric int64_t Offset2 = BDec.Offset; 66881ad6265SDimitry Andric Offset1 *= -1; 66981ad6265SDimitry Andric 670bdd1243dSDimitry Andric auto &VariablesA = ADec.Vars; 671bdd1243dSDimitry Andric auto &VariablesB = BDec.Vars; 672e8d8bef9SDimitry Andric 673bdd1243dSDimitry Andric // First try to look up \p V in Value2Index and NewVariables. Otherwise add a 674bdd1243dSDimitry Andric // new entry to NewVariables. 6751db9f3b2SDimitry Andric SmallDenseMap<Value *, unsigned> NewIndexMap; 676bdd1243dSDimitry Andric auto GetOrAddIndex = [&Value2Index, &NewVariables, 677bdd1243dSDimitry Andric &NewIndexMap](Value *V) -> unsigned { 678fe6060f1SDimitry Andric auto V2I = Value2Index.find(V); 679fe6060f1SDimitry Andric if (V2I != Value2Index.end()) 680fe6060f1SDimitry Andric return V2I->second; 681fe6060f1SDimitry Andric auto Insert = 682bdd1243dSDimitry Andric NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1}); 683bdd1243dSDimitry Andric if (Insert.second) 684bdd1243dSDimitry Andric NewVariables.push_back(V); 685fe6060f1SDimitry Andric return Insert.first->second; 686e8d8bef9SDimitry Andric }; 687e8d8bef9SDimitry Andric 688bdd1243dSDimitry Andric // Make sure all variables have entries in Value2Index or NewVariables. 689bdd1243dSDimitry Andric for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB)) 690bdd1243dSDimitry Andric GetOrAddIndex(KV.Variable); 691e8d8bef9SDimitry Andric 692e8d8bef9SDimitry Andric // Build result constraint, by first adding all coefficients from A and then 693e8d8bef9SDimitry Andric // subtracting all coefficients from B. 69481ad6265SDimitry Andric ConstraintTy Res( 695bdd1243dSDimitry Andric SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0), 69606c3fb27SDimitry Andric IsSigned, IsEq, IsNe); 697bdd1243dSDimitry Andric // Collect variables that are known to be positive in all uses in the 698bdd1243dSDimitry Andric // constraint. 6991db9f3b2SDimitry Andric SmallDenseMap<Value *, bool> KnownNonNegativeVariables; 70081ad6265SDimitry Andric auto &R = Res.Coefficients; 701bdd1243dSDimitry Andric for (const auto &KV : VariablesA) { 702bdd1243dSDimitry Andric R[GetOrAddIndex(KV.Variable)] += KV.Coefficient; 703bdd1243dSDimitry Andric auto I = 704bdd1243dSDimitry Andric KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative}); 705bdd1243dSDimitry Andric I.first->second &= KV.IsKnownNonNegative; 706bdd1243dSDimitry Andric } 707e8d8bef9SDimitry Andric 708bdd1243dSDimitry Andric for (const auto &KV : VariablesB) { 70906c3fb27SDimitry Andric if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient, 71006c3fb27SDimitry Andric R[GetOrAddIndex(KV.Variable)])) 71106c3fb27SDimitry Andric return {}; 712bdd1243dSDimitry Andric auto I = 713bdd1243dSDimitry Andric KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative}); 714bdd1243dSDimitry Andric I.first->second &= KV.IsKnownNonNegative; 715bdd1243dSDimitry Andric } 716e8d8bef9SDimitry Andric 71781ad6265SDimitry Andric int64_t OffsetSum; 71881ad6265SDimitry Andric if (AddOverflow(Offset1, Offset2, OffsetSum)) 71981ad6265SDimitry Andric return {}; 72081ad6265SDimitry Andric if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT)) 72181ad6265SDimitry Andric if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum)) 72281ad6265SDimitry Andric return {}; 72381ad6265SDimitry Andric R[0] = OffsetSum; 72481ad6265SDimitry Andric Res.Preconditions = std::move(Preconditions); 725bdd1243dSDimitry Andric 726bdd1243dSDimitry Andric // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new 727bdd1243dSDimitry Andric // variables. 728bdd1243dSDimitry Andric while (!NewVariables.empty()) { 729bdd1243dSDimitry Andric int64_t Last = R.back(); 730bdd1243dSDimitry Andric if (Last != 0) 731bdd1243dSDimitry Andric break; 732bdd1243dSDimitry Andric R.pop_back(); 733bdd1243dSDimitry Andric Value *RemovedV = NewVariables.pop_back_val(); 734bdd1243dSDimitry Andric NewIndexMap.erase(RemovedV); 735bdd1243dSDimitry Andric } 736bdd1243dSDimitry Andric 737bdd1243dSDimitry Andric // Add extra constraints for variables that are known positive. 738bdd1243dSDimitry Andric for (auto &KV : KnownNonNegativeVariables) { 73906c3fb27SDimitry Andric if (!KV.second || 74006c3fb27SDimitry Andric (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first))) 741bdd1243dSDimitry Andric continue; 742bdd1243dSDimitry Andric SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0); 743bdd1243dSDimitry Andric C[GetOrAddIndex(KV.first)] = -1; 744bdd1243dSDimitry Andric Res.ExtraInfo.push_back(C); 745bdd1243dSDimitry Andric } 74681ad6265SDimitry Andric return Res; 747e8d8bef9SDimitry Andric } 748e8d8bef9SDimitry Andric 749bdd1243dSDimitry Andric ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred, 750bdd1243dSDimitry Andric Value *Op0, 751bdd1243dSDimitry Andric Value *Op1) const { 7525f757f3fSDimitry Andric Constant *NullC = Constant::getNullValue(Op0->getType()); 7535f757f3fSDimitry Andric // Handle trivially true compares directly to avoid adding V UGE 0 constraints 7545f757f3fSDimitry Andric // for all variables in the unsigned system. 7555f757f3fSDimitry Andric if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) || 7565f757f3fSDimitry Andric (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) { 7575f757f3fSDimitry Andric auto &Value2Index = getValue2Index(false); 7585f757f3fSDimitry Andric // Return constraint that's trivially true. 7595f757f3fSDimitry Andric return ConstraintTy(SmallVector<int64_t, 8>(Value2Index.size(), 0), false, 7605f757f3fSDimitry Andric false, false); 7615f757f3fSDimitry Andric } 7625f757f3fSDimitry Andric 763bdd1243dSDimitry Andric // If both operands are known to be non-negative, change signed predicates to 764bdd1243dSDimitry Andric // unsigned ones. This increases the reasoning effectiveness in combination 765bdd1243dSDimitry Andric // with the signed <-> unsigned transfer logic. 766bdd1243dSDimitry Andric if (CmpInst::isSigned(Pred) && 767bdd1243dSDimitry Andric isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) && 768bdd1243dSDimitry Andric isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 769bdd1243dSDimitry Andric Pred = CmpInst::getUnsignedPredicate(Pred); 770bdd1243dSDimitry Andric 771bdd1243dSDimitry Andric SmallVector<Value *> NewVariables; 772bdd1243dSDimitry Andric ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables); 77306c3fb27SDimitry Andric if (!NewVariables.empty()) 774bdd1243dSDimitry Andric return {}; 775bdd1243dSDimitry Andric return R; 776bdd1243dSDimitry Andric } 777bdd1243dSDimitry Andric 77881ad6265SDimitry Andric bool ConstraintTy::isValid(const ConstraintInfo &Info) const { 77981ad6265SDimitry Andric return Coefficients.size() > 0 && 7805f757f3fSDimitry Andric all_of(Preconditions, [&Info](const ConditionTy &C) { 78181ad6265SDimitry Andric return Info.doesHold(C.Pred, C.Op0, C.Op1); 78281ad6265SDimitry Andric }); 78381ad6265SDimitry Andric } 78481ad6265SDimitry Andric 78506c3fb27SDimitry Andric std::optional<bool> 78606c3fb27SDimitry Andric ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const { 78706c3fb27SDimitry Andric bool IsConditionImplied = CS.isConditionImplied(Coefficients); 78806c3fb27SDimitry Andric 78906c3fb27SDimitry Andric if (IsEq || IsNe) { 79006c3fb27SDimitry Andric auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients); 79106c3fb27SDimitry Andric bool IsNegatedOrEqualImplied = 79206c3fb27SDimitry Andric !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual); 79306c3fb27SDimitry Andric 79406c3fb27SDimitry Andric // In order to check that `%a == %b` is true (equality), both conditions `%a 79506c3fb27SDimitry Andric // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq` 79606c3fb27SDimitry Andric // is true), we return true if they both hold, false in the other cases. 79706c3fb27SDimitry Andric if (IsConditionImplied && IsNegatedOrEqualImplied) 79806c3fb27SDimitry Andric return IsEq; 79906c3fb27SDimitry Andric 80006c3fb27SDimitry Andric auto Negated = ConstraintSystem::negate(Coefficients); 80106c3fb27SDimitry Andric bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated); 80206c3fb27SDimitry Andric 80306c3fb27SDimitry Andric auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients); 80406c3fb27SDimitry Andric bool IsStrictLessThanImplied = 80506c3fb27SDimitry Andric !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan); 80606c3fb27SDimitry Andric 80706c3fb27SDimitry Andric // In order to check that `%a != %b` is true (non-equality), either 80806c3fb27SDimitry Andric // condition `%a > %b` or `%a < %b` must hold true. When checking for 80906c3fb27SDimitry Andric // non-equality (`IsNe` is true), we return true if one of the two holds, 81006c3fb27SDimitry Andric // false in the other cases. 81106c3fb27SDimitry Andric if (IsNegatedImplied || IsStrictLessThanImplied) 81206c3fb27SDimitry Andric return IsNe; 81306c3fb27SDimitry Andric 81406c3fb27SDimitry Andric return std::nullopt; 81506c3fb27SDimitry Andric } 81606c3fb27SDimitry Andric 81706c3fb27SDimitry Andric if (IsConditionImplied) 81806c3fb27SDimitry Andric return true; 81906c3fb27SDimitry Andric 82006c3fb27SDimitry Andric auto Negated = ConstraintSystem::negate(Coefficients); 82106c3fb27SDimitry Andric auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated); 82206c3fb27SDimitry Andric if (IsNegatedImplied) 82306c3fb27SDimitry Andric return false; 82406c3fb27SDimitry Andric 82506c3fb27SDimitry Andric // Neither the condition nor its negated holds, did not prove anything. 82606c3fb27SDimitry Andric return std::nullopt; 82706c3fb27SDimitry Andric } 82806c3fb27SDimitry Andric 82981ad6265SDimitry Andric bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A, 83081ad6265SDimitry Andric Value *B) const { 831bdd1243dSDimitry Andric auto R = getConstraintForSolving(Pred, A, B); 83206c3fb27SDimitry Andric return R.isValid(*this) && 833bdd1243dSDimitry Andric getCS(R.IsSigned).isConditionImplied(R.Coefficients); 83481ad6265SDimitry Andric } 83581ad6265SDimitry Andric 83681ad6265SDimitry Andric void ConstraintInfo::transferToOtherSystem( 837bdd1243dSDimitry Andric CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 83881ad6265SDimitry Andric unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) { 8395f757f3fSDimitry Andric auto IsKnownNonNegative = [this](Value *V) { 8405f757f3fSDimitry Andric return doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0)) || 8415f757f3fSDimitry Andric isKnownNonNegative(V, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1); 8425f757f3fSDimitry Andric }; 84381ad6265SDimitry Andric // Check if we can combine facts from the signed and unsigned systems to 84481ad6265SDimitry Andric // derive additional facts. 84581ad6265SDimitry Andric if (!A->getType()->isIntegerTy()) 84681ad6265SDimitry Andric return; 84781ad6265SDimitry Andric // FIXME: This currently depends on the order we add facts. Ideally we 84881ad6265SDimitry Andric // would first add all known facts and only then try to add additional 84981ad6265SDimitry Andric // facts. 85081ad6265SDimitry Andric switch (Pred) { 85181ad6265SDimitry Andric default: 85281ad6265SDimitry Andric break; 85381ad6265SDimitry Andric case CmpInst::ICMP_ULT: 8545f757f3fSDimitry Andric case CmpInst::ICMP_ULE: 8555f757f3fSDimitry Andric // If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B. 8565f757f3fSDimitry Andric if (IsKnownNonNegative(B)) { 857bdd1243dSDimitry Andric addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn, 858bdd1243dSDimitry Andric NumOut, DFSInStack); 8595f757f3fSDimitry Andric addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut, 8605f757f3fSDimitry Andric DFSInStack); 8615f757f3fSDimitry Andric } 8625f757f3fSDimitry Andric break; 8635f757f3fSDimitry Andric case CmpInst::ICMP_UGE: 8645f757f3fSDimitry Andric case CmpInst::ICMP_UGT: 8655f757f3fSDimitry Andric // If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B. 8665f757f3fSDimitry Andric if (IsKnownNonNegative(A)) { 8675f757f3fSDimitry Andric addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn, 8685f757f3fSDimitry Andric NumOut, DFSInStack); 8695f757f3fSDimitry Andric addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut, 8705f757f3fSDimitry Andric DFSInStack); 87181ad6265SDimitry Andric } 87281ad6265SDimitry Andric break; 87381ad6265SDimitry Andric case CmpInst::ICMP_SLT: 8745f757f3fSDimitry Andric if (IsKnownNonNegative(A)) 875bdd1243dSDimitry Andric addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack); 87681ad6265SDimitry Andric break; 87706c3fb27SDimitry Andric case CmpInst::ICMP_SGT: { 87881ad6265SDimitry Andric if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1))) 879bdd1243dSDimitry Andric addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn, 880bdd1243dSDimitry Andric NumOut, DFSInStack); 8815f757f3fSDimitry Andric if (IsKnownNonNegative(B)) 88206c3fb27SDimitry Andric addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack); 88306c3fb27SDimitry Andric 88481ad6265SDimitry Andric break; 88506c3fb27SDimitry Andric } 88681ad6265SDimitry Andric case CmpInst::ICMP_SGE: 8875f757f3fSDimitry Andric if (IsKnownNonNegative(B)) 888bdd1243dSDimitry Andric addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack); 88981ad6265SDimitry Andric break; 89081ad6265SDimitry Andric } 891e8d8bef9SDimitry Andric } 892e8d8bef9SDimitry Andric 893fe6060f1SDimitry Andric #ifndef NDEBUG 89481ad6265SDimitry Andric 89506c3fb27SDimitry Andric static void dumpConstraint(ArrayRef<int64_t> C, 89606c3fb27SDimitry Andric const DenseMap<Value *, unsigned> &Value2Index) { 89706c3fb27SDimitry Andric ConstraintSystem CS(Value2Index); 89881ad6265SDimitry Andric CS.addVariableRowFill(C); 89906c3fb27SDimitry Andric CS.dump(); 90081ad6265SDimitry Andric } 901fe6060f1SDimitry Andric #endif 902fe6060f1SDimitry Andric 9035f757f3fSDimitry Andric void State::addInfoForInductions(BasicBlock &BB) { 9045f757f3fSDimitry Andric auto *L = LI.getLoopFor(&BB); 9055f757f3fSDimitry Andric if (!L || L->getHeader() != &BB) 9065f757f3fSDimitry Andric return; 9075f757f3fSDimitry Andric 9085f757f3fSDimitry Andric Value *A; 9095f757f3fSDimitry Andric Value *B; 9105f757f3fSDimitry Andric CmpInst::Predicate Pred; 9115f757f3fSDimitry Andric 9125f757f3fSDimitry Andric if (!match(BB.getTerminator(), 9135f757f3fSDimitry Andric m_Br(m_ICmp(Pred, m_Value(A), m_Value(B)), m_Value(), m_Value()))) 9145f757f3fSDimitry Andric return; 9155f757f3fSDimitry Andric PHINode *PN = dyn_cast<PHINode>(A); 9165f757f3fSDimitry Andric if (!PN) { 9175f757f3fSDimitry Andric Pred = CmpInst::getSwappedPredicate(Pred); 9185f757f3fSDimitry Andric std::swap(A, B); 9195f757f3fSDimitry Andric PN = dyn_cast<PHINode>(A); 9205f757f3fSDimitry Andric } 9215f757f3fSDimitry Andric 9225f757f3fSDimitry Andric if (!PN || PN->getParent() != &BB || PN->getNumIncomingValues() != 2 || 9235f757f3fSDimitry Andric !SE.isSCEVable(PN->getType())) 9245f757f3fSDimitry Andric return; 9255f757f3fSDimitry Andric 9265f757f3fSDimitry Andric BasicBlock *InLoopSucc = nullptr; 9275f757f3fSDimitry Andric if (Pred == CmpInst::ICMP_NE) 9285f757f3fSDimitry Andric InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(0); 9295f757f3fSDimitry Andric else if (Pred == CmpInst::ICMP_EQ) 9305f757f3fSDimitry Andric InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(1); 9315f757f3fSDimitry Andric else 9325f757f3fSDimitry Andric return; 9335f757f3fSDimitry Andric 9345f757f3fSDimitry Andric if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB) 9355f757f3fSDimitry Andric return; 9365f757f3fSDimitry Andric 9375f757f3fSDimitry Andric auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN)); 9385f757f3fSDimitry Andric BasicBlock *LoopPred = L->getLoopPredecessor(); 9395f757f3fSDimitry Andric if (!AR || AR->getLoop() != L || !LoopPred) 9405f757f3fSDimitry Andric return; 9415f757f3fSDimitry Andric 9425f757f3fSDimitry Andric const SCEV *StartSCEV = AR->getStart(); 9435f757f3fSDimitry Andric Value *StartValue = nullptr; 9445f757f3fSDimitry Andric if (auto *C = dyn_cast<SCEVConstant>(StartSCEV)) { 9455f757f3fSDimitry Andric StartValue = C->getValue(); 9465f757f3fSDimitry Andric } else { 9475f757f3fSDimitry Andric StartValue = PN->getIncomingValueForBlock(LoopPred); 9485f757f3fSDimitry Andric assert(SE.getSCEV(StartValue) == StartSCEV && "inconsistent start value"); 9495f757f3fSDimitry Andric } 9505f757f3fSDimitry Andric 9515f757f3fSDimitry Andric DomTreeNode *DTN = DT.getNode(InLoopSucc); 9521db9f3b2SDimitry Andric auto IncUnsigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_UGT); 9531db9f3b2SDimitry Andric auto IncSigned = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_SGT); 9541db9f3b2SDimitry Andric bool MonotonicallyIncreasingUnsigned = 9551db9f3b2SDimitry Andric IncUnsigned && *IncUnsigned == ScalarEvolution::MonotonicallyIncreasing; 9561db9f3b2SDimitry Andric bool MonotonicallyIncreasingSigned = 9571db9f3b2SDimitry Andric IncSigned && *IncSigned == ScalarEvolution::MonotonicallyIncreasing; 9581db9f3b2SDimitry Andric // If SCEV guarantees that AR does not wrap, PN >= StartValue can be added 9595f757f3fSDimitry Andric // unconditionally. 9601db9f3b2SDimitry Andric if (MonotonicallyIncreasingUnsigned) 9615f757f3fSDimitry Andric WorkList.push_back( 9625f757f3fSDimitry Andric FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGE, PN, StartValue)); 9631db9f3b2SDimitry Andric if (MonotonicallyIncreasingSigned) 9641db9f3b2SDimitry Andric WorkList.push_back( 9651db9f3b2SDimitry Andric FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_SGE, PN, StartValue)); 9665f757f3fSDimitry Andric 9675f757f3fSDimitry Andric APInt StepOffset; 9685f757f3fSDimitry Andric if (auto *C = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 9695f757f3fSDimitry Andric StepOffset = C->getAPInt(); 9705f757f3fSDimitry Andric else 9715f757f3fSDimitry Andric return; 9725f757f3fSDimitry Andric 9735f757f3fSDimitry Andric // Make sure the bound B is loop-invariant. 9745f757f3fSDimitry Andric if (!L->isLoopInvariant(B)) 9755f757f3fSDimitry Andric return; 9765f757f3fSDimitry Andric 9775f757f3fSDimitry Andric // Handle negative steps. 9785f757f3fSDimitry Andric if (StepOffset.isNegative()) { 9795f757f3fSDimitry Andric // TODO: Extend to allow steps > -1. 9805f757f3fSDimitry Andric if (!(-StepOffset).isOne()) 9815f757f3fSDimitry Andric return; 9825f757f3fSDimitry Andric 9835f757f3fSDimitry Andric // AR may wrap. 9845f757f3fSDimitry Andric // Add StartValue >= PN conditional on B <= StartValue which guarantees that 9855f757f3fSDimitry Andric // the loop exits before wrapping with a step of -1. 9865f757f3fSDimitry Andric WorkList.push_back(FactOrCheck::getConditionFact( 9875f757f3fSDimitry Andric DTN, CmpInst::ICMP_UGE, StartValue, PN, 9885f757f3fSDimitry Andric ConditionTy(CmpInst::ICMP_ULE, B, StartValue))); 9891db9f3b2SDimitry Andric WorkList.push_back(FactOrCheck::getConditionFact( 9901db9f3b2SDimitry Andric DTN, CmpInst::ICMP_SGE, StartValue, PN, 9911db9f3b2SDimitry Andric ConditionTy(CmpInst::ICMP_SLE, B, StartValue))); 9925f757f3fSDimitry Andric // Add PN > B conditional on B <= StartValue which guarantees that the loop 9935f757f3fSDimitry Andric // exits when reaching B with a step of -1. 9945f757f3fSDimitry Andric WorkList.push_back(FactOrCheck::getConditionFact( 9955f757f3fSDimitry Andric DTN, CmpInst::ICMP_UGT, PN, B, 9965f757f3fSDimitry Andric ConditionTy(CmpInst::ICMP_ULE, B, StartValue))); 9971db9f3b2SDimitry Andric WorkList.push_back(FactOrCheck::getConditionFact( 9981db9f3b2SDimitry Andric DTN, CmpInst::ICMP_SGT, PN, B, 9991db9f3b2SDimitry Andric ConditionTy(CmpInst::ICMP_SLE, B, StartValue))); 10005f757f3fSDimitry Andric return; 10015f757f3fSDimitry Andric } 10025f757f3fSDimitry Andric 10035f757f3fSDimitry Andric // Make sure AR either steps by 1 or that the value we compare against is a 10045f757f3fSDimitry Andric // GEP based on the same start value and all offsets are a multiple of the 10055f757f3fSDimitry Andric // step size, to guarantee that the induction will reach the value. 10065f757f3fSDimitry Andric if (StepOffset.isZero() || StepOffset.isNegative()) 10075f757f3fSDimitry Andric return; 10085f757f3fSDimitry Andric 10095f757f3fSDimitry Andric if (!StepOffset.isOne()) { 10101db9f3b2SDimitry Andric // Check whether B-Start is known to be a multiple of StepOffset. 10111db9f3b2SDimitry Andric const SCEV *BMinusStart = SE.getMinusSCEV(SE.getSCEV(B), StartSCEV); 10121db9f3b2SDimitry Andric if (isa<SCEVCouldNotCompute>(BMinusStart) || 10131db9f3b2SDimitry Andric !SE.getConstantMultiple(BMinusStart).urem(StepOffset).isZero()) 10145f757f3fSDimitry Andric return; 10155f757f3fSDimitry Andric } 10165f757f3fSDimitry Andric 10175f757f3fSDimitry Andric // AR may wrap. Add PN >= StartValue conditional on StartValue <= B which 10185f757f3fSDimitry Andric // guarantees that the loop exits before wrapping in combination with the 10195f757f3fSDimitry Andric // restrictions on B and the step above. 10201db9f3b2SDimitry Andric if (!MonotonicallyIncreasingUnsigned) 10215f757f3fSDimitry Andric WorkList.push_back(FactOrCheck::getConditionFact( 10225f757f3fSDimitry Andric DTN, CmpInst::ICMP_UGE, PN, StartValue, 10235f757f3fSDimitry Andric ConditionTy(CmpInst::ICMP_ULE, StartValue, B))); 10241db9f3b2SDimitry Andric if (!MonotonicallyIncreasingSigned) 10251db9f3b2SDimitry Andric WorkList.push_back(FactOrCheck::getConditionFact( 10261db9f3b2SDimitry Andric DTN, CmpInst::ICMP_SGE, PN, StartValue, 10271db9f3b2SDimitry Andric ConditionTy(CmpInst::ICMP_SLE, StartValue, B))); 10281db9f3b2SDimitry Andric 10295f757f3fSDimitry Andric WorkList.push_back(FactOrCheck::getConditionFact( 10305f757f3fSDimitry Andric DTN, CmpInst::ICMP_ULT, PN, B, 10315f757f3fSDimitry Andric ConditionTy(CmpInst::ICMP_ULE, StartValue, B))); 10321db9f3b2SDimitry Andric WorkList.push_back(FactOrCheck::getConditionFact( 10331db9f3b2SDimitry Andric DTN, CmpInst::ICMP_SLT, PN, B, 10341db9f3b2SDimitry Andric ConditionTy(CmpInst::ICMP_SLE, StartValue, B))); 10350fca6ea1SDimitry Andric 1036*71ac745dSDimitry Andric // Try to add condition from header to the dedicated exit blocks. When exiting 1037*71ac745dSDimitry Andric // either with EQ or NE in the header, we know that the induction value must 1038*71ac745dSDimitry Andric // be u<= B, as other exits may only exit earlier. 10390fca6ea1SDimitry Andric assert(!StepOffset.isNegative() && "induction must be increasing"); 10400fca6ea1SDimitry Andric assert((Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) && 10410fca6ea1SDimitry Andric "unsupported predicate"); 10420fca6ea1SDimitry Andric ConditionTy Precond = {CmpInst::ICMP_ULE, StartValue, B}; 10430fca6ea1SDimitry Andric SmallVector<BasicBlock *> ExitBBs; 10440fca6ea1SDimitry Andric L->getExitBlocks(ExitBBs); 10450fca6ea1SDimitry Andric for (BasicBlock *EB : ExitBBs) { 1046*71ac745dSDimitry Andric // Bail out on non-dedicated exits. 1047*71ac745dSDimitry Andric if (DT.dominates(&BB, EB)) { 10480fca6ea1SDimitry Andric WorkList.emplace_back(FactOrCheck::getConditionFact( 10490fca6ea1SDimitry Andric DT.getNode(EB), CmpInst::ICMP_ULE, A, B, Precond)); 10500fca6ea1SDimitry Andric } 10515f757f3fSDimitry Andric } 1052*71ac745dSDimitry Andric } 10535f757f3fSDimitry Andric 105481ad6265SDimitry Andric void State::addInfoFor(BasicBlock &BB) { 10555f757f3fSDimitry Andric addInfoForInductions(BB); 10565f757f3fSDimitry Andric 1057349cc55cSDimitry Andric // True as long as long as the current instruction is guaranteed to execute. 1058349cc55cSDimitry Andric bool GuaranteedToExecute = true; 1059bdd1243dSDimitry Andric // Queue conditions and assumes. 1060349cc55cSDimitry Andric for (Instruction &I : BB) { 1061bdd1243dSDimitry Andric if (auto Cmp = dyn_cast<ICmpInst>(&I)) { 106206c3fb27SDimitry Andric for (Use &U : Cmp->uses()) { 106306c3fb27SDimitry Andric auto *UserI = getContextInstForUse(U); 106406c3fb27SDimitry Andric auto *DTN = DT.getNode(UserI->getParent()); 106506c3fb27SDimitry Andric if (!DTN) 106606c3fb27SDimitry Andric continue; 106706c3fb27SDimitry Andric WorkList.push_back(FactOrCheck::getCheck(DTN, &U)); 106806c3fb27SDimitry Andric } 1069bdd1243dSDimitry Andric continue; 1070bdd1243dSDimitry Andric } 1071bdd1243dSDimitry Andric 1072647cbc5dSDimitry Andric auto *II = dyn_cast<IntrinsicInst>(&I); 1073647cbc5dSDimitry Andric Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic; 1074647cbc5dSDimitry Andric switch (ID) { 1075647cbc5dSDimitry Andric case Intrinsic::assume: { 10765f757f3fSDimitry Andric Value *A, *B; 10775f757f3fSDimitry Andric CmpInst::Predicate Pred; 1078647cbc5dSDimitry Andric if (!match(I.getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B)))) 1079647cbc5dSDimitry Andric break; 1080349cc55cSDimitry Andric if (GuaranteedToExecute) { 1081349cc55cSDimitry Andric // The assume is guaranteed to execute when BB is entered, hence Cond 1082349cc55cSDimitry Andric // holds on entry to BB. 10835f757f3fSDimitry Andric WorkList.emplace_back(FactOrCheck::getConditionFact( 10845f757f3fSDimitry Andric DT.getNode(I.getParent()), Pred, A, B)); 1085349cc55cSDimitry Andric } else { 1086bdd1243dSDimitry Andric WorkList.emplace_back( 10875f757f3fSDimitry Andric FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I)); 1088349cc55cSDimitry Andric } 1089647cbc5dSDimitry Andric break; 1090349cc55cSDimitry Andric } 1091647cbc5dSDimitry Andric // Enqueue ssub_with_overflow for simplification. 1092647cbc5dSDimitry Andric case Intrinsic::ssub_with_overflow: 10930fca6ea1SDimitry Andric case Intrinsic::ucmp: 10940fca6ea1SDimitry Andric case Intrinsic::scmp: 1095647cbc5dSDimitry Andric WorkList.push_back( 1096647cbc5dSDimitry Andric FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I))); 1097647cbc5dSDimitry Andric break; 1098647cbc5dSDimitry Andric // Enqueue the intrinsics to add extra info. 1099647cbc5dSDimitry Andric case Intrinsic::umin: 1100647cbc5dSDimitry Andric case Intrinsic::umax: 1101647cbc5dSDimitry Andric case Intrinsic::smin: 1102647cbc5dSDimitry Andric case Intrinsic::smax: 11030fca6ea1SDimitry Andric // TODO: handle llvm.abs as well 11040fca6ea1SDimitry Andric WorkList.push_back( 11050fca6ea1SDimitry Andric FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I))); 1106b3edf446SDimitry Andric // TODO: Check if it is possible to instead only added the min/max facts 1107b3edf446SDimitry Andric // when simplifying uses of the min/max intrinsics. 1108b3edf446SDimitry Andric if (!isGuaranteedNotToBePoison(&I)) 1109b3edf446SDimitry Andric break; 1110b3edf446SDimitry Andric [[fallthrough]]; 1111b3edf446SDimitry Andric case Intrinsic::abs: 1112647cbc5dSDimitry Andric WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I)); 1113647cbc5dSDimitry Andric break; 1114647cbc5dSDimitry Andric } 1115647cbc5dSDimitry Andric 1116349cc55cSDimitry Andric GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I); 1117349cc55cSDimitry Andric } 1118349cc55cSDimitry Andric 11195f757f3fSDimitry Andric if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) { 11205f757f3fSDimitry Andric for (auto &Case : Switch->cases()) { 11215f757f3fSDimitry Andric BasicBlock *Succ = Case.getCaseSuccessor(); 11225f757f3fSDimitry Andric Value *V = Case.getCaseValue(); 11235f757f3fSDimitry Andric if (!canAddSuccessor(BB, Succ)) 11245f757f3fSDimitry Andric continue; 11255f757f3fSDimitry Andric WorkList.emplace_back(FactOrCheck::getConditionFact( 11265f757f3fSDimitry Andric DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V)); 11275f757f3fSDimitry Andric } 11285f757f3fSDimitry Andric return; 11295f757f3fSDimitry Andric } 11305f757f3fSDimitry Andric 1131e8d8bef9SDimitry Andric auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 1132e8d8bef9SDimitry Andric if (!Br || !Br->isConditional()) 113381ad6265SDimitry Andric return; 1134e8d8bef9SDimitry Andric 1135bdd1243dSDimitry Andric Value *Cond = Br->getCondition(); 1136e8d8bef9SDimitry Andric 1137bdd1243dSDimitry Andric // If the condition is a chain of ORs/AND and the successor only has the 1138bdd1243dSDimitry Andric // current block as predecessor, queue conditions for the successor. 1139bdd1243dSDimitry Andric Value *Op0, *Op1; 1140bdd1243dSDimitry Andric if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) || 1141bdd1243dSDimitry Andric match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 1142bdd1243dSDimitry Andric bool IsOr = match(Cond, m_LogicalOr()); 1143bdd1243dSDimitry Andric bool IsAnd = match(Cond, m_LogicalAnd()); 1144bdd1243dSDimitry Andric // If there's a select that matches both AND and OR, we need to commit to 1145bdd1243dSDimitry Andric // one of the options. Arbitrarily pick OR. 1146bdd1243dSDimitry Andric if (IsOr && IsAnd) 1147bdd1243dSDimitry Andric IsAnd = false; 1148bdd1243dSDimitry Andric 1149bdd1243dSDimitry Andric BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0); 1150bdd1243dSDimitry Andric if (canAddSuccessor(BB, Successor)) { 1151bdd1243dSDimitry Andric SmallVector<Value *> CondWorkList; 1152bdd1243dSDimitry Andric SmallPtrSet<Value *, 8> SeenCond; 1153bdd1243dSDimitry Andric auto QueueValue = [&CondWorkList, &SeenCond](Value *V) { 1154bdd1243dSDimitry Andric if (SeenCond.insert(V).second) 1155bdd1243dSDimitry Andric CondWorkList.push_back(V); 1156bdd1243dSDimitry Andric }; 1157bdd1243dSDimitry Andric QueueValue(Op1); 1158bdd1243dSDimitry Andric QueueValue(Op0); 1159bdd1243dSDimitry Andric while (!CondWorkList.empty()) { 1160bdd1243dSDimitry Andric Value *Cur = CondWorkList.pop_back_val(); 1161bdd1243dSDimitry Andric if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) { 11625f757f3fSDimitry Andric WorkList.emplace_back(FactOrCheck::getConditionFact( 11635f757f3fSDimitry Andric DT.getNode(Successor), 11645f757f3fSDimitry Andric IsOr ? CmpInst::getInversePredicate(Cmp->getPredicate()) 11655f757f3fSDimitry Andric : Cmp->getPredicate(), 11665f757f3fSDimitry Andric Cmp->getOperand(0), Cmp->getOperand(1))); 1167bdd1243dSDimitry Andric continue; 1168bdd1243dSDimitry Andric } 1169bdd1243dSDimitry Andric if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 1170bdd1243dSDimitry Andric QueueValue(Op1); 1171bdd1243dSDimitry Andric QueueValue(Op0); 1172bdd1243dSDimitry Andric continue; 1173bdd1243dSDimitry Andric } 1174bdd1243dSDimitry Andric if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 1175bdd1243dSDimitry Andric QueueValue(Op1); 1176bdd1243dSDimitry Andric QueueValue(Op0); 1177bdd1243dSDimitry Andric continue; 1178bdd1243dSDimitry Andric } 1179bdd1243dSDimitry Andric } 1180e8d8bef9SDimitry Andric } 118181ad6265SDimitry Andric return; 1182e8d8bef9SDimitry Andric } 1183e8d8bef9SDimitry Andric 118481ad6265SDimitry Andric auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition()); 1185e8d8bef9SDimitry Andric if (!CmpI) 118681ad6265SDimitry Andric return; 118781ad6265SDimitry Andric if (canAddSuccessor(BB, Br->getSuccessor(0))) 11885f757f3fSDimitry Andric WorkList.emplace_back(FactOrCheck::getConditionFact( 11895f757f3fSDimitry Andric DT.getNode(Br->getSuccessor(0)), CmpI->getPredicate(), 11905f757f3fSDimitry Andric CmpI->getOperand(0), CmpI->getOperand(1))); 119181ad6265SDimitry Andric if (canAddSuccessor(BB, Br->getSuccessor(1))) 11925f757f3fSDimitry Andric WorkList.emplace_back(FactOrCheck::getConditionFact( 11935f757f3fSDimitry Andric DT.getNode(Br->getSuccessor(1)), 11945f757f3fSDimitry Andric CmpInst::getInversePredicate(CmpI->getPredicate()), CmpI->getOperand(0), 11955f757f3fSDimitry Andric CmpI->getOperand(1))); 1196bdd1243dSDimitry Andric } 1197bdd1243dSDimitry Andric 11985f757f3fSDimitry Andric #ifndef NDEBUG 11995f757f3fSDimitry Andric static void dumpUnpackedICmp(raw_ostream &OS, ICmpInst::Predicate Pred, 12005f757f3fSDimitry Andric Value *LHS, Value *RHS) { 12015f757f3fSDimitry Andric OS << "icmp " << Pred << ' '; 12025f757f3fSDimitry Andric LHS->printAsOperand(OS, /*PrintType=*/true); 12035f757f3fSDimitry Andric OS << ", "; 12045f757f3fSDimitry Andric RHS->printAsOperand(OS, /*PrintType=*/false); 12055f757f3fSDimitry Andric } 12065f757f3fSDimitry Andric #endif 12075f757f3fSDimitry Andric 120806c3fb27SDimitry Andric namespace { 120906c3fb27SDimitry Andric /// Helper to keep track of a condition and if it should be treated as negated 121006c3fb27SDimitry Andric /// for reproducer construction. 121106c3fb27SDimitry Andric /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a 121206c3fb27SDimitry Andric /// placeholder to keep the ReproducerCondStack in sync with DFSInStack. 121306c3fb27SDimitry Andric struct ReproducerEntry { 121406c3fb27SDimitry Andric ICmpInst::Predicate Pred; 121506c3fb27SDimitry Andric Value *LHS; 121606c3fb27SDimitry Andric Value *RHS; 121706c3fb27SDimitry Andric 121806c3fb27SDimitry Andric ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS) 121906c3fb27SDimitry Andric : Pred(Pred), LHS(LHS), RHS(RHS) {} 122006c3fb27SDimitry Andric }; 122106c3fb27SDimitry Andric } // namespace 122206c3fb27SDimitry Andric 122306c3fb27SDimitry Andric /// Helper function to generate a reproducer function for simplifying \p Cond. 122406c3fb27SDimitry Andric /// The reproducer function contains a series of @llvm.assume calls, one for 122506c3fb27SDimitry Andric /// each condition in \p Stack. For each condition, the operand instruction are 122606c3fb27SDimitry Andric /// cloned until we reach operands that have an entry in \p Value2Index. Those 122706c3fb27SDimitry Andric /// will then be added as function arguments. \p DT is used to order cloned 122806c3fb27SDimitry Andric /// instructions. The reproducer function will get added to \p M, if it is 122906c3fb27SDimitry Andric /// non-null. Otherwise no reproducer function is generated. 123006c3fb27SDimitry Andric static void generateReproducer(CmpInst *Cond, Module *M, 123106c3fb27SDimitry Andric ArrayRef<ReproducerEntry> Stack, 123206c3fb27SDimitry Andric ConstraintInfo &Info, DominatorTree &DT) { 123306c3fb27SDimitry Andric if (!M) 123406c3fb27SDimitry Andric return; 123506c3fb27SDimitry Andric 123606c3fb27SDimitry Andric LLVMContext &Ctx = Cond->getContext(); 123706c3fb27SDimitry Andric 123806c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n"); 123906c3fb27SDimitry Andric 124006c3fb27SDimitry Andric ValueToValueMapTy Old2New; 124106c3fb27SDimitry Andric SmallVector<Value *> Args; 124206c3fb27SDimitry Andric SmallPtrSet<Value *, 8> Seen; 124306c3fb27SDimitry Andric // Traverse Cond and its operands recursively until we reach a value that's in 124406c3fb27SDimitry Andric // Value2Index or not an instruction, or not a operation that 124506c3fb27SDimitry Andric // ConstraintElimination can decompose. Such values will be considered as 124606c3fb27SDimitry Andric // external inputs to the reproducer, they are collected and added as function 124706c3fb27SDimitry Andric // arguments later. 124806c3fb27SDimitry Andric auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) { 124906c3fb27SDimitry Andric auto &Value2Index = Info.getValue2Index(IsSigned); 125006c3fb27SDimitry Andric SmallVector<Value *, 4> WorkList(Ops); 125106c3fb27SDimitry Andric while (!WorkList.empty()) { 125206c3fb27SDimitry Andric Value *V = WorkList.pop_back_val(); 125306c3fb27SDimitry Andric if (!Seen.insert(V).second) 125406c3fb27SDimitry Andric continue; 125506c3fb27SDimitry Andric if (Old2New.find(V) != Old2New.end()) 125606c3fb27SDimitry Andric continue; 125706c3fb27SDimitry Andric if (isa<Constant>(V)) 125806c3fb27SDimitry Andric continue; 125906c3fb27SDimitry Andric 126006c3fb27SDimitry Andric auto *I = dyn_cast<Instruction>(V); 126106c3fb27SDimitry Andric if (Value2Index.contains(V) || !I || 126206c3fb27SDimitry Andric !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) { 126306c3fb27SDimitry Andric Old2New[V] = V; 126406c3fb27SDimitry Andric Args.push_back(V); 126506c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << " found external input " << *V << "\n"); 126606c3fb27SDimitry Andric } else { 126706c3fb27SDimitry Andric append_range(WorkList, I->operands()); 126806c3fb27SDimitry Andric } 126906c3fb27SDimitry Andric } 127006c3fb27SDimitry Andric }; 127106c3fb27SDimitry Andric 127206c3fb27SDimitry Andric for (auto &Entry : Stack) 127306c3fb27SDimitry Andric if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE) 127406c3fb27SDimitry Andric CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred)); 127506c3fb27SDimitry Andric CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate())); 127606c3fb27SDimitry Andric 127706c3fb27SDimitry Andric SmallVector<Type *> ParamTys; 127806c3fb27SDimitry Andric for (auto *P : Args) 127906c3fb27SDimitry Andric ParamTys.push_back(P->getType()); 128006c3fb27SDimitry Andric 128106c3fb27SDimitry Andric FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys, 128206c3fb27SDimitry Andric /*isVarArg=*/false); 128306c3fb27SDimitry Andric Function *F = Function::Create(FTy, Function::ExternalLinkage, 128406c3fb27SDimitry Andric Cond->getModule()->getName() + 128506c3fb27SDimitry Andric Cond->getFunction()->getName() + "repro", 128606c3fb27SDimitry Andric M); 128706c3fb27SDimitry Andric // Add arguments to the reproducer function for each external value collected. 128806c3fb27SDimitry Andric for (unsigned I = 0; I < Args.size(); ++I) { 128906c3fb27SDimitry Andric F->getArg(I)->setName(Args[I]->getName()); 129006c3fb27SDimitry Andric Old2New[Args[I]] = F->getArg(I); 129106c3fb27SDimitry Andric } 129206c3fb27SDimitry Andric 129306c3fb27SDimitry Andric BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F); 129406c3fb27SDimitry Andric IRBuilder<> Builder(Entry); 129506c3fb27SDimitry Andric Builder.CreateRet(Builder.getTrue()); 129606c3fb27SDimitry Andric Builder.SetInsertPoint(Entry->getTerminator()); 129706c3fb27SDimitry Andric 129806c3fb27SDimitry Andric // Clone instructions in \p Ops and their operands recursively until reaching 129906c3fb27SDimitry Andric // an value in Value2Index (external input to the reproducer). Update Old2New 130006c3fb27SDimitry Andric // mapping for the original and cloned instructions. Sort instructions to 130106c3fb27SDimitry Andric // clone by dominance, then insert the cloned instructions in the function. 130206c3fb27SDimitry Andric auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) { 130306c3fb27SDimitry Andric SmallVector<Value *, 4> WorkList(Ops); 130406c3fb27SDimitry Andric SmallVector<Instruction *> ToClone; 130506c3fb27SDimitry Andric auto &Value2Index = Info.getValue2Index(IsSigned); 130606c3fb27SDimitry Andric while (!WorkList.empty()) { 130706c3fb27SDimitry Andric Value *V = WorkList.pop_back_val(); 130806c3fb27SDimitry Andric if (Old2New.find(V) != Old2New.end()) 130906c3fb27SDimitry Andric continue; 131006c3fb27SDimitry Andric 131106c3fb27SDimitry Andric auto *I = dyn_cast<Instruction>(V); 131206c3fb27SDimitry Andric if (!Value2Index.contains(V) && I) { 131306c3fb27SDimitry Andric Old2New[V] = nullptr; 131406c3fb27SDimitry Andric ToClone.push_back(I); 131506c3fb27SDimitry Andric append_range(WorkList, I->operands()); 131606c3fb27SDimitry Andric } 131706c3fb27SDimitry Andric } 131806c3fb27SDimitry Andric 131906c3fb27SDimitry Andric sort(ToClone, 132006c3fb27SDimitry Andric [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); }); 132106c3fb27SDimitry Andric for (Instruction *I : ToClone) { 132206c3fb27SDimitry Andric Instruction *Cloned = I->clone(); 132306c3fb27SDimitry Andric Old2New[I] = Cloned; 132406c3fb27SDimitry Andric Old2New[I]->setName(I->getName()); 132506c3fb27SDimitry Andric Cloned->insertBefore(&*Builder.GetInsertPoint()); 132606c3fb27SDimitry Andric Cloned->dropUnknownNonDebugMetadata(); 132706c3fb27SDimitry Andric Cloned->setDebugLoc({}); 132806c3fb27SDimitry Andric } 132906c3fb27SDimitry Andric }; 133006c3fb27SDimitry Andric 133106c3fb27SDimitry Andric // Materialize the assumptions for the reproducer using the entries in Stack. 133206c3fb27SDimitry Andric // That is, first clone the operands of the condition recursively until we 133306c3fb27SDimitry Andric // reach an external input to the reproducer and add them to the reproducer 133406c3fb27SDimitry Andric // function. Then add an ICmp for the condition (with the inverse predicate if 133506c3fb27SDimitry Andric // the entry is negated) and an assert using the ICmp. 133606c3fb27SDimitry Andric for (auto &Entry : Stack) { 133706c3fb27SDimitry Andric if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE) 133806c3fb27SDimitry Andric continue; 133906c3fb27SDimitry Andric 13405f757f3fSDimitry Andric LLVM_DEBUG(dbgs() << " Materializing assumption "; 13415f757f3fSDimitry Andric dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS); 13425f757f3fSDimitry Andric dbgs() << "\n"); 134306c3fb27SDimitry Andric CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred)); 134406c3fb27SDimitry Andric 134506c3fb27SDimitry Andric auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS); 134606c3fb27SDimitry Andric Builder.CreateAssumption(Cmp); 134706c3fb27SDimitry Andric } 134806c3fb27SDimitry Andric 134906c3fb27SDimitry Andric // Finally, clone the condition to reproduce and remap instruction operands in 135006c3fb27SDimitry Andric // the reproducer using Old2New. 135106c3fb27SDimitry Andric CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate())); 135206c3fb27SDimitry Andric Entry->getTerminator()->setOperand(0, Cond); 135306c3fb27SDimitry Andric remapInstructionsInBlocks({Entry}, Old2New); 135406c3fb27SDimitry Andric 135506c3fb27SDimitry Andric assert(!verifyFunction(*F, &dbgs())); 135606c3fb27SDimitry Andric } 135706c3fb27SDimitry Andric 13585f757f3fSDimitry Andric static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A, 13595f757f3fSDimitry Andric Value *B, Instruction *CheckInst, 13607a6dacacSDimitry Andric ConstraintInfo &Info) { 13615f757f3fSDimitry Andric LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n"); 1362bdd1243dSDimitry Andric 1363bdd1243dSDimitry Andric auto R = Info.getConstraintForSolving(Pred, A, B); 1364bdd1243dSDimitry Andric if (R.empty() || !R.isValid(Info)){ 1365bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << " failed to decompose condition\n"); 136606c3fb27SDimitry Andric return std::nullopt; 1367bdd1243dSDimitry Andric } 1368bdd1243dSDimitry Andric 1369bdd1243dSDimitry Andric auto &CSToUse = Info.getCS(R.IsSigned); 1370bdd1243dSDimitry Andric 1371bdd1243dSDimitry Andric // If there was extra information collected during decomposition, apply 1372bdd1243dSDimitry Andric // it now and remove it immediately once we are done with reasoning 1373bdd1243dSDimitry Andric // about the constraint. 1374bdd1243dSDimitry Andric for (auto &Row : R.ExtraInfo) 1375bdd1243dSDimitry Andric CSToUse.addVariableRow(Row); 1376bdd1243dSDimitry Andric auto InfoRestorer = make_scope_exit([&]() { 1377bdd1243dSDimitry Andric for (unsigned I = 0; I < R.ExtraInfo.size(); ++I) 1378bdd1243dSDimitry Andric CSToUse.popLastConstraint(); 1379bdd1243dSDimitry Andric }); 1380bdd1243dSDimitry Andric 138106c3fb27SDimitry Andric if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) { 1382bdd1243dSDimitry Andric if (!DebugCounter::shouldExecute(EliminatedCounter)) 138306c3fb27SDimitry Andric return std::nullopt; 1384bdd1243dSDimitry Andric 1385bdd1243dSDimitry Andric LLVM_DEBUG({ 13865f757f3fSDimitry Andric dbgs() << "Condition "; 13875f757f3fSDimitry Andric dumpUnpackedICmp( 13885f757f3fSDimitry Andric dbgs(), *ImpliedCondition ? Pred : CmpInst::getInversePredicate(Pred), 13895f757f3fSDimitry Andric A, B); 139006c3fb27SDimitry Andric dbgs() << " implied by dominating constraints\n"; 139106c3fb27SDimitry Andric CSToUse.dump(); 1392bdd1243dSDimitry Andric }); 139306c3fb27SDimitry Andric return ImpliedCondition; 139406c3fb27SDimitry Andric } 139506c3fb27SDimitry Andric 139606c3fb27SDimitry Andric return std::nullopt; 139706c3fb27SDimitry Andric } 139806c3fb27SDimitry Andric 139906c3fb27SDimitry Andric static bool checkAndReplaceCondition( 140006c3fb27SDimitry Andric CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut, 140106c3fb27SDimitry Andric Instruction *ContextInst, Module *ReproducerModule, 14025f757f3fSDimitry Andric ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT, 14035f757f3fSDimitry Andric SmallVectorImpl<Instruction *> &ToRemove) { 140406c3fb27SDimitry Andric auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) { 140506c3fb27SDimitry Andric generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT); 140606c3fb27SDimitry Andric Constant *ConstantC = ConstantInt::getBool( 140706c3fb27SDimitry Andric CmpInst::makeCmpResultType(Cmp->getType()), IsTrue); 140806c3fb27SDimitry Andric Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut, 140906c3fb27SDimitry Andric ContextInst](Use &U) { 141006c3fb27SDimitry Andric auto *UserI = getContextInstForUse(U); 141106c3fb27SDimitry Andric auto *DTN = DT.getNode(UserI->getParent()); 141206c3fb27SDimitry Andric if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut) 141306c3fb27SDimitry Andric return false; 141406c3fb27SDimitry Andric if (UserI->getParent() == ContextInst->getParent() && 141506c3fb27SDimitry Andric UserI->comesBefore(ContextInst)) 141606c3fb27SDimitry Andric return false; 141706c3fb27SDimitry Andric 1418bdd1243dSDimitry Andric // Conditions in an assume trivially simplify to true. Skip uses 1419bdd1243dSDimitry Andric // in assume calls to not destroy the available information. 1420bdd1243dSDimitry Andric auto *II = dyn_cast<IntrinsicInst>(U.getUser()); 1421bdd1243dSDimitry Andric return !II || II->getIntrinsicID() != Intrinsic::assume; 1422bdd1243dSDimitry Andric }); 1423bdd1243dSDimitry Andric NumCondsRemoved++; 14245f757f3fSDimitry Andric if (Cmp->use_empty()) 14255f757f3fSDimitry Andric ToRemove.push_back(Cmp); 142606c3fb27SDimitry Andric return true; 142706c3fb27SDimitry Andric }; 142806c3fb27SDimitry Andric 14297a6dacacSDimitry Andric if (auto ImpliedCondition = 14307a6dacacSDimitry Andric checkCondition(Cmp->getPredicate(), Cmp->getOperand(0), 14317a6dacacSDimitry Andric Cmp->getOperand(1), Cmp, Info)) 143206c3fb27SDimitry Andric return ReplaceCmpWithConstant(Cmp, *ImpliedCondition); 143306c3fb27SDimitry Andric return false; 1434bdd1243dSDimitry Andric } 143506c3fb27SDimitry Andric 14360fca6ea1SDimitry Andric static bool checkAndReplaceMinMax(MinMaxIntrinsic *MinMax, ConstraintInfo &Info, 14370fca6ea1SDimitry Andric SmallVectorImpl<Instruction *> &ToRemove) { 14380fca6ea1SDimitry Andric auto ReplaceMinMaxWithOperand = [&](MinMaxIntrinsic *MinMax, bool UseLHS) { 14390fca6ea1SDimitry Andric // TODO: generate reproducer for min/max. 14400fca6ea1SDimitry Andric MinMax->replaceAllUsesWith(MinMax->getOperand(UseLHS ? 0 : 1)); 14410fca6ea1SDimitry Andric ToRemove.push_back(MinMax); 14420fca6ea1SDimitry Andric return true; 14430fca6ea1SDimitry Andric }; 14440fca6ea1SDimitry Andric 14450fca6ea1SDimitry Andric ICmpInst::Predicate Pred = 14460fca6ea1SDimitry Andric ICmpInst::getNonStrictPredicate(MinMax->getPredicate()); 14470fca6ea1SDimitry Andric if (auto ImpliedCondition = checkCondition( 14480fca6ea1SDimitry Andric Pred, MinMax->getOperand(0), MinMax->getOperand(1), MinMax, Info)) 14490fca6ea1SDimitry Andric return ReplaceMinMaxWithOperand(MinMax, *ImpliedCondition); 14500fca6ea1SDimitry Andric if (auto ImpliedCondition = checkCondition( 14510fca6ea1SDimitry Andric Pred, MinMax->getOperand(1), MinMax->getOperand(0), MinMax, Info)) 14520fca6ea1SDimitry Andric return ReplaceMinMaxWithOperand(MinMax, !*ImpliedCondition); 14530fca6ea1SDimitry Andric return false; 14540fca6ea1SDimitry Andric } 14550fca6ea1SDimitry Andric 14560fca6ea1SDimitry Andric static bool checkAndReplaceCmp(CmpIntrinsic *I, ConstraintInfo &Info, 14570fca6ea1SDimitry Andric SmallVectorImpl<Instruction *> &ToRemove) { 14580fca6ea1SDimitry Andric Value *LHS = I->getOperand(0); 14590fca6ea1SDimitry Andric Value *RHS = I->getOperand(1); 14600fca6ea1SDimitry Andric if (checkCondition(I->getGTPredicate(), LHS, RHS, I, Info).value_or(false)) { 14610fca6ea1SDimitry Andric I->replaceAllUsesWith(ConstantInt::get(I->getType(), 1)); 14620fca6ea1SDimitry Andric ToRemove.push_back(I); 14630fca6ea1SDimitry Andric return true; 14640fca6ea1SDimitry Andric } 14650fca6ea1SDimitry Andric if (checkCondition(I->getLTPredicate(), LHS, RHS, I, Info).value_or(false)) { 14660fca6ea1SDimitry Andric I->replaceAllUsesWith(ConstantInt::getSigned(I->getType(), -1)); 14670fca6ea1SDimitry Andric ToRemove.push_back(I); 14680fca6ea1SDimitry Andric return true; 14690fca6ea1SDimitry Andric } 14706c4b055cSDimitry Andric if (checkCondition(ICmpInst::ICMP_EQ, LHS, RHS, I, Info).value_or(false)) { 14710fca6ea1SDimitry Andric I->replaceAllUsesWith(ConstantInt::get(I->getType(), 0)); 14720fca6ea1SDimitry Andric ToRemove.push_back(I); 14730fca6ea1SDimitry Andric return true; 14740fca6ea1SDimitry Andric } 14750fca6ea1SDimitry Andric return false; 14760fca6ea1SDimitry Andric } 14770fca6ea1SDimitry Andric 147806c3fb27SDimitry Andric static void 147906c3fb27SDimitry Andric removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info, 148006c3fb27SDimitry Andric Module *ReproducerModule, 148106c3fb27SDimitry Andric SmallVectorImpl<ReproducerEntry> &ReproducerCondStack, 148206c3fb27SDimitry Andric SmallVectorImpl<StackEntry> &DFSInStack) { 148306c3fb27SDimitry Andric Info.popLastConstraint(E.IsSigned); 148406c3fb27SDimitry Andric // Remove variables in the system that went out of scope. 148506c3fb27SDimitry Andric auto &Mapping = Info.getValue2Index(E.IsSigned); 148606c3fb27SDimitry Andric for (Value *V : E.ValuesToRelease) 148706c3fb27SDimitry Andric Mapping.erase(V); 148806c3fb27SDimitry Andric Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size()); 148906c3fb27SDimitry Andric DFSInStack.pop_back(); 149006c3fb27SDimitry Andric if (ReproducerModule) 149106c3fb27SDimitry Andric ReproducerCondStack.pop_back(); 149206c3fb27SDimitry Andric } 149306c3fb27SDimitry Andric 1494cb14a3feSDimitry Andric /// Check if either the first condition of an AND or OR is implied by the 1495cb14a3feSDimitry Andric /// (negated in case of OR) second condition or vice versa. 1496cb14a3feSDimitry Andric static bool checkOrAndOpImpliedByOther( 149706c3fb27SDimitry Andric FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule, 149806c3fb27SDimitry Andric SmallVectorImpl<ReproducerEntry> &ReproducerCondStack, 149906c3fb27SDimitry Andric SmallVectorImpl<StackEntry> &DFSInStack) { 15005f757f3fSDimitry Andric 150106c3fb27SDimitry Andric CmpInst::Predicate Pred; 150206c3fb27SDimitry Andric Value *A, *B; 1503cb14a3feSDimitry Andric Instruction *JoinOp = CB.getContextInst(); 1504cb14a3feSDimitry Andric CmpInst *CmpToCheck = cast<CmpInst>(CB.getInstructionToSimplify()); 1505cb14a3feSDimitry Andric unsigned OtherOpIdx = JoinOp->getOperand(0) == CmpToCheck ? 1 : 0; 1506cb14a3feSDimitry Andric 1507cb14a3feSDimitry Andric // Don't try to simplify the first condition of a select by the second, as 1508cb14a3feSDimitry Andric // this may make the select more poisonous than the original one. 1509cb14a3feSDimitry Andric // TODO: check if the first operand may be poison. 1510cb14a3feSDimitry Andric if (OtherOpIdx != 0 && isa<SelectInst>(JoinOp)) 1511bdd1243dSDimitry Andric return false; 1512bdd1243dSDimitry Andric 1513cb14a3feSDimitry Andric if (!match(JoinOp->getOperand(OtherOpIdx), 1514cb14a3feSDimitry Andric m_ICmp(Pred, m_Value(A), m_Value(B)))) 1515cb14a3feSDimitry Andric return false; 1516cb14a3feSDimitry Andric 1517cb14a3feSDimitry Andric // For OR, check if the negated condition implies CmpToCheck. 1518cb14a3feSDimitry Andric bool IsOr = match(JoinOp, m_LogicalOr()); 1519cb14a3feSDimitry Andric if (IsOr) 1520cb14a3feSDimitry Andric Pred = CmpInst::getInversePredicate(Pred); 1521cb14a3feSDimitry Andric 152206c3fb27SDimitry Andric // Optimistically add fact from first condition. 152306c3fb27SDimitry Andric unsigned OldSize = DFSInStack.size(); 152406c3fb27SDimitry Andric Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 152506c3fb27SDimitry Andric if (OldSize == DFSInStack.size()) 152606c3fb27SDimitry Andric return false; 152706c3fb27SDimitry Andric 152806c3fb27SDimitry Andric bool Changed = false; 152906c3fb27SDimitry Andric // Check if the second condition can be simplified now. 1530cb14a3feSDimitry Andric if (auto ImpliedCondition = 1531cb14a3feSDimitry Andric checkCondition(CmpToCheck->getPredicate(), CmpToCheck->getOperand(0), 15327a6dacacSDimitry Andric CmpToCheck->getOperand(1), CmpToCheck, Info)) { 1533cb14a3feSDimitry Andric if (IsOr && isa<SelectInst>(JoinOp)) { 1534cb14a3feSDimitry Andric JoinOp->setOperand( 1535cb14a3feSDimitry Andric OtherOpIdx == 0 ? 2 : 0, 1536cb14a3feSDimitry Andric ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition)); 1537cb14a3feSDimitry Andric } else 1538cb14a3feSDimitry Andric JoinOp->setOperand( 1539cb14a3feSDimitry Andric 1 - OtherOpIdx, 1540cb14a3feSDimitry Andric ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition)); 1541cb14a3feSDimitry Andric 1542bdd1243dSDimitry Andric Changed = true; 1543bdd1243dSDimitry Andric } 154406c3fb27SDimitry Andric 154506c3fb27SDimitry Andric // Remove entries again. 154606c3fb27SDimitry Andric while (OldSize < DFSInStack.size()) { 154706c3fb27SDimitry Andric StackEntry E = DFSInStack.back(); 154806c3fb27SDimitry Andric removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack, 154906c3fb27SDimitry Andric DFSInStack); 155006c3fb27SDimitry Andric } 1551bdd1243dSDimitry Andric return Changed; 1552e8d8bef9SDimitry Andric } 1553e8d8bef9SDimitry Andric 155481ad6265SDimitry Andric void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B, 1555bdd1243dSDimitry Andric unsigned NumIn, unsigned NumOut, 155681ad6265SDimitry Andric SmallVectorImpl<StackEntry> &DFSInStack) { 155781ad6265SDimitry Andric // If the constraint has a pre-condition, skip the constraint if it does not 155881ad6265SDimitry Andric // hold. 1559bdd1243dSDimitry Andric SmallVector<Value *> NewVariables; 1560bdd1243dSDimitry Andric auto R = getConstraint(Pred, A, B, NewVariables); 156106c3fb27SDimitry Andric 156206c3fb27SDimitry Andric // TODO: Support non-equality for facts as well. 156306c3fb27SDimitry Andric if (!R.isValid(*this) || R.isNe()) 156481ad6265SDimitry Andric return; 156581ad6265SDimitry Andric 15665f757f3fSDimitry Andric LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B); 15675f757f3fSDimitry Andric dbgs() << "'\n"); 156881ad6265SDimitry Andric bool Added = false; 156981ad6265SDimitry Andric auto &CSToUse = getCS(R.IsSigned); 157081ad6265SDimitry Andric if (R.Coefficients.empty()) 157181ad6265SDimitry Andric return; 157281ad6265SDimitry Andric 157381ad6265SDimitry Andric Added |= CSToUse.addVariableRowFill(R.Coefficients); 157481ad6265SDimitry Andric 1575bdd1243dSDimitry Andric // If R has been added to the system, add the new variables and queue it for 1576bdd1243dSDimitry Andric // removal once it goes out-of-scope. 157781ad6265SDimitry Andric if (Added) { 157881ad6265SDimitry Andric SmallVector<Value *, 2> ValuesToRelease; 1579bdd1243dSDimitry Andric auto &Value2Index = getValue2Index(R.IsSigned); 1580bdd1243dSDimitry Andric for (Value *V : NewVariables) { 1581bdd1243dSDimitry Andric Value2Index.insert({V, Value2Index.size() + 1}); 1582bdd1243dSDimitry Andric ValuesToRelease.push_back(V); 158381ad6265SDimitry Andric } 158481ad6265SDimitry Andric 158581ad6265SDimitry Andric LLVM_DEBUG({ 158681ad6265SDimitry Andric dbgs() << " constraint: "; 158706c3fb27SDimitry Andric dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned)); 1588bdd1243dSDimitry Andric dbgs() << "\n"; 158981ad6265SDimitry Andric }); 159081ad6265SDimitry Andric 1591bdd1243dSDimitry Andric DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 1592bdd1243dSDimitry Andric std::move(ValuesToRelease)); 159381ad6265SDimitry Andric 1594cb14a3feSDimitry Andric if (!R.IsSigned) { 1595cb14a3feSDimitry Andric for (Value *V : NewVariables) { 1596cb14a3feSDimitry Andric ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0), 1597cb14a3feSDimitry Andric false, false, false); 1598cb14a3feSDimitry Andric VarPos.Coefficients[Value2Index[V]] = -1; 1599cb14a3feSDimitry Andric CSToUse.addVariableRow(VarPos.Coefficients); 1600cb14a3feSDimitry Andric DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 1601cb14a3feSDimitry Andric SmallVector<Value *, 2>()); 1602cb14a3feSDimitry Andric } 1603cb14a3feSDimitry Andric } 1604cb14a3feSDimitry Andric 160506c3fb27SDimitry Andric if (R.isEq()) { 160681ad6265SDimitry Andric // Also add the inverted constraint for equality constraints. 160781ad6265SDimitry Andric for (auto &Coeff : R.Coefficients) 160881ad6265SDimitry Andric Coeff *= -1; 160981ad6265SDimitry Andric CSToUse.addVariableRowFill(R.Coefficients); 161081ad6265SDimitry Andric 1611bdd1243dSDimitry Andric DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 161281ad6265SDimitry Andric SmallVector<Value *, 2>()); 161381ad6265SDimitry Andric } 161481ad6265SDimitry Andric } 161581ad6265SDimitry Andric } 161681ad6265SDimitry Andric 1617bdd1243dSDimitry Andric static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B, 1618bdd1243dSDimitry Andric SmallVectorImpl<Instruction *> &ToRemove) { 1619bdd1243dSDimitry Andric bool Changed = false; 1620bdd1243dSDimitry Andric IRBuilder<> Builder(II->getParent(), II->getIterator()); 1621bdd1243dSDimitry Andric Value *Sub = nullptr; 1622bdd1243dSDimitry Andric for (User *U : make_early_inc_range(II->users())) { 1623bdd1243dSDimitry Andric if (match(U, m_ExtractValue<0>(m_Value()))) { 1624bdd1243dSDimitry Andric if (!Sub) 1625bdd1243dSDimitry Andric Sub = Builder.CreateSub(A, B); 1626bdd1243dSDimitry Andric U->replaceAllUsesWith(Sub); 1627bdd1243dSDimitry Andric Changed = true; 1628bdd1243dSDimitry Andric } else if (match(U, m_ExtractValue<1>(m_Value()))) { 1629bdd1243dSDimitry Andric U->replaceAllUsesWith(Builder.getFalse()); 1630bdd1243dSDimitry Andric Changed = true; 1631bdd1243dSDimitry Andric } else 1632bdd1243dSDimitry Andric continue; 1633bdd1243dSDimitry Andric 1634bdd1243dSDimitry Andric if (U->use_empty()) { 1635bdd1243dSDimitry Andric auto *I = cast<Instruction>(U); 1636bdd1243dSDimitry Andric ToRemove.push_back(I); 1637bdd1243dSDimitry Andric I->setOperand(0, PoisonValue::get(II->getType())); 1638bdd1243dSDimitry Andric Changed = true; 1639bdd1243dSDimitry Andric } 1640bdd1243dSDimitry Andric } 1641bdd1243dSDimitry Andric 1642bdd1243dSDimitry Andric if (II->use_empty()) { 1643bdd1243dSDimitry Andric II->eraseFromParent(); 1644bdd1243dSDimitry Andric Changed = true; 1645bdd1243dSDimitry Andric } 1646bdd1243dSDimitry Andric return Changed; 1647bdd1243dSDimitry Andric } 1648bdd1243dSDimitry Andric 1649bdd1243dSDimitry Andric static bool 165081ad6265SDimitry Andric tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, 165181ad6265SDimitry Andric SmallVectorImpl<Instruction *> &ToRemove) { 165281ad6265SDimitry Andric auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B, 165381ad6265SDimitry Andric ConstraintInfo &Info) { 1654bdd1243dSDimitry Andric auto R = Info.getConstraintForSolving(Pred, A, B); 1655bdd1243dSDimitry Andric if (R.size() < 2 || !R.isValid(Info)) 165681ad6265SDimitry Andric return false; 165781ad6265SDimitry Andric 1658bdd1243dSDimitry Andric auto &CSToUse = Info.getCS(R.IsSigned); 165981ad6265SDimitry Andric return CSToUse.isConditionImplied(R.Coefficients); 166081ad6265SDimitry Andric }; 166181ad6265SDimitry Andric 1662bdd1243dSDimitry Andric bool Changed = false; 166381ad6265SDimitry Andric if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) { 166481ad6265SDimitry Andric // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and 166581ad6265SDimitry Andric // can be simplified to a regular sub. 166681ad6265SDimitry Andric Value *A = II->getArgOperand(0); 166781ad6265SDimitry Andric Value *B = II->getArgOperand(1); 166881ad6265SDimitry Andric if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) || 166981ad6265SDimitry Andric !DoesConditionHold(CmpInst::ICMP_SGE, B, 167081ad6265SDimitry Andric ConstantInt::get(A->getType(), 0), Info)) 1671bdd1243dSDimitry Andric return false; 1672bdd1243dSDimitry Andric Changed = replaceSubOverflowUses(II, A, B, ToRemove); 167381ad6265SDimitry Andric } 1674bdd1243dSDimitry Andric return Changed; 167581ad6265SDimitry Andric } 167681ad6265SDimitry Andric 16775f757f3fSDimitry Andric static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI, 16785f757f3fSDimitry Andric ScalarEvolution &SE, 167906c3fb27SDimitry Andric OptimizationRemarkEmitter &ORE) { 168081ad6265SDimitry Andric bool Changed = false; 168181ad6265SDimitry Andric DT.updateDFSNumbers(); 168206c3fb27SDimitry Andric SmallVector<Value *> FunctionArgs; 168306c3fb27SDimitry Andric for (Value &Arg : F.args()) 168406c3fb27SDimitry Andric FunctionArgs.push_back(&Arg); 16850fca6ea1SDimitry Andric ConstraintInfo Info(F.getDataLayout(), FunctionArgs); 16865f757f3fSDimitry Andric State S(DT, LI, SE); 168706c3fb27SDimitry Andric std::unique_ptr<Module> ReproducerModule( 168806c3fb27SDimitry Andric DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr); 168981ad6265SDimitry Andric 169081ad6265SDimitry Andric // First, collect conditions implied by branches and blocks with their 169181ad6265SDimitry Andric // Dominator DFS in and out numbers. 169281ad6265SDimitry Andric for (BasicBlock &BB : F) { 169381ad6265SDimitry Andric if (!DT.getNode(&BB)) 169481ad6265SDimitry Andric continue; 169581ad6265SDimitry Andric S.addInfoFor(BB); 169681ad6265SDimitry Andric } 169781ad6265SDimitry Andric 1698bdd1243dSDimitry Andric // Next, sort worklist by dominance, so that dominating conditions to check 1699bdd1243dSDimitry Andric // and facts come before conditions and facts dominated by them. If a 1700bdd1243dSDimitry Andric // condition to check and a fact have the same numbers, conditional facts come 1701bdd1243dSDimitry Andric // first. Assume facts and checks are ordered according to their relative 1702bdd1243dSDimitry Andric // order in the containing basic block. Also make sure conditions with 1703bdd1243dSDimitry Andric // constant operands come before conditions without constant operands. This 1704bdd1243dSDimitry Andric // increases the effectiveness of the current signed <-> unsigned fact 1705bdd1243dSDimitry Andric // transfer logic. 1706bdd1243dSDimitry Andric stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) { 1707bdd1243dSDimitry Andric auto HasNoConstOp = [](const FactOrCheck &B) { 17085f757f3fSDimitry Andric Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0); 17095f757f3fSDimitry Andric Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1); 17105f757f3fSDimitry Andric return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1); 1711bdd1243dSDimitry Andric }; 1712bdd1243dSDimitry Andric // If both entries have the same In numbers, conditional facts come first. 1713bdd1243dSDimitry Andric // Otherwise use the relative order in the basic block. 1714bdd1243dSDimitry Andric if (A.NumIn == B.NumIn) { 1715bdd1243dSDimitry Andric if (A.isConditionFact() && B.isConditionFact()) { 1716bdd1243dSDimitry Andric bool NoConstOpA = HasNoConstOp(A); 1717bdd1243dSDimitry Andric bool NoConstOpB = HasNoConstOp(B); 1718bdd1243dSDimitry Andric return NoConstOpA < NoConstOpB; 1719bdd1243dSDimitry Andric } 1720bdd1243dSDimitry Andric if (A.isConditionFact()) 1721bdd1243dSDimitry Andric return true; 1722bdd1243dSDimitry Andric if (B.isConditionFact()) 1723bdd1243dSDimitry Andric return false; 172406c3fb27SDimitry Andric auto *InstA = A.getContextInst(); 172506c3fb27SDimitry Andric auto *InstB = B.getContextInst(); 172606c3fb27SDimitry Andric return InstA->comesBefore(InstB); 1727bdd1243dSDimitry Andric } 1728bdd1243dSDimitry Andric return A.NumIn < B.NumIn; 1729e8d8bef9SDimitry Andric }); 1730e8d8bef9SDimitry Andric 173181ad6265SDimitry Andric SmallVector<Instruction *> ToRemove; 173281ad6265SDimitry Andric 1733e8d8bef9SDimitry Andric // Finally, process ordered worklist and eliminate implied conditions. 1734e8d8bef9SDimitry Andric SmallVector<StackEntry, 16> DFSInStack; 173506c3fb27SDimitry Andric SmallVector<ReproducerEntry> ReproducerCondStack; 1736bdd1243dSDimitry Andric for (FactOrCheck &CB : S.WorkList) { 1737e8d8bef9SDimitry Andric // First, pop entries from the stack that are out-of-scope for CB. Remove 1738e8d8bef9SDimitry Andric // the corresponding entry from the constraint system. 1739e8d8bef9SDimitry Andric while (!DFSInStack.empty()) { 1740e8d8bef9SDimitry Andric auto &E = DFSInStack.back(); 1741e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 1742e8d8bef9SDimitry Andric << "\n"); 1743e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 1744e8d8bef9SDimitry Andric assert(E.NumIn <= CB.NumIn); 1745e8d8bef9SDimitry Andric if (CB.NumOut <= E.NumOut) 1746e8d8bef9SDimitry Andric break; 174781ad6265SDimitry Andric LLVM_DEBUG({ 174881ad6265SDimitry Andric dbgs() << "Removing "; 174906c3fb27SDimitry Andric dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(), 175081ad6265SDimitry Andric Info.getValue2Index(E.IsSigned)); 175181ad6265SDimitry Andric dbgs() << "\n"; 175281ad6265SDimitry Andric }); 175306c3fb27SDimitry Andric removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack, 175406c3fb27SDimitry Andric DFSInStack); 1755e8d8bef9SDimitry Andric } 1756e8d8bef9SDimitry Andric 1757e8d8bef9SDimitry Andric // For a block, check if any CmpInsts become known based on the current set 1758e8d8bef9SDimitry Andric // of constraints. 175906c3fb27SDimitry Andric if (CB.isCheck()) { 176006c3fb27SDimitry Andric Instruction *Inst = CB.getInstructionToSimplify(); 176106c3fb27SDimitry Andric if (!Inst) 176206c3fb27SDimitry Andric continue; 17631db9f3b2SDimitry Andric LLVM_DEBUG(dbgs() << "Processing condition to simplify: " << *Inst 17641db9f3b2SDimitry Andric << "\n"); 176506c3fb27SDimitry Andric if (auto *II = dyn_cast<WithOverflowInst>(Inst)) { 1766bdd1243dSDimitry Andric Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove); 176706c3fb27SDimitry Andric } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) { 176806c3fb27SDimitry Andric bool Simplified = checkAndReplaceCondition( 176906c3fb27SDimitry Andric Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(), 17705f757f3fSDimitry Andric ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove); 1771cb14a3feSDimitry Andric if (!Simplified && 1772cb14a3feSDimitry Andric match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) { 177306c3fb27SDimitry Andric Simplified = 1774cb14a3feSDimitry Andric checkOrAndOpImpliedByOther(CB, Info, ReproducerModule.get(), 177506c3fb27SDimitry Andric ReproducerCondStack, DFSInStack); 177606c3fb27SDimitry Andric } 177706c3fb27SDimitry Andric Changed |= Simplified; 17780fca6ea1SDimitry Andric } else if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Inst)) { 17790fca6ea1SDimitry Andric Changed |= checkAndReplaceMinMax(MinMax, Info, ToRemove); 17800fca6ea1SDimitry Andric } else if (auto *CmpIntr = dyn_cast<CmpIntrinsic>(Inst)) { 17810fca6ea1SDimitry Andric Changed |= checkAndReplaceCmp(CmpIntr, Info, ToRemove); 1782e8d8bef9SDimitry Andric } 1783e8d8bef9SDimitry Andric continue; 1784e8d8bef9SDimitry Andric } 1785e8d8bef9SDimitry Andric 178606c3fb27SDimitry Andric auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) { 17871db9f3b2SDimitry Andric LLVM_DEBUG(dbgs() << "Processing fact to add to the system: "; 17885f757f3fSDimitry Andric dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n"); 1789bdd1243dSDimitry Andric if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) { 1790bdd1243dSDimitry Andric LLVM_DEBUG( 1791bdd1243dSDimitry Andric dbgs() 1792bdd1243dSDimitry Andric << "Skip adding constraint because system has too many rows.\n"); 179306c3fb27SDimitry Andric return; 179406c3fb27SDimitry Andric } 179506c3fb27SDimitry Andric 179606c3fb27SDimitry Andric Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 179706c3fb27SDimitry Andric if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) 179806c3fb27SDimitry Andric ReproducerCondStack.emplace_back(Pred, A, B); 179906c3fb27SDimitry Andric 180006c3fb27SDimitry Andric Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 180106c3fb27SDimitry Andric if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) { 180206c3fb27SDimitry Andric // Add dummy entries to ReproducerCondStack to keep it in sync with 180306c3fb27SDimitry Andric // DFSInStack. 180406c3fb27SDimitry Andric for (unsigned I = 0, 180506c3fb27SDimitry Andric E = (DFSInStack.size() - ReproducerCondStack.size()); 180606c3fb27SDimitry Andric I < E; ++I) { 180706c3fb27SDimitry Andric ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE, 180806c3fb27SDimitry Andric nullptr, nullptr); 180906c3fb27SDimitry Andric } 181006c3fb27SDimitry Andric } 181106c3fb27SDimitry Andric }; 181206c3fb27SDimitry Andric 181306c3fb27SDimitry Andric ICmpInst::Predicate Pred; 18145f757f3fSDimitry Andric if (!CB.isConditionFact()) { 1815647cbc5dSDimitry Andric Value *X; 1816647cbc5dSDimitry Andric if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) { 18170fca6ea1SDimitry Andric // If is_int_min_poison is true then we may assume llvm.abs >= 0. 18180fca6ea1SDimitry Andric if (cast<ConstantInt>(CB.Inst->getOperand(1))->isOne()) 18190fca6ea1SDimitry Andric AddFact(CmpInst::ICMP_SGE, CB.Inst, 18200fca6ea1SDimitry Andric ConstantInt::get(CB.Inst->getType(), 0)); 1821647cbc5dSDimitry Andric AddFact(CmpInst::ICMP_SGE, CB.Inst, X); 1822647cbc5dSDimitry Andric continue; 1823647cbc5dSDimitry Andric } 1824647cbc5dSDimitry Andric 182506c3fb27SDimitry Andric if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) { 182606c3fb27SDimitry Andric Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate()); 182706c3fb27SDimitry Andric AddFact(Pred, MinMax, MinMax->getLHS()); 182806c3fb27SDimitry Andric AddFact(Pred, MinMax, MinMax->getRHS()); 1829bdd1243dSDimitry Andric continue; 1830bdd1243dSDimitry Andric } 1831e8d8bef9SDimitry Andric } 18325f757f3fSDimitry Andric 18335f757f3fSDimitry Andric Value *A = nullptr, *B = nullptr; 18345f757f3fSDimitry Andric if (CB.isConditionFact()) { 18355f757f3fSDimitry Andric Pred = CB.Cond.Pred; 18365f757f3fSDimitry Andric A = CB.Cond.Op0; 18375f757f3fSDimitry Andric B = CB.Cond.Op1; 18385f757f3fSDimitry Andric if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE && 18391db9f3b2SDimitry Andric !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) { 18401db9f3b2SDimitry Andric LLVM_DEBUG({ 18411db9f3b2SDimitry Andric dbgs() << "Not adding fact "; 18421db9f3b2SDimitry Andric dumpUnpackedICmp(dbgs(), Pred, A, B); 18431db9f3b2SDimitry Andric dbgs() << " because precondition "; 18441db9f3b2SDimitry Andric dumpUnpackedICmp(dbgs(), CB.DoesHold.Pred, CB.DoesHold.Op0, 18451db9f3b2SDimitry Andric CB.DoesHold.Op1); 18461db9f3b2SDimitry Andric dbgs() << " does not hold.\n"; 18471db9f3b2SDimitry Andric }); 18485f757f3fSDimitry Andric continue; 18491db9f3b2SDimitry Andric } 18505f757f3fSDimitry Andric } else { 18515f757f3fSDimitry Andric bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>( 18525f757f3fSDimitry Andric m_ICmp(Pred, m_Value(A), m_Value(B)))); 18535f757f3fSDimitry Andric (void)Matched; 18545f757f3fSDimitry Andric assert(Matched && "Must have an assume intrinsic with a icmp operand"); 18555f757f3fSDimitry Andric } 18565f757f3fSDimitry Andric AddFact(Pred, A, B); 1857fe6060f1SDimitry Andric } 1858e8d8bef9SDimitry Andric 185906c3fb27SDimitry Andric if (ReproducerModule && !ReproducerModule->functions().empty()) { 186006c3fb27SDimitry Andric std::string S; 186106c3fb27SDimitry Andric raw_string_ostream StringS(S); 186206c3fb27SDimitry Andric ReproducerModule->print(StringS, nullptr); 186306c3fb27SDimitry Andric StringS.flush(); 186406c3fb27SDimitry Andric OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F); 186506c3fb27SDimitry Andric Rem << ore::NV("module") << S; 186606c3fb27SDimitry Andric ORE.emit(Rem); 186706c3fb27SDimitry Andric } 186806c3fb27SDimitry Andric 186981ad6265SDimitry Andric #ifndef NDEBUG 187081ad6265SDimitry Andric unsigned SignedEntries = 187181ad6265SDimitry Andric count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; }); 1872cb14a3feSDimitry Andric assert(Info.getCS(false).size() - FunctionArgs.size() == 1873cb14a3feSDimitry Andric DFSInStack.size() - SignedEntries && 1874fe6060f1SDimitry Andric "updates to CS and DFSInStack are out of sync"); 187581ad6265SDimitry Andric assert(Info.getCS(true).size() == SignedEntries && 187681ad6265SDimitry Andric "updates to CS and DFSInStack are out of sync"); 187781ad6265SDimitry Andric #endif 187881ad6265SDimitry Andric 187981ad6265SDimitry Andric for (Instruction *I : ToRemove) 188081ad6265SDimitry Andric I->eraseFromParent(); 1881e8d8bef9SDimitry Andric return Changed; 1882e8d8bef9SDimitry Andric } 1883e8d8bef9SDimitry Andric 1884e8d8bef9SDimitry Andric PreservedAnalyses ConstraintEliminationPass::run(Function &F, 1885e8d8bef9SDimitry Andric FunctionAnalysisManager &AM) { 1886e8d8bef9SDimitry Andric auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 18875f757f3fSDimitry Andric auto &LI = AM.getResult<LoopAnalysis>(F); 18885f757f3fSDimitry Andric auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 188906c3fb27SDimitry Andric auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 18905f757f3fSDimitry Andric if (!eliminateConstraints(F, DT, LI, SE, ORE)) 1891e8d8bef9SDimitry Andric return PreservedAnalyses::all(); 1892e8d8bef9SDimitry Andric 1893e8d8bef9SDimitry Andric PreservedAnalyses PA; 1894e8d8bef9SDimitry Andric PA.preserve<DominatorTreeAnalysis>(); 18955f757f3fSDimitry Andric PA.preserve<LoopAnalysis>(); 18965f757f3fSDimitry Andric PA.preserve<ScalarEvolutionAnalysis>(); 1897e8d8bef9SDimitry Andric PA.preserveSet<CFGAnalyses>(); 1898e8d8bef9SDimitry Andric return PA; 1899e8d8bef9SDimitry Andric } 1900