xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 647cbc5de815c5651677bf8582797f716ec7b48d)
1e8d8bef9SDimitry Andric //===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric //
9e8d8bef9SDimitry Andric // Eliminate conditions based on constraints collected from dominating
10e8d8bef9SDimitry Andric // conditions.
11e8d8bef9SDimitry Andric //
12e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
13e8d8bef9SDimitry Andric 
14e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar/ConstraintElimination.h"
15e8d8bef9SDimitry Andric #include "llvm/ADT/STLExtras.h"
16fe6060f1SDimitry Andric #include "llvm/ADT/ScopeExit.h"
17e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h"
18e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h"
19e8d8bef9SDimitry Andric #include "llvm/Analysis/ConstraintSystem.h"
20e8d8bef9SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
215f757f3fSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
2206c3fb27SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
235f757f3fSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
245f757f3fSDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
25349cc55cSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
26bdd1243dSDimitry Andric #include "llvm/IR/DataLayout.h"
27e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h"
28e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
2981ad6265SDimitry Andric #include "llvm/IR/IRBuilder.h"
305f757f3fSDimitry Andric #include "llvm/IR/InstrTypes.h"
31e8d8bef9SDimitry Andric #include "llvm/IR/Instructions.h"
32e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h"
3306c3fb27SDimitry Andric #include "llvm/IR/Verifier.h"
34e8d8bef9SDimitry Andric #include "llvm/Pass.h"
35bdd1243dSDimitry Andric #include "llvm/Support/CommandLine.h"
36e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h"
37e8d8bef9SDimitry Andric #include "llvm/Support/DebugCounter.h"
3881ad6265SDimitry Andric #include "llvm/Support/MathExtras.h"
3906c3fb27SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
4006c3fb27SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
41e8d8bef9SDimitry Andric 
42bdd1243dSDimitry Andric #include <cmath>
4306c3fb27SDimitry Andric #include <optional>
44fe6060f1SDimitry Andric #include <string>
45fe6060f1SDimitry Andric 
46e8d8bef9SDimitry Andric using namespace llvm;
47e8d8bef9SDimitry Andric using namespace PatternMatch;
48e8d8bef9SDimitry Andric 
49e8d8bef9SDimitry Andric #define DEBUG_TYPE "constraint-elimination"
50e8d8bef9SDimitry Andric 
51e8d8bef9SDimitry Andric STATISTIC(NumCondsRemoved, "Number of instructions removed");
52e8d8bef9SDimitry Andric DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
53e8d8bef9SDimitry Andric               "Controls which conditions are eliminated");
54e8d8bef9SDimitry Andric 
55bdd1243dSDimitry Andric static cl::opt<unsigned>
56bdd1243dSDimitry Andric     MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden,
57bdd1243dSDimitry Andric             cl::desc("Maximum number of rows to keep in constraint system"));
58bdd1243dSDimitry Andric 
5906c3fb27SDimitry Andric static cl::opt<bool> DumpReproducers(
6006c3fb27SDimitry Andric     "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden,
6106c3fb27SDimitry Andric     cl::desc("Dump IR to reproduce successful transformations."));
6206c3fb27SDimitry Andric 
63e8d8bef9SDimitry Andric static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
6481ad6265SDimitry Andric static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min();
65e8d8bef9SDimitry Andric 
66bdd1243dSDimitry Andric // A helper to multiply 2 signed integers where overflowing is allowed.
67bdd1243dSDimitry Andric static int64_t multiplyWithOverflow(int64_t A, int64_t B) {
68bdd1243dSDimitry Andric   int64_t Result;
69bdd1243dSDimitry Andric   MulOverflow(A, B, Result);
70bdd1243dSDimitry Andric   return Result;
71bdd1243dSDimitry Andric }
72bdd1243dSDimitry Andric 
73bdd1243dSDimitry Andric // A helper to add 2 signed integers where overflowing is allowed.
74bdd1243dSDimitry Andric static int64_t addWithOverflow(int64_t A, int64_t B) {
75bdd1243dSDimitry Andric   int64_t Result;
76bdd1243dSDimitry Andric   AddOverflow(A, B, Result);
77bdd1243dSDimitry Andric   return Result;
78bdd1243dSDimitry Andric }
79bdd1243dSDimitry Andric 
8006c3fb27SDimitry Andric static Instruction *getContextInstForUse(Use &U) {
8106c3fb27SDimitry Andric   Instruction *UserI = cast<Instruction>(U.getUser());
8206c3fb27SDimitry Andric   if (auto *Phi = dyn_cast<PHINode>(UserI))
8306c3fb27SDimitry Andric     UserI = Phi->getIncomingBlock(U)->getTerminator();
8406c3fb27SDimitry Andric   return UserI;
8506c3fb27SDimitry Andric }
8606c3fb27SDimitry Andric 
8704eeddc0SDimitry Andric namespace {
885f757f3fSDimitry Andric /// Struct to express a condition of the form %Op0 Pred %Op1.
895f757f3fSDimitry Andric struct ConditionTy {
905f757f3fSDimitry Andric   CmpInst::Predicate Pred;
915f757f3fSDimitry Andric   Value *Op0;
925f757f3fSDimitry Andric   Value *Op1;
935f757f3fSDimitry Andric 
945f757f3fSDimitry Andric   ConditionTy()
955f757f3fSDimitry Andric       : Pred(CmpInst::BAD_ICMP_PREDICATE), Op0(nullptr), Op1(nullptr) {}
965f757f3fSDimitry Andric   ConditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1)
975f757f3fSDimitry Andric       : Pred(Pred), Op0(Op0), Op1(Op1) {}
985f757f3fSDimitry Andric };
995f757f3fSDimitry Andric 
10006c3fb27SDimitry Andric /// Represents either
1015f757f3fSDimitry Andric ///  * a condition that holds on entry to a block (=condition fact)
10206c3fb27SDimitry Andric ///  * an assume (=assume fact)
10306c3fb27SDimitry Andric ///  * a use of a compare instruction to simplify.
10406c3fb27SDimitry Andric /// It also tracks the Dominator DFS in and out numbers for each entry.
10506c3fb27SDimitry Andric struct FactOrCheck {
1065f757f3fSDimitry Andric   enum class EntryTy {
1075f757f3fSDimitry Andric     ConditionFact, /// A condition that holds on entry to a block.
1085f757f3fSDimitry Andric     InstFact,      /// A fact that holds after Inst executed (e.g. an assume or
1095f757f3fSDimitry Andric                    /// min/mix intrinsic.
1105f757f3fSDimitry Andric     InstCheck,     /// An instruction to simplify (e.g. an overflow math
1115f757f3fSDimitry Andric                    /// intrinsics).
1125f757f3fSDimitry Andric     UseCheck       /// An use of a compare instruction to simplify.
1135f757f3fSDimitry Andric   };
1145f757f3fSDimitry Andric 
11506c3fb27SDimitry Andric   union {
11606c3fb27SDimitry Andric     Instruction *Inst;
11706c3fb27SDimitry Andric     Use *U;
1185f757f3fSDimitry Andric     ConditionTy Cond;
11906c3fb27SDimitry Andric   };
1205f757f3fSDimitry Andric 
1215f757f3fSDimitry Andric   /// A pre-condition that must hold for the current fact to be added to the
1225f757f3fSDimitry Andric   /// system.
1235f757f3fSDimitry Andric   ConditionTy DoesHold;
1245f757f3fSDimitry Andric 
12506c3fb27SDimitry Andric   unsigned NumIn;
12606c3fb27SDimitry Andric   unsigned NumOut;
1275f757f3fSDimitry Andric   EntryTy Ty;
12806c3fb27SDimitry Andric 
1295f757f3fSDimitry Andric   FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst)
13006c3fb27SDimitry Andric       : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
1315f757f3fSDimitry Andric         Ty(Ty) {}
13206c3fb27SDimitry Andric 
13306c3fb27SDimitry Andric   FactOrCheck(DomTreeNode *DTN, Use *U)
1345f757f3fSDimitry Andric       : U(U), DoesHold(CmpInst::BAD_ICMP_PREDICATE, nullptr, nullptr),
1355f757f3fSDimitry Andric         NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()),
1365f757f3fSDimitry Andric         Ty(EntryTy::UseCheck) {}
13706c3fb27SDimitry Andric 
1385f757f3fSDimitry Andric   FactOrCheck(DomTreeNode *DTN, CmpInst::Predicate Pred, Value *Op0, Value *Op1,
1395f757f3fSDimitry Andric               ConditionTy Precond = ConditionTy())
1405f757f3fSDimitry Andric       : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()),
1415f757f3fSDimitry Andric         NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {}
1425f757f3fSDimitry Andric 
1435f757f3fSDimitry Andric   static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpInst::Predicate Pred,
1445f757f3fSDimitry Andric                                       Value *Op0, Value *Op1,
1455f757f3fSDimitry Andric                                       ConditionTy Precond = ConditionTy()) {
1465f757f3fSDimitry Andric     return FactOrCheck(DTN, Pred, Op0, Op1, Precond);
1475f757f3fSDimitry Andric   }
1485f757f3fSDimitry Andric 
1495f757f3fSDimitry Andric   static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) {
1505f757f3fSDimitry Andric     return FactOrCheck(EntryTy::InstFact, DTN, Inst);
15106c3fb27SDimitry Andric   }
15206c3fb27SDimitry Andric 
15306c3fb27SDimitry Andric   static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) {
15406c3fb27SDimitry Andric     return FactOrCheck(DTN, U);
15506c3fb27SDimitry Andric   }
15606c3fb27SDimitry Andric 
15706c3fb27SDimitry Andric   static FactOrCheck getCheck(DomTreeNode *DTN, CallInst *CI) {
1585f757f3fSDimitry Andric     return FactOrCheck(EntryTy::InstCheck, DTN, CI);
15906c3fb27SDimitry Andric   }
16006c3fb27SDimitry Andric 
16106c3fb27SDimitry Andric   bool isCheck() const {
1625f757f3fSDimitry Andric     return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck;
16306c3fb27SDimitry Andric   }
16406c3fb27SDimitry Andric 
16506c3fb27SDimitry Andric   Instruction *getContextInst() const {
1665f757f3fSDimitry Andric     if (Ty == EntryTy::UseCheck)
16706c3fb27SDimitry Andric       return getContextInstForUse(*U);
1685f757f3fSDimitry Andric     return Inst;
16906c3fb27SDimitry Andric   }
1705f757f3fSDimitry Andric 
17106c3fb27SDimitry Andric   Instruction *getInstructionToSimplify() const {
17206c3fb27SDimitry Andric     assert(isCheck());
1735f757f3fSDimitry Andric     if (Ty == EntryTy::InstCheck)
17406c3fb27SDimitry Andric       return Inst;
17506c3fb27SDimitry Andric     // The use may have been simplified to a constant already.
17606c3fb27SDimitry Andric     return dyn_cast<Instruction>(*U);
17706c3fb27SDimitry Andric   }
1785f757f3fSDimitry Andric 
1795f757f3fSDimitry Andric   bool isConditionFact() const { return Ty == EntryTy::ConditionFact; }
18006c3fb27SDimitry Andric };
18106c3fb27SDimitry Andric 
18206c3fb27SDimitry Andric /// Keep state required to build worklist.
18306c3fb27SDimitry Andric struct State {
18406c3fb27SDimitry Andric   DominatorTree &DT;
1855f757f3fSDimitry Andric   LoopInfo &LI;
1865f757f3fSDimitry Andric   ScalarEvolution &SE;
18706c3fb27SDimitry Andric   SmallVector<FactOrCheck, 64> WorkList;
18806c3fb27SDimitry Andric 
1895f757f3fSDimitry Andric   State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE)
1905f757f3fSDimitry Andric       : DT(DT), LI(LI), SE(SE) {}
19106c3fb27SDimitry Andric 
19206c3fb27SDimitry Andric   /// Process block \p BB and add known facts to work-list.
19306c3fb27SDimitry Andric   void addInfoFor(BasicBlock &BB);
19406c3fb27SDimitry Andric 
1955f757f3fSDimitry Andric   /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares
1965f757f3fSDimitry Andric   /// controlling the loop header.
1975f757f3fSDimitry Andric   void addInfoForInductions(BasicBlock &BB);
1985f757f3fSDimitry Andric 
19906c3fb27SDimitry Andric   /// Returns true if we can add a known condition from BB to its successor
20006c3fb27SDimitry Andric   /// block Succ.
20106c3fb27SDimitry Andric   bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const {
20206c3fb27SDimitry Andric     return DT.dominates(BasicBlockEdge(&BB, Succ), Succ);
20306c3fb27SDimitry Andric   }
20406c3fb27SDimitry Andric };
20504eeddc0SDimitry Andric 
20681ad6265SDimitry Andric class ConstraintInfo;
20704eeddc0SDimitry Andric 
20881ad6265SDimitry Andric struct StackEntry {
20981ad6265SDimitry Andric   unsigned NumIn;
21081ad6265SDimitry Andric   unsigned NumOut;
21181ad6265SDimitry Andric   bool IsSigned = false;
21281ad6265SDimitry Andric   /// Variables that can be removed from the system once the stack entry gets
21381ad6265SDimitry Andric   /// removed.
21481ad6265SDimitry Andric   SmallVector<Value *, 2> ValuesToRelease;
21581ad6265SDimitry Andric 
216bdd1243dSDimitry Andric   StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned,
21781ad6265SDimitry Andric              SmallVector<Value *, 2> ValuesToRelease)
218bdd1243dSDimitry Andric       : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned),
21981ad6265SDimitry Andric         ValuesToRelease(ValuesToRelease) {}
22004eeddc0SDimitry Andric };
22104eeddc0SDimitry Andric 
22281ad6265SDimitry Andric struct ConstraintTy {
22381ad6265SDimitry Andric   SmallVector<int64_t, 8> Coefficients;
2245f757f3fSDimitry Andric   SmallVector<ConditionTy, 2> Preconditions;
22504eeddc0SDimitry Andric 
226bdd1243dSDimitry Andric   SmallVector<SmallVector<int64_t, 8>> ExtraInfo;
227bdd1243dSDimitry Andric 
22881ad6265SDimitry Andric   bool IsSigned = false;
22904eeddc0SDimitry Andric 
23081ad6265SDimitry Andric   ConstraintTy() = default;
23104eeddc0SDimitry Andric 
23206c3fb27SDimitry Andric   ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned, bool IsEq,
23306c3fb27SDimitry Andric                bool IsNe)
23406c3fb27SDimitry Andric       : Coefficients(Coefficients), IsSigned(IsSigned), IsEq(IsEq), IsNe(IsNe) {
23506c3fb27SDimitry Andric   }
23681ad6265SDimitry Andric 
23781ad6265SDimitry Andric   unsigned size() const { return Coefficients.size(); }
23881ad6265SDimitry Andric 
23981ad6265SDimitry Andric   unsigned empty() const { return Coefficients.empty(); }
24004eeddc0SDimitry Andric 
24181ad6265SDimitry Andric   /// Returns true if all preconditions for this list of constraints are
24281ad6265SDimitry Andric   /// satisfied given \p CS and the corresponding \p Value2Index mapping.
24381ad6265SDimitry Andric   bool isValid(const ConstraintInfo &Info) const;
24406c3fb27SDimitry Andric 
24506c3fb27SDimitry Andric   bool isEq() const { return IsEq; }
24606c3fb27SDimitry Andric 
24706c3fb27SDimitry Andric   bool isNe() const { return IsNe; }
24806c3fb27SDimitry Andric 
24906c3fb27SDimitry Andric   /// Check if the current constraint is implied by the given ConstraintSystem.
25006c3fb27SDimitry Andric   ///
25106c3fb27SDimitry Andric   /// \return true or false if the constraint is proven to be respectively true,
25206c3fb27SDimitry Andric   /// or false. When the constraint cannot be proven to be either true or false,
25306c3fb27SDimitry Andric   /// std::nullopt is returned.
25406c3fb27SDimitry Andric   std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const;
25506c3fb27SDimitry Andric 
25606c3fb27SDimitry Andric private:
25706c3fb27SDimitry Andric   bool IsEq = false;
25806c3fb27SDimitry Andric   bool IsNe = false;
25981ad6265SDimitry Andric };
26081ad6265SDimitry Andric 
26181ad6265SDimitry Andric /// Wrapper encapsulating separate constraint systems and corresponding value
26281ad6265SDimitry Andric /// mappings for both unsigned and signed information. Facts are added to and
26381ad6265SDimitry Andric /// conditions are checked against the corresponding system depending on the
26481ad6265SDimitry Andric /// signed-ness of their predicates. While the information is kept separate
26581ad6265SDimitry Andric /// based on signed-ness, certain conditions can be transferred between the two
26681ad6265SDimitry Andric /// systems.
26781ad6265SDimitry Andric class ConstraintInfo {
26881ad6265SDimitry Andric 
26981ad6265SDimitry Andric   ConstraintSystem UnsignedCS;
27081ad6265SDimitry Andric   ConstraintSystem SignedCS;
27181ad6265SDimitry Andric 
272bdd1243dSDimitry Andric   const DataLayout &DL;
273bdd1243dSDimitry Andric 
27481ad6265SDimitry Andric public:
27506c3fb27SDimitry Andric   ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs)
276cb14a3feSDimitry Andric       : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {
277cb14a3feSDimitry Andric     auto &Value2Index = getValue2Index(false);
278cb14a3feSDimitry Andric     // Add Arg > -1 constraints to unsigned system for all function arguments.
279cb14a3feSDimitry Andric     for (Value *Arg : FunctionArgs) {
280cb14a3feSDimitry Andric       ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
281cb14a3feSDimitry Andric                           false, false, false);
282cb14a3feSDimitry Andric       VarPos.Coefficients[Value2Index[Arg]] = -1;
283cb14a3feSDimitry Andric       UnsignedCS.addVariableRow(VarPos.Coefficients);
284cb14a3feSDimitry Andric     }
285cb14a3feSDimitry Andric   }
286bdd1243dSDimitry Andric 
28781ad6265SDimitry Andric   DenseMap<Value *, unsigned> &getValue2Index(bool Signed) {
28806c3fb27SDimitry Andric     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
28981ad6265SDimitry Andric   }
29081ad6265SDimitry Andric   const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const {
29106c3fb27SDimitry Andric     return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index();
29281ad6265SDimitry Andric   }
29381ad6265SDimitry Andric 
29481ad6265SDimitry Andric   ConstraintSystem &getCS(bool Signed) {
29581ad6265SDimitry Andric     return Signed ? SignedCS : UnsignedCS;
29681ad6265SDimitry Andric   }
29781ad6265SDimitry Andric   const ConstraintSystem &getCS(bool Signed) const {
29881ad6265SDimitry Andric     return Signed ? SignedCS : UnsignedCS;
29981ad6265SDimitry Andric   }
30081ad6265SDimitry Andric 
30181ad6265SDimitry Andric   void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); }
30281ad6265SDimitry Andric   void popLastNVariables(bool Signed, unsigned N) {
30381ad6265SDimitry Andric     getCS(Signed).popLastNVariables(N);
30481ad6265SDimitry Andric   }
30581ad6265SDimitry Andric 
30681ad6265SDimitry Andric   bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const;
30781ad6265SDimitry Andric 
308bdd1243dSDimitry Andric   void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
309bdd1243dSDimitry Andric                unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack);
31081ad6265SDimitry Andric 
31181ad6265SDimitry Andric   /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
31281ad6265SDimitry Andric   /// constraints, using indices from the corresponding constraint system.
313bdd1243dSDimitry Andric   /// New variables that need to be added to the system are collected in
314bdd1243dSDimitry Andric   /// \p NewVariables.
31581ad6265SDimitry Andric   ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
316bdd1243dSDimitry Andric                              SmallVectorImpl<Value *> &NewVariables) const;
31781ad6265SDimitry Andric 
318bdd1243dSDimitry Andric   /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of
319bdd1243dSDimitry Andric   /// constraints using getConstraint. Returns an empty constraint if the result
320bdd1243dSDimitry Andric   /// cannot be used to query the existing constraint system, e.g. because it
321bdd1243dSDimitry Andric   /// would require adding new variables. Also tries to convert signed
322bdd1243dSDimitry Andric   /// predicates to unsigned ones if possible to allow using the unsigned system
323bdd1243dSDimitry Andric   /// which increases the effectiveness of the signed <-> unsigned transfer
324bdd1243dSDimitry Andric   /// logic.
325bdd1243dSDimitry Andric   ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0,
326bdd1243dSDimitry Andric                                        Value *Op1) const;
32781ad6265SDimitry Andric 
32881ad6265SDimitry Andric   /// Try to add information from \p A \p Pred \p B to the unsigned/signed
32981ad6265SDimitry Andric   /// system if \p Pred is signed/unsigned.
33081ad6265SDimitry Andric   void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B,
331bdd1243dSDimitry Andric                              unsigned NumIn, unsigned NumOut,
33281ad6265SDimitry Andric                              SmallVectorImpl<StackEntry> &DFSInStack);
33304eeddc0SDimitry Andric };
33404eeddc0SDimitry Andric 
335bdd1243dSDimitry Andric /// Represents a (Coefficient * Variable) entry after IR decomposition.
336bdd1243dSDimitry Andric struct DecompEntry {
337bdd1243dSDimitry Andric   int64_t Coefficient;
338bdd1243dSDimitry Andric   Value *Variable;
339bdd1243dSDimitry Andric   /// True if the variable is known positive in the current constraint.
340bdd1243dSDimitry Andric   bool IsKnownNonNegative;
341bdd1243dSDimitry Andric 
342bdd1243dSDimitry Andric   DecompEntry(int64_t Coefficient, Value *Variable,
343bdd1243dSDimitry Andric               bool IsKnownNonNegative = false)
344bdd1243dSDimitry Andric       : Coefficient(Coefficient), Variable(Variable),
345bdd1243dSDimitry Andric         IsKnownNonNegative(IsKnownNonNegative) {}
346bdd1243dSDimitry Andric };
347bdd1243dSDimitry Andric 
348bdd1243dSDimitry Andric /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition.
349bdd1243dSDimitry Andric struct Decomposition {
350bdd1243dSDimitry Andric   int64_t Offset = 0;
351bdd1243dSDimitry Andric   SmallVector<DecompEntry, 3> Vars;
352bdd1243dSDimitry Andric 
353bdd1243dSDimitry Andric   Decomposition(int64_t Offset) : Offset(Offset) {}
354bdd1243dSDimitry Andric   Decomposition(Value *V, bool IsKnownNonNegative = false) {
355bdd1243dSDimitry Andric     Vars.emplace_back(1, V, IsKnownNonNegative);
356bdd1243dSDimitry Andric   }
357bdd1243dSDimitry Andric   Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars)
358bdd1243dSDimitry Andric       : Offset(Offset), Vars(Vars) {}
359bdd1243dSDimitry Andric 
360bdd1243dSDimitry Andric   void add(int64_t OtherOffset) {
361bdd1243dSDimitry Andric     Offset = addWithOverflow(Offset, OtherOffset);
362bdd1243dSDimitry Andric   }
363bdd1243dSDimitry Andric 
364bdd1243dSDimitry Andric   void add(const Decomposition &Other) {
365bdd1243dSDimitry Andric     add(Other.Offset);
366bdd1243dSDimitry Andric     append_range(Vars, Other.Vars);
367bdd1243dSDimitry Andric   }
368bdd1243dSDimitry Andric 
369*647cbc5dSDimitry Andric   void sub(const Decomposition &Other) {
370*647cbc5dSDimitry Andric     Decomposition Tmp = Other;
371*647cbc5dSDimitry Andric     Tmp.mul(-1);
372*647cbc5dSDimitry Andric     add(Tmp.Offset);
373*647cbc5dSDimitry Andric     append_range(Vars, Tmp.Vars);
374*647cbc5dSDimitry Andric   }
375*647cbc5dSDimitry Andric 
376bdd1243dSDimitry Andric   void mul(int64_t Factor) {
377bdd1243dSDimitry Andric     Offset = multiplyWithOverflow(Offset, Factor);
378bdd1243dSDimitry Andric     for (auto &Var : Vars)
379bdd1243dSDimitry Andric       Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor);
380bdd1243dSDimitry Andric   }
381bdd1243dSDimitry Andric };
382bdd1243dSDimitry Andric 
3835f757f3fSDimitry Andric // Variable and constant offsets for a chain of GEPs, with base pointer BasePtr.
3845f757f3fSDimitry Andric struct OffsetResult {
3855f757f3fSDimitry Andric   Value *BasePtr;
3865f757f3fSDimitry Andric   APInt ConstantOffset;
3875f757f3fSDimitry Andric   MapVector<Value *, APInt> VariableOffsets;
3885f757f3fSDimitry Andric   bool AllInbounds;
3895f757f3fSDimitry Andric 
3905f757f3fSDimitry Andric   OffsetResult() : BasePtr(nullptr), ConstantOffset(0, uint64_t(0)) {}
3915f757f3fSDimitry Andric 
3925f757f3fSDimitry Andric   OffsetResult(GEPOperator &GEP, const DataLayout &DL)
3935f757f3fSDimitry Andric       : BasePtr(GEP.getPointerOperand()), AllInbounds(GEP.isInBounds()) {
3945f757f3fSDimitry Andric     ConstantOffset = APInt(DL.getIndexTypeSizeInBits(BasePtr->getType()), 0);
3955f757f3fSDimitry Andric   }
3965f757f3fSDimitry Andric };
39704eeddc0SDimitry Andric } // namespace
39804eeddc0SDimitry Andric 
3995f757f3fSDimitry Andric // Try to collect variable and constant offsets for \p GEP, partly traversing
4005f757f3fSDimitry Andric // nested GEPs. Returns an OffsetResult with nullptr as BasePtr of collecting
4015f757f3fSDimitry Andric // the offset fails.
4025f757f3fSDimitry Andric static OffsetResult collectOffsets(GEPOperator &GEP, const DataLayout &DL) {
4035f757f3fSDimitry Andric   OffsetResult Result(GEP, DL);
4045f757f3fSDimitry Andric   unsigned BitWidth = Result.ConstantOffset.getBitWidth();
4055f757f3fSDimitry Andric   if (!GEP.collectOffset(DL, BitWidth, Result.VariableOffsets,
4065f757f3fSDimitry Andric                          Result.ConstantOffset))
4075f757f3fSDimitry Andric     return {};
4085f757f3fSDimitry Andric 
4095f757f3fSDimitry Andric   // If we have a nested GEP, check if we can combine the constant offset of the
4105f757f3fSDimitry Andric   // inner GEP with the outer GEP.
4115f757f3fSDimitry Andric   if (auto *InnerGEP = dyn_cast<GetElementPtrInst>(Result.BasePtr)) {
4125f757f3fSDimitry Andric     MapVector<Value *, APInt> VariableOffsets2;
4135f757f3fSDimitry Andric     APInt ConstantOffset2(BitWidth, 0);
4145f757f3fSDimitry Andric     bool CanCollectInner = InnerGEP->collectOffset(
4155f757f3fSDimitry Andric         DL, BitWidth, VariableOffsets2, ConstantOffset2);
4165f757f3fSDimitry Andric     // TODO: Support cases with more than 1 variable offset.
4175f757f3fSDimitry Andric     if (!CanCollectInner || Result.VariableOffsets.size() > 1 ||
4185f757f3fSDimitry Andric         VariableOffsets2.size() > 1 ||
4195f757f3fSDimitry Andric         (Result.VariableOffsets.size() >= 1 && VariableOffsets2.size() >= 1)) {
4205f757f3fSDimitry Andric       // More than 1 variable index, use outer result.
4215f757f3fSDimitry Andric       return Result;
4225f757f3fSDimitry Andric     }
4235f757f3fSDimitry Andric     Result.BasePtr = InnerGEP->getPointerOperand();
4245f757f3fSDimitry Andric     Result.ConstantOffset += ConstantOffset2;
4255f757f3fSDimitry Andric     if (Result.VariableOffsets.size() == 0 && VariableOffsets2.size() == 1)
4265f757f3fSDimitry Andric       Result.VariableOffsets = VariableOffsets2;
4275f757f3fSDimitry Andric     Result.AllInbounds &= InnerGEP->isInBounds();
4285f757f3fSDimitry Andric   }
4295f757f3fSDimitry Andric   return Result;
4305f757f3fSDimitry Andric }
4315f757f3fSDimitry Andric 
432bdd1243dSDimitry Andric static Decomposition decompose(Value *V,
4335f757f3fSDimitry Andric                                SmallVectorImpl<ConditionTy> &Preconditions,
434bdd1243dSDimitry Andric                                bool IsSigned, const DataLayout &DL);
43581ad6265SDimitry Andric 
436bdd1243dSDimitry Andric static bool canUseSExt(ConstantInt *CI) {
43781ad6265SDimitry Andric   const APInt &Val = CI->getValue();
43881ad6265SDimitry Andric   return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue);
439bdd1243dSDimitry Andric }
440bdd1243dSDimitry Andric 
4415f757f3fSDimitry Andric static Decomposition decomposeGEP(GEPOperator &GEP,
4425f757f3fSDimitry Andric                                   SmallVectorImpl<ConditionTy> &Preconditions,
44306c3fb27SDimitry Andric                                   bool IsSigned, const DataLayout &DL) {
444bdd1243dSDimitry Andric   // Do not reason about pointers where the index size is larger than 64 bits,
445bdd1243dSDimitry Andric   // as the coefficients used to encode constraints are 64 bit integers.
446bdd1243dSDimitry Andric   if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64)
447bdd1243dSDimitry Andric     return &GEP;
448bdd1243dSDimitry Andric 
449bdd1243dSDimitry Andric   assert(!IsSigned && "The logic below only supports decomposition for "
4505f757f3fSDimitry Andric                       "unsigned predicates at the moment.");
4515f757f3fSDimitry Andric   const auto &[BasePtr, ConstantOffset, VariableOffsets, AllInbounds] =
4525f757f3fSDimitry Andric       collectOffsets(GEP, DL);
4535f757f3fSDimitry Andric   if (!BasePtr || !AllInbounds)
454bdd1243dSDimitry Andric     return &GEP;
455bdd1243dSDimitry Andric 
4565f757f3fSDimitry Andric   Decomposition Result(ConstantOffset.getSExtValue(), DecompEntry(1, BasePtr));
457bdd1243dSDimitry Andric   for (auto [Index, Scale] : VariableOffsets) {
458bdd1243dSDimitry Andric     auto IdxResult = decompose(Index, Preconditions, IsSigned, DL);
459bdd1243dSDimitry Andric     IdxResult.mul(Scale.getSExtValue());
460bdd1243dSDimitry Andric     Result.add(IdxResult);
461bdd1243dSDimitry Andric 
462bdd1243dSDimitry Andric     // If Op0 is signed non-negative, the GEP is increasing monotonically and
463bdd1243dSDimitry Andric     // can be de-composed.
464bdd1243dSDimitry Andric     if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
465bdd1243dSDimitry Andric       Preconditions.emplace_back(CmpInst::ICMP_SGE, Index,
466bdd1243dSDimitry Andric                                  ConstantInt::get(Index->getType(), 0));
467bdd1243dSDimitry Andric   }
468bdd1243dSDimitry Andric   return Result;
469bdd1243dSDimitry Andric }
470bdd1243dSDimitry Andric 
471bdd1243dSDimitry Andric // Decomposes \p V into a constant offset + list of pairs { Coefficient,
472bdd1243dSDimitry Andric // Variable } where Coefficient * Variable. The sum of the constant offset and
473bdd1243dSDimitry Andric // pairs equals \p V.
474bdd1243dSDimitry Andric static Decomposition decompose(Value *V,
4755f757f3fSDimitry Andric                                SmallVectorImpl<ConditionTy> &Preconditions,
476bdd1243dSDimitry Andric                                bool IsSigned, const DataLayout &DL) {
477bdd1243dSDimitry Andric 
478bdd1243dSDimitry Andric   auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B,
479bdd1243dSDimitry Andric                                                       bool IsSignedB) {
480bdd1243dSDimitry Andric     auto ResA = decompose(A, Preconditions, IsSigned, DL);
481bdd1243dSDimitry Andric     auto ResB = decompose(B, Preconditions, IsSignedB, DL);
482bdd1243dSDimitry Andric     ResA.add(ResB);
483bdd1243dSDimitry Andric     return ResA;
48481ad6265SDimitry Andric   };
485bdd1243dSDimitry Andric 
486b121cb00SDimitry Andric   Type *Ty = V->getType()->getScalarType();
487b121cb00SDimitry Andric   if (Ty->isPointerTy() && !IsSigned) {
488b121cb00SDimitry Andric     if (auto *GEP = dyn_cast<GEPOperator>(V))
489b121cb00SDimitry Andric       return decomposeGEP(*GEP, Preconditions, IsSigned, DL);
4905f757f3fSDimitry Andric     if (isa<ConstantPointerNull>(V))
4915f757f3fSDimitry Andric       return int64_t(0);
4925f757f3fSDimitry Andric 
493b121cb00SDimitry Andric     return V;
494b121cb00SDimitry Andric   }
495b121cb00SDimitry Andric 
496b121cb00SDimitry Andric   // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so
497b121cb00SDimitry Andric   // coefficient add/mul may wrap, while the operation in the full bit width
498b121cb00SDimitry Andric   // would not.
499b121cb00SDimitry Andric   if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64)
500b121cb00SDimitry Andric     return V;
501b121cb00SDimitry Andric 
50281ad6265SDimitry Andric   // Decompose \p V used with a signed predicate.
50381ad6265SDimitry Andric   if (IsSigned) {
504e8d8bef9SDimitry Andric     if (auto *CI = dyn_cast<ConstantInt>(V)) {
505bdd1243dSDimitry Andric       if (canUseSExt(CI))
506bdd1243dSDimitry Andric         return CI->getSExtValue();
507e8d8bef9SDimitry Andric     }
508bdd1243dSDimitry Andric     Value *Op0;
509bdd1243dSDimitry Andric     Value *Op1;
510bdd1243dSDimitry Andric     if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1))))
511bdd1243dSDimitry Andric       return MergeResults(Op0, Op1, IsSigned);
51281ad6265SDimitry Andric 
51306c3fb27SDimitry Andric     ConstantInt *CI;
5148a4dda33SDimitry Andric     if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) {
51506c3fb27SDimitry Andric       auto Result = decompose(Op0, Preconditions, IsSigned, DL);
51606c3fb27SDimitry Andric       Result.mul(CI->getSExtValue());
51706c3fb27SDimitry Andric       return Result;
51806c3fb27SDimitry Andric     }
51906c3fb27SDimitry Andric 
520bdd1243dSDimitry Andric     return V;
52181ad6265SDimitry Andric   }
52281ad6265SDimitry Andric 
52381ad6265SDimitry Andric   if (auto *CI = dyn_cast<ConstantInt>(V)) {
52481ad6265SDimitry Andric     if (CI->uge(MaxConstraintValue))
525bdd1243dSDimitry Andric       return V;
526bdd1243dSDimitry Andric     return int64_t(CI->getZExtValue());
527fe6060f1SDimitry Andric   }
528fe6060f1SDimitry Andric 
529e8d8bef9SDimitry Andric   Value *Op0;
530bdd1243dSDimitry Andric   bool IsKnownNonNegative = false;
531bdd1243dSDimitry Andric   if (match(V, m_ZExt(m_Value(Op0)))) {
532bdd1243dSDimitry Andric     IsKnownNonNegative = true;
533fe6060f1SDimitry Andric     V = Op0;
534bdd1243dSDimitry Andric   }
535fe6060f1SDimitry Andric 
536e8d8bef9SDimitry Andric   Value *Op1;
537e8d8bef9SDimitry Andric   ConstantInt *CI;
538bdd1243dSDimitry Andric   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) {
539bdd1243dSDimitry Andric     return MergeResults(Op0, Op1, IsSigned);
540bdd1243dSDimitry Andric   }
541bdd1243dSDimitry Andric   if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) {
542bdd1243dSDimitry Andric     if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
543bdd1243dSDimitry Andric       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0,
544bdd1243dSDimitry Andric                                  ConstantInt::get(Op0->getType(), 0));
545bdd1243dSDimitry Andric     if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
546bdd1243dSDimitry Andric       Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1,
547bdd1243dSDimitry Andric                                  ConstantInt::get(Op1->getType(), 0));
548bdd1243dSDimitry Andric 
549bdd1243dSDimitry Andric     return MergeResults(Op0, Op1, IsSigned);
550bdd1243dSDimitry Andric   }
551bdd1243dSDimitry Andric 
55281ad6265SDimitry Andric   if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() &&
553bdd1243dSDimitry Andric       canUseSExt(CI)) {
55481ad6265SDimitry Andric     Preconditions.emplace_back(
55581ad6265SDimitry Andric         CmpInst::ICMP_UGE, Op0,
55681ad6265SDimitry Andric         ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1));
557bdd1243dSDimitry Andric     return MergeResults(Op0, CI, true);
55881ad6265SDimitry Andric   }
559e8d8bef9SDimitry Andric 
56006c3fb27SDimitry Andric   // Decompose or as an add if there are no common bits between the operands.
5615f757f3fSDimitry Andric   if (match(V, m_DisjointOr(m_Value(Op0), m_ConstantInt(CI))))
56206c3fb27SDimitry Andric     return MergeResults(Op0, CI, IsSigned);
56306c3fb27SDimitry Andric 
564bdd1243dSDimitry Andric   if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) {
56506c3fb27SDimitry Andric     if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64)
56606c3fb27SDimitry Andric       return {V, IsKnownNonNegative};
567bdd1243dSDimitry Andric     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
56806c3fb27SDimitry Andric     Result.mul(int64_t{1} << CI->getSExtValue());
569bdd1243dSDimitry Andric     return Result;
570bdd1243dSDimitry Andric   }
571bdd1243dSDimitry Andric 
572bdd1243dSDimitry Andric   if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) &&
573bdd1243dSDimitry Andric       (!CI->isNegative())) {
574bdd1243dSDimitry Andric     auto Result = decompose(Op1, Preconditions, IsSigned, DL);
575bdd1243dSDimitry Andric     Result.mul(CI->getSExtValue());
576bdd1243dSDimitry Andric     return Result;
577bdd1243dSDimitry Andric   }
578bdd1243dSDimitry Andric 
579*647cbc5dSDimitry Andric   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) {
580*647cbc5dSDimitry Andric     auto ResA = decompose(Op0, Preconditions, IsSigned, DL);
581*647cbc5dSDimitry Andric     auto ResB = decompose(Op1, Preconditions, IsSigned, DL);
582*647cbc5dSDimitry Andric     ResA.sub(ResB);
583*647cbc5dSDimitry Andric     return ResA;
584*647cbc5dSDimitry Andric   }
585e8d8bef9SDimitry Andric 
586bdd1243dSDimitry Andric   return {V, IsKnownNonNegative};
587e8d8bef9SDimitry Andric }
588e8d8bef9SDimitry Andric 
58981ad6265SDimitry Andric ConstraintTy
59081ad6265SDimitry Andric ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
591bdd1243dSDimitry Andric                               SmallVectorImpl<Value *> &NewVariables) const {
592bdd1243dSDimitry Andric   assert(NewVariables.empty() && "NewVariables must be empty when passed in");
59381ad6265SDimitry Andric   bool IsEq = false;
59406c3fb27SDimitry Andric   bool IsNe = false;
59506c3fb27SDimitry Andric 
59681ad6265SDimitry Andric   // Try to convert Pred to one of ULE/SLT/SLE/SLT.
59781ad6265SDimitry Andric   switch (Pred) {
59881ad6265SDimitry Andric   case CmpInst::ICMP_UGT:
59981ad6265SDimitry Andric   case CmpInst::ICMP_UGE:
60081ad6265SDimitry Andric   case CmpInst::ICMP_SGT:
60181ad6265SDimitry Andric   case CmpInst::ICMP_SGE: {
60281ad6265SDimitry Andric     Pred = CmpInst::getSwappedPredicate(Pred);
60381ad6265SDimitry Andric     std::swap(Op0, Op1);
60481ad6265SDimitry Andric     break;
60581ad6265SDimitry Andric   }
60681ad6265SDimitry Andric   case CmpInst::ICMP_EQ:
60781ad6265SDimitry Andric     if (match(Op1, m_Zero())) {
60881ad6265SDimitry Andric       Pred = CmpInst::ICMP_ULE;
60981ad6265SDimitry Andric     } else {
61081ad6265SDimitry Andric       IsEq = true;
61181ad6265SDimitry Andric       Pred = CmpInst::ICMP_ULE;
61281ad6265SDimitry Andric     }
61381ad6265SDimitry Andric     break;
61481ad6265SDimitry Andric   case CmpInst::ICMP_NE:
61506c3fb27SDimitry Andric     if (match(Op1, m_Zero())) {
61681ad6265SDimitry Andric       Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT);
61781ad6265SDimitry Andric       std::swap(Op0, Op1);
61806c3fb27SDimitry Andric     } else {
61906c3fb27SDimitry Andric       IsNe = true;
62006c3fb27SDimitry Andric       Pred = CmpInst::ICMP_ULE;
62106c3fb27SDimitry Andric     }
62281ad6265SDimitry Andric     break;
62381ad6265SDimitry Andric   default:
62481ad6265SDimitry Andric     break;
62581ad6265SDimitry Andric   }
62681ad6265SDimitry Andric 
62781ad6265SDimitry Andric   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT &&
62881ad6265SDimitry Andric       Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT)
62981ad6265SDimitry Andric     return {};
63081ad6265SDimitry Andric 
6315f757f3fSDimitry Andric   SmallVector<ConditionTy, 4> Preconditions;
63281ad6265SDimitry Andric   bool IsSigned = CmpInst::isSigned(Pred);
63381ad6265SDimitry Andric   auto &Value2Index = getValue2Index(IsSigned);
63481ad6265SDimitry Andric   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(),
635bdd1243dSDimitry Andric                         Preconditions, IsSigned, DL);
63681ad6265SDimitry Andric   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(),
637bdd1243dSDimitry Andric                         Preconditions, IsSigned, DL);
638bdd1243dSDimitry Andric   int64_t Offset1 = ADec.Offset;
639bdd1243dSDimitry Andric   int64_t Offset2 = BDec.Offset;
64081ad6265SDimitry Andric   Offset1 *= -1;
64181ad6265SDimitry Andric 
642bdd1243dSDimitry Andric   auto &VariablesA = ADec.Vars;
643bdd1243dSDimitry Andric   auto &VariablesB = BDec.Vars;
644e8d8bef9SDimitry Andric 
645bdd1243dSDimitry Andric   // First try to look up \p V in Value2Index and NewVariables. Otherwise add a
646bdd1243dSDimitry Andric   // new entry to NewVariables.
647bdd1243dSDimitry Andric   DenseMap<Value *, unsigned> NewIndexMap;
648bdd1243dSDimitry Andric   auto GetOrAddIndex = [&Value2Index, &NewVariables,
649bdd1243dSDimitry Andric                         &NewIndexMap](Value *V) -> unsigned {
650fe6060f1SDimitry Andric     auto V2I = Value2Index.find(V);
651fe6060f1SDimitry Andric     if (V2I != Value2Index.end())
652fe6060f1SDimitry Andric       return V2I->second;
653fe6060f1SDimitry Andric     auto Insert =
654bdd1243dSDimitry Andric         NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1});
655bdd1243dSDimitry Andric     if (Insert.second)
656bdd1243dSDimitry Andric       NewVariables.push_back(V);
657fe6060f1SDimitry Andric     return Insert.first->second;
658e8d8bef9SDimitry Andric   };
659e8d8bef9SDimitry Andric 
660bdd1243dSDimitry Andric   // Make sure all variables have entries in Value2Index or NewVariables.
661bdd1243dSDimitry Andric   for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB))
662bdd1243dSDimitry Andric     GetOrAddIndex(KV.Variable);
663e8d8bef9SDimitry Andric 
664e8d8bef9SDimitry Andric   // Build result constraint, by first adding all coefficients from A and then
665e8d8bef9SDimitry Andric   // subtracting all coefficients from B.
66681ad6265SDimitry Andric   ConstraintTy Res(
667bdd1243dSDimitry Andric       SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0),
66806c3fb27SDimitry Andric       IsSigned, IsEq, IsNe);
669bdd1243dSDimitry Andric   // Collect variables that are known to be positive in all uses in the
670bdd1243dSDimitry Andric   // constraint.
671bdd1243dSDimitry Andric   DenseMap<Value *, bool> KnownNonNegativeVariables;
67281ad6265SDimitry Andric   auto &R = Res.Coefficients;
673bdd1243dSDimitry Andric   for (const auto &KV : VariablesA) {
674bdd1243dSDimitry Andric     R[GetOrAddIndex(KV.Variable)] += KV.Coefficient;
675bdd1243dSDimitry Andric     auto I =
676bdd1243dSDimitry Andric         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
677bdd1243dSDimitry Andric     I.first->second &= KV.IsKnownNonNegative;
678bdd1243dSDimitry Andric   }
679e8d8bef9SDimitry Andric 
680bdd1243dSDimitry Andric   for (const auto &KV : VariablesB) {
68106c3fb27SDimitry Andric     if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient,
68206c3fb27SDimitry Andric                     R[GetOrAddIndex(KV.Variable)]))
68306c3fb27SDimitry Andric       return {};
684bdd1243dSDimitry Andric     auto I =
685bdd1243dSDimitry Andric         KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative});
686bdd1243dSDimitry Andric     I.first->second &= KV.IsKnownNonNegative;
687bdd1243dSDimitry Andric   }
688e8d8bef9SDimitry Andric 
68981ad6265SDimitry Andric   int64_t OffsetSum;
69081ad6265SDimitry Andric   if (AddOverflow(Offset1, Offset2, OffsetSum))
69181ad6265SDimitry Andric     return {};
69281ad6265SDimitry Andric   if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT))
69381ad6265SDimitry Andric     if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum))
69481ad6265SDimitry Andric       return {};
69581ad6265SDimitry Andric   R[0] = OffsetSum;
69681ad6265SDimitry Andric   Res.Preconditions = std::move(Preconditions);
697bdd1243dSDimitry Andric 
698bdd1243dSDimitry Andric   // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new
699bdd1243dSDimitry Andric   // variables.
700bdd1243dSDimitry Andric   while (!NewVariables.empty()) {
701bdd1243dSDimitry Andric     int64_t Last = R.back();
702bdd1243dSDimitry Andric     if (Last != 0)
703bdd1243dSDimitry Andric       break;
704bdd1243dSDimitry Andric     R.pop_back();
705bdd1243dSDimitry Andric     Value *RemovedV = NewVariables.pop_back_val();
706bdd1243dSDimitry Andric     NewIndexMap.erase(RemovedV);
707bdd1243dSDimitry Andric   }
708bdd1243dSDimitry Andric 
709bdd1243dSDimitry Andric   // Add extra constraints for variables that are known positive.
710bdd1243dSDimitry Andric   for (auto &KV : KnownNonNegativeVariables) {
71106c3fb27SDimitry Andric     if (!KV.second ||
71206c3fb27SDimitry Andric         (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first)))
713bdd1243dSDimitry Andric       continue;
714bdd1243dSDimitry Andric     SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0);
715bdd1243dSDimitry Andric     C[GetOrAddIndex(KV.first)] = -1;
716bdd1243dSDimitry Andric     Res.ExtraInfo.push_back(C);
717bdd1243dSDimitry Andric   }
71881ad6265SDimitry Andric   return Res;
719e8d8bef9SDimitry Andric }
720e8d8bef9SDimitry Andric 
721bdd1243dSDimitry Andric ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred,
722bdd1243dSDimitry Andric                                                      Value *Op0,
723bdd1243dSDimitry Andric                                                      Value *Op1) const {
7245f757f3fSDimitry Andric   Constant *NullC = Constant::getNullValue(Op0->getType());
7255f757f3fSDimitry Andric   // Handle trivially true compares directly to avoid adding V UGE 0 constraints
7265f757f3fSDimitry Andric   // for all variables in the unsigned system.
7275f757f3fSDimitry Andric   if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) ||
7285f757f3fSDimitry Andric       (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) {
7295f757f3fSDimitry Andric     auto &Value2Index = getValue2Index(false);
7305f757f3fSDimitry Andric     // Return constraint that's trivially true.
7315f757f3fSDimitry Andric     return ConstraintTy(SmallVector<int64_t, 8>(Value2Index.size(), 0), false,
7325f757f3fSDimitry Andric                         false, false);
7335f757f3fSDimitry Andric   }
7345f757f3fSDimitry Andric 
735bdd1243dSDimitry Andric   // If both operands are known to be non-negative, change signed predicates to
736bdd1243dSDimitry Andric   // unsigned ones. This increases the reasoning effectiveness in combination
737bdd1243dSDimitry Andric   // with the signed <-> unsigned transfer logic.
738bdd1243dSDimitry Andric   if (CmpInst::isSigned(Pred) &&
739bdd1243dSDimitry Andric       isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) &&
740bdd1243dSDimitry Andric       isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1))
741bdd1243dSDimitry Andric     Pred = CmpInst::getUnsignedPredicate(Pred);
742bdd1243dSDimitry Andric 
743bdd1243dSDimitry Andric   SmallVector<Value *> NewVariables;
744bdd1243dSDimitry Andric   ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables);
74506c3fb27SDimitry Andric   if (!NewVariables.empty())
746bdd1243dSDimitry Andric     return {};
747bdd1243dSDimitry Andric   return R;
748bdd1243dSDimitry Andric }
749bdd1243dSDimitry Andric 
75081ad6265SDimitry Andric bool ConstraintTy::isValid(const ConstraintInfo &Info) const {
75181ad6265SDimitry Andric   return Coefficients.size() > 0 &&
7525f757f3fSDimitry Andric          all_of(Preconditions, [&Info](const ConditionTy &C) {
75381ad6265SDimitry Andric            return Info.doesHold(C.Pred, C.Op0, C.Op1);
75481ad6265SDimitry Andric          });
75581ad6265SDimitry Andric }
75681ad6265SDimitry Andric 
75706c3fb27SDimitry Andric std::optional<bool>
75806c3fb27SDimitry Andric ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const {
75906c3fb27SDimitry Andric   bool IsConditionImplied = CS.isConditionImplied(Coefficients);
76006c3fb27SDimitry Andric 
76106c3fb27SDimitry Andric   if (IsEq || IsNe) {
76206c3fb27SDimitry Andric     auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients);
76306c3fb27SDimitry Andric     bool IsNegatedOrEqualImplied =
76406c3fb27SDimitry Andric         !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual);
76506c3fb27SDimitry Andric 
76606c3fb27SDimitry Andric     // In order to check that `%a == %b` is true (equality), both conditions `%a
76706c3fb27SDimitry Andric     // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq`
76806c3fb27SDimitry Andric     // is true), we return true if they both hold, false in the other cases.
76906c3fb27SDimitry Andric     if (IsConditionImplied && IsNegatedOrEqualImplied)
77006c3fb27SDimitry Andric       return IsEq;
77106c3fb27SDimitry Andric 
77206c3fb27SDimitry Andric     auto Negated = ConstraintSystem::negate(Coefficients);
77306c3fb27SDimitry Andric     bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
77406c3fb27SDimitry Andric 
77506c3fb27SDimitry Andric     auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients);
77606c3fb27SDimitry Andric     bool IsStrictLessThanImplied =
77706c3fb27SDimitry Andric         !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan);
77806c3fb27SDimitry Andric 
77906c3fb27SDimitry Andric     // In order to check that `%a != %b` is true (non-equality), either
78006c3fb27SDimitry Andric     // condition `%a > %b` or `%a < %b` must hold true. When checking for
78106c3fb27SDimitry Andric     // non-equality (`IsNe` is true), we return true if one of the two holds,
78206c3fb27SDimitry Andric     // false in the other cases.
78306c3fb27SDimitry Andric     if (IsNegatedImplied || IsStrictLessThanImplied)
78406c3fb27SDimitry Andric       return IsNe;
78506c3fb27SDimitry Andric 
78606c3fb27SDimitry Andric     return std::nullopt;
78706c3fb27SDimitry Andric   }
78806c3fb27SDimitry Andric 
78906c3fb27SDimitry Andric   if (IsConditionImplied)
79006c3fb27SDimitry Andric     return true;
79106c3fb27SDimitry Andric 
79206c3fb27SDimitry Andric   auto Negated = ConstraintSystem::negate(Coefficients);
79306c3fb27SDimitry Andric   auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated);
79406c3fb27SDimitry Andric   if (IsNegatedImplied)
79506c3fb27SDimitry Andric     return false;
79606c3fb27SDimitry Andric 
79706c3fb27SDimitry Andric   // Neither the condition nor its negated holds, did not prove anything.
79806c3fb27SDimitry Andric   return std::nullopt;
79906c3fb27SDimitry Andric }
80006c3fb27SDimitry Andric 
80181ad6265SDimitry Andric bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A,
80281ad6265SDimitry Andric                               Value *B) const {
803bdd1243dSDimitry Andric   auto R = getConstraintForSolving(Pred, A, B);
80406c3fb27SDimitry Andric   return R.isValid(*this) &&
805bdd1243dSDimitry Andric          getCS(R.IsSigned).isConditionImplied(R.Coefficients);
80681ad6265SDimitry Andric }
80781ad6265SDimitry Andric 
80881ad6265SDimitry Andric void ConstraintInfo::transferToOtherSystem(
809bdd1243dSDimitry Andric     CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn,
81081ad6265SDimitry Andric     unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) {
8115f757f3fSDimitry Andric   auto IsKnownNonNegative = [this](Value *V) {
8125f757f3fSDimitry Andric     return doesHold(CmpInst::ICMP_SGE, V, ConstantInt::get(V->getType(), 0)) ||
8135f757f3fSDimitry Andric            isKnownNonNegative(V, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1);
8145f757f3fSDimitry Andric   };
81581ad6265SDimitry Andric   // Check if we can combine facts from the signed and unsigned systems to
81681ad6265SDimitry Andric   // derive additional facts.
81781ad6265SDimitry Andric   if (!A->getType()->isIntegerTy())
81881ad6265SDimitry Andric     return;
81981ad6265SDimitry Andric   // FIXME: This currently depends on the order we add facts. Ideally we
82081ad6265SDimitry Andric   // would first add all known facts and only then try to add additional
82181ad6265SDimitry Andric   // facts.
82281ad6265SDimitry Andric   switch (Pred) {
82381ad6265SDimitry Andric   default:
82481ad6265SDimitry Andric     break;
82581ad6265SDimitry Andric   case CmpInst::ICMP_ULT:
8265f757f3fSDimitry Andric   case CmpInst::ICMP_ULE:
8275f757f3fSDimitry Andric     //  If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B.
8285f757f3fSDimitry Andric     if (IsKnownNonNegative(B)) {
829bdd1243dSDimitry Andric       addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn,
830bdd1243dSDimitry Andric               NumOut, DFSInStack);
8315f757f3fSDimitry Andric       addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
8325f757f3fSDimitry Andric               DFSInStack);
8335f757f3fSDimitry Andric     }
8345f757f3fSDimitry Andric     break;
8355f757f3fSDimitry Andric   case CmpInst::ICMP_UGE:
8365f757f3fSDimitry Andric   case CmpInst::ICMP_UGT:
8375f757f3fSDimitry Andric     //  If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B.
8385f757f3fSDimitry Andric     if (IsKnownNonNegative(A)) {
8395f757f3fSDimitry Andric       addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn,
8405f757f3fSDimitry Andric               NumOut, DFSInStack);
8415f757f3fSDimitry Andric       addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut,
8425f757f3fSDimitry Andric               DFSInStack);
84381ad6265SDimitry Andric     }
84481ad6265SDimitry Andric     break;
84581ad6265SDimitry Andric   case CmpInst::ICMP_SLT:
8465f757f3fSDimitry Andric     if (IsKnownNonNegative(A))
847bdd1243dSDimitry Andric       addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack);
84881ad6265SDimitry Andric     break;
84906c3fb27SDimitry Andric   case CmpInst::ICMP_SGT: {
85081ad6265SDimitry Andric     if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1)))
851bdd1243dSDimitry Andric       addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn,
852bdd1243dSDimitry Andric               NumOut, DFSInStack);
8535f757f3fSDimitry Andric     if (IsKnownNonNegative(B))
85406c3fb27SDimitry Andric       addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack);
85506c3fb27SDimitry Andric 
85681ad6265SDimitry Andric     break;
85706c3fb27SDimitry Andric   }
85881ad6265SDimitry Andric   case CmpInst::ICMP_SGE:
8595f757f3fSDimitry Andric     if (IsKnownNonNegative(B))
860bdd1243dSDimitry Andric       addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack);
86181ad6265SDimitry Andric     break;
86281ad6265SDimitry Andric   }
863e8d8bef9SDimitry Andric }
864e8d8bef9SDimitry Andric 
865fe6060f1SDimitry Andric #ifndef NDEBUG
86681ad6265SDimitry Andric 
86706c3fb27SDimitry Andric static void dumpConstraint(ArrayRef<int64_t> C,
86806c3fb27SDimitry Andric                            const DenseMap<Value *, unsigned> &Value2Index) {
86906c3fb27SDimitry Andric   ConstraintSystem CS(Value2Index);
87081ad6265SDimitry Andric   CS.addVariableRowFill(C);
87106c3fb27SDimitry Andric   CS.dump();
87281ad6265SDimitry Andric }
873fe6060f1SDimitry Andric #endif
874fe6060f1SDimitry Andric 
8755f757f3fSDimitry Andric void State::addInfoForInductions(BasicBlock &BB) {
8765f757f3fSDimitry Andric   auto *L = LI.getLoopFor(&BB);
8775f757f3fSDimitry Andric   if (!L || L->getHeader() != &BB)
8785f757f3fSDimitry Andric     return;
8795f757f3fSDimitry Andric 
8805f757f3fSDimitry Andric   Value *A;
8815f757f3fSDimitry Andric   Value *B;
8825f757f3fSDimitry Andric   CmpInst::Predicate Pred;
8835f757f3fSDimitry Andric 
8845f757f3fSDimitry Andric   if (!match(BB.getTerminator(),
8855f757f3fSDimitry Andric              m_Br(m_ICmp(Pred, m_Value(A), m_Value(B)), m_Value(), m_Value())))
8865f757f3fSDimitry Andric     return;
8875f757f3fSDimitry Andric   PHINode *PN = dyn_cast<PHINode>(A);
8885f757f3fSDimitry Andric   if (!PN) {
8895f757f3fSDimitry Andric     Pred = CmpInst::getSwappedPredicate(Pred);
8905f757f3fSDimitry Andric     std::swap(A, B);
8915f757f3fSDimitry Andric     PN = dyn_cast<PHINode>(A);
8925f757f3fSDimitry Andric   }
8935f757f3fSDimitry Andric 
8945f757f3fSDimitry Andric   if (!PN || PN->getParent() != &BB || PN->getNumIncomingValues() != 2 ||
8955f757f3fSDimitry Andric       !SE.isSCEVable(PN->getType()))
8965f757f3fSDimitry Andric     return;
8975f757f3fSDimitry Andric 
8985f757f3fSDimitry Andric   BasicBlock *InLoopSucc = nullptr;
8995f757f3fSDimitry Andric   if (Pred == CmpInst::ICMP_NE)
9005f757f3fSDimitry Andric     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(0);
9015f757f3fSDimitry Andric   else if (Pred == CmpInst::ICMP_EQ)
9025f757f3fSDimitry Andric     InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(1);
9035f757f3fSDimitry Andric   else
9045f757f3fSDimitry Andric     return;
9055f757f3fSDimitry Andric 
9065f757f3fSDimitry Andric   if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB)
9075f757f3fSDimitry Andric     return;
9085f757f3fSDimitry Andric 
9095f757f3fSDimitry Andric   auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN));
9105f757f3fSDimitry Andric   BasicBlock *LoopPred = L->getLoopPredecessor();
9115f757f3fSDimitry Andric   if (!AR || AR->getLoop() != L || !LoopPred)
9125f757f3fSDimitry Andric     return;
9135f757f3fSDimitry Andric 
9145f757f3fSDimitry Andric   const SCEV *StartSCEV = AR->getStart();
9155f757f3fSDimitry Andric   Value *StartValue = nullptr;
9165f757f3fSDimitry Andric   if (auto *C = dyn_cast<SCEVConstant>(StartSCEV)) {
9175f757f3fSDimitry Andric     StartValue = C->getValue();
9185f757f3fSDimitry Andric   } else {
9195f757f3fSDimitry Andric     StartValue = PN->getIncomingValueForBlock(LoopPred);
9205f757f3fSDimitry Andric     assert(SE.getSCEV(StartValue) == StartSCEV && "inconsistent start value");
9215f757f3fSDimitry Andric   }
9225f757f3fSDimitry Andric 
9235f757f3fSDimitry Andric   DomTreeNode *DTN = DT.getNode(InLoopSucc);
9245f757f3fSDimitry Andric   auto Inc = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_UGT);
9255f757f3fSDimitry Andric   bool MonotonicallyIncreasing =
9265f757f3fSDimitry Andric       Inc && *Inc == ScalarEvolution::MonotonicallyIncreasing;
9275f757f3fSDimitry Andric   if (MonotonicallyIncreasing) {
9285f757f3fSDimitry Andric     // SCEV guarantees that AR does not wrap, so PN >= StartValue can be added
9295f757f3fSDimitry Andric     // unconditionally.
9305f757f3fSDimitry Andric     WorkList.push_back(
9315f757f3fSDimitry Andric         FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGE, PN, StartValue));
9325f757f3fSDimitry Andric   }
9335f757f3fSDimitry Andric 
9345f757f3fSDimitry Andric   APInt StepOffset;
9355f757f3fSDimitry Andric   if (auto *C = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
9365f757f3fSDimitry Andric     StepOffset = C->getAPInt();
9375f757f3fSDimitry Andric   else
9385f757f3fSDimitry Andric     return;
9395f757f3fSDimitry Andric 
9405f757f3fSDimitry Andric   // Make sure the bound B is loop-invariant.
9415f757f3fSDimitry Andric   if (!L->isLoopInvariant(B))
9425f757f3fSDimitry Andric     return;
9435f757f3fSDimitry Andric 
9445f757f3fSDimitry Andric   // Handle negative steps.
9455f757f3fSDimitry Andric   if (StepOffset.isNegative()) {
9465f757f3fSDimitry Andric     // TODO: Extend to allow steps > -1.
9475f757f3fSDimitry Andric     if (!(-StepOffset).isOne())
9485f757f3fSDimitry Andric       return;
9495f757f3fSDimitry Andric 
9505f757f3fSDimitry Andric     // AR may wrap.
9515f757f3fSDimitry Andric     // Add StartValue >= PN conditional on B <= StartValue which guarantees that
9525f757f3fSDimitry Andric     // the loop exits before wrapping with a step of -1.
9535f757f3fSDimitry Andric     WorkList.push_back(FactOrCheck::getConditionFact(
9545f757f3fSDimitry Andric         DTN, CmpInst::ICMP_UGE, StartValue, PN,
9555f757f3fSDimitry Andric         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
9565f757f3fSDimitry Andric     // Add PN > B conditional on B <= StartValue which guarantees that the loop
9575f757f3fSDimitry Andric     // exits when reaching B with a step of -1.
9585f757f3fSDimitry Andric     WorkList.push_back(FactOrCheck::getConditionFact(
9595f757f3fSDimitry Andric         DTN, CmpInst::ICMP_UGT, PN, B,
9605f757f3fSDimitry Andric         ConditionTy(CmpInst::ICMP_ULE, B, StartValue)));
9615f757f3fSDimitry Andric     return;
9625f757f3fSDimitry Andric   }
9635f757f3fSDimitry Andric 
9645f757f3fSDimitry Andric   // Make sure AR either steps by 1 or that the value we compare against is a
9655f757f3fSDimitry Andric   // GEP based on the same start value and all offsets are a multiple of the
9665f757f3fSDimitry Andric   // step size, to guarantee that the induction will reach the value.
9675f757f3fSDimitry Andric   if (StepOffset.isZero() || StepOffset.isNegative())
9685f757f3fSDimitry Andric     return;
9695f757f3fSDimitry Andric 
9705f757f3fSDimitry Andric   if (!StepOffset.isOne()) {
9715f757f3fSDimitry Andric     auto *UpperGEP = dyn_cast<GetElementPtrInst>(B);
9725f757f3fSDimitry Andric     if (!UpperGEP || UpperGEP->getPointerOperand() != StartValue ||
9735f757f3fSDimitry Andric         !UpperGEP->isInBounds())
9745f757f3fSDimitry Andric       return;
9755f757f3fSDimitry Andric 
9765f757f3fSDimitry Andric     MapVector<Value *, APInt> UpperVariableOffsets;
9775f757f3fSDimitry Andric     APInt UpperConstantOffset(StepOffset.getBitWidth(), 0);
9785f757f3fSDimitry Andric     const DataLayout &DL = BB.getModule()->getDataLayout();
9795f757f3fSDimitry Andric     if (!UpperGEP->collectOffset(DL, StepOffset.getBitWidth(),
9805f757f3fSDimitry Andric                                  UpperVariableOffsets, UpperConstantOffset))
9815f757f3fSDimitry Andric       return;
9825f757f3fSDimitry Andric     // All variable offsets and the constant offset have to be a multiple of the
9835f757f3fSDimitry Andric     // step.
9845f757f3fSDimitry Andric     if (!UpperConstantOffset.urem(StepOffset).isZero() ||
9855f757f3fSDimitry Andric         any_of(UpperVariableOffsets, [&StepOffset](const auto &P) {
9865f757f3fSDimitry Andric           return !P.second.urem(StepOffset).isZero();
9875f757f3fSDimitry Andric         }))
9885f757f3fSDimitry Andric       return;
9895f757f3fSDimitry Andric   }
9905f757f3fSDimitry Andric 
9915f757f3fSDimitry Andric   // AR may wrap. Add PN >= StartValue conditional on StartValue <= B which
9925f757f3fSDimitry Andric   // guarantees that the loop exits before wrapping in combination with the
9935f757f3fSDimitry Andric   // restrictions on B and the step above.
9945f757f3fSDimitry Andric   if (!MonotonicallyIncreasing) {
9955f757f3fSDimitry Andric     WorkList.push_back(FactOrCheck::getConditionFact(
9965f757f3fSDimitry Andric         DTN, CmpInst::ICMP_UGE, PN, StartValue,
9975f757f3fSDimitry Andric         ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
9985f757f3fSDimitry Andric   }
9995f757f3fSDimitry Andric   WorkList.push_back(FactOrCheck::getConditionFact(
10005f757f3fSDimitry Andric       DTN, CmpInst::ICMP_ULT, PN, B,
10015f757f3fSDimitry Andric       ConditionTy(CmpInst::ICMP_ULE, StartValue, B)));
10025f757f3fSDimitry Andric }
10035f757f3fSDimitry Andric 
100481ad6265SDimitry Andric void State::addInfoFor(BasicBlock &BB) {
10055f757f3fSDimitry Andric   addInfoForInductions(BB);
10065f757f3fSDimitry Andric 
1007349cc55cSDimitry Andric   // True as long as long as the current instruction is guaranteed to execute.
1008349cc55cSDimitry Andric   bool GuaranteedToExecute = true;
1009bdd1243dSDimitry Andric   // Queue conditions and assumes.
1010349cc55cSDimitry Andric   for (Instruction &I : BB) {
1011bdd1243dSDimitry Andric     if (auto Cmp = dyn_cast<ICmpInst>(&I)) {
101206c3fb27SDimitry Andric       for (Use &U : Cmp->uses()) {
101306c3fb27SDimitry Andric         auto *UserI = getContextInstForUse(U);
101406c3fb27SDimitry Andric         auto *DTN = DT.getNode(UserI->getParent());
101506c3fb27SDimitry Andric         if (!DTN)
101606c3fb27SDimitry Andric           continue;
101706c3fb27SDimitry Andric         WorkList.push_back(FactOrCheck::getCheck(DTN, &U));
101806c3fb27SDimitry Andric       }
1019bdd1243dSDimitry Andric       continue;
1020bdd1243dSDimitry Andric     }
1021bdd1243dSDimitry Andric 
1022*647cbc5dSDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(&I);
1023*647cbc5dSDimitry Andric     Intrinsic::ID ID = II ? II->getIntrinsicID() : Intrinsic::not_intrinsic;
1024*647cbc5dSDimitry Andric     switch (ID) {
1025*647cbc5dSDimitry Andric     case Intrinsic::assume: {
10265f757f3fSDimitry Andric       Value *A, *B;
10275f757f3fSDimitry Andric       CmpInst::Predicate Pred;
1028*647cbc5dSDimitry Andric       if (!match(I.getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B))))
1029*647cbc5dSDimitry Andric         break;
1030349cc55cSDimitry Andric       if (GuaranteedToExecute) {
1031349cc55cSDimitry Andric         // The assume is guaranteed to execute when BB is entered, hence Cond
1032349cc55cSDimitry Andric         // holds on entry to BB.
10335f757f3fSDimitry Andric         WorkList.emplace_back(FactOrCheck::getConditionFact(
10345f757f3fSDimitry Andric             DT.getNode(I.getParent()), Pred, A, B));
1035349cc55cSDimitry Andric       } else {
1036bdd1243dSDimitry Andric         WorkList.emplace_back(
10375f757f3fSDimitry Andric             FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I));
1038349cc55cSDimitry Andric       }
1039*647cbc5dSDimitry Andric       break;
1040349cc55cSDimitry Andric     }
1041*647cbc5dSDimitry Andric     // Enqueue ssub_with_overflow for simplification.
1042*647cbc5dSDimitry Andric     case Intrinsic::ssub_with_overflow:
1043*647cbc5dSDimitry Andric       WorkList.push_back(
1044*647cbc5dSDimitry Andric           FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I)));
1045*647cbc5dSDimitry Andric       break;
1046*647cbc5dSDimitry Andric     // Enqueue the intrinsics to add extra info.
1047*647cbc5dSDimitry Andric     case Intrinsic::abs:
1048*647cbc5dSDimitry Andric     case Intrinsic::umin:
1049*647cbc5dSDimitry Andric     case Intrinsic::umax:
1050*647cbc5dSDimitry Andric     case Intrinsic::smin:
1051*647cbc5dSDimitry Andric     case Intrinsic::smax:
1052*647cbc5dSDimitry Andric       WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
1053*647cbc5dSDimitry Andric       break;
1054*647cbc5dSDimitry Andric     }
1055*647cbc5dSDimitry Andric 
1056349cc55cSDimitry Andric     GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
1057349cc55cSDimitry Andric   }
1058349cc55cSDimitry Andric 
10595f757f3fSDimitry Andric   if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) {
10605f757f3fSDimitry Andric     for (auto &Case : Switch->cases()) {
10615f757f3fSDimitry Andric       BasicBlock *Succ = Case.getCaseSuccessor();
10625f757f3fSDimitry Andric       Value *V = Case.getCaseValue();
10635f757f3fSDimitry Andric       if (!canAddSuccessor(BB, Succ))
10645f757f3fSDimitry Andric         continue;
10655f757f3fSDimitry Andric       WorkList.emplace_back(FactOrCheck::getConditionFact(
10665f757f3fSDimitry Andric           DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V));
10675f757f3fSDimitry Andric     }
10685f757f3fSDimitry Andric     return;
10695f757f3fSDimitry Andric   }
10705f757f3fSDimitry Andric 
1071e8d8bef9SDimitry Andric   auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
1072e8d8bef9SDimitry Andric   if (!Br || !Br->isConditional())
107381ad6265SDimitry Andric     return;
1074e8d8bef9SDimitry Andric 
1075bdd1243dSDimitry Andric   Value *Cond = Br->getCondition();
1076e8d8bef9SDimitry Andric 
1077bdd1243dSDimitry Andric   // If the condition is a chain of ORs/AND and the successor only has the
1078bdd1243dSDimitry Andric   // current block as predecessor, queue conditions for the successor.
1079bdd1243dSDimitry Andric   Value *Op0, *Op1;
1080bdd1243dSDimitry Andric   if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
1081bdd1243dSDimitry Andric       match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1082bdd1243dSDimitry Andric     bool IsOr = match(Cond, m_LogicalOr());
1083bdd1243dSDimitry Andric     bool IsAnd = match(Cond, m_LogicalAnd());
1084bdd1243dSDimitry Andric     // If there's a select that matches both AND and OR, we need to commit to
1085bdd1243dSDimitry Andric     // one of the options. Arbitrarily pick OR.
1086bdd1243dSDimitry Andric     if (IsOr && IsAnd)
1087bdd1243dSDimitry Andric       IsAnd = false;
1088bdd1243dSDimitry Andric 
1089bdd1243dSDimitry Andric     BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0);
1090bdd1243dSDimitry Andric     if (canAddSuccessor(BB, Successor)) {
1091bdd1243dSDimitry Andric       SmallVector<Value *> CondWorkList;
1092bdd1243dSDimitry Andric       SmallPtrSet<Value *, 8> SeenCond;
1093bdd1243dSDimitry Andric       auto QueueValue = [&CondWorkList, &SeenCond](Value *V) {
1094bdd1243dSDimitry Andric         if (SeenCond.insert(V).second)
1095bdd1243dSDimitry Andric           CondWorkList.push_back(V);
1096bdd1243dSDimitry Andric       };
1097bdd1243dSDimitry Andric       QueueValue(Op1);
1098bdd1243dSDimitry Andric       QueueValue(Op0);
1099bdd1243dSDimitry Andric       while (!CondWorkList.empty()) {
1100bdd1243dSDimitry Andric         Value *Cur = CondWorkList.pop_back_val();
1101bdd1243dSDimitry Andric         if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) {
11025f757f3fSDimitry Andric           WorkList.emplace_back(FactOrCheck::getConditionFact(
11035f757f3fSDimitry Andric               DT.getNode(Successor),
11045f757f3fSDimitry Andric               IsOr ? CmpInst::getInversePredicate(Cmp->getPredicate())
11055f757f3fSDimitry Andric                    : Cmp->getPredicate(),
11065f757f3fSDimitry Andric               Cmp->getOperand(0), Cmp->getOperand(1)));
1107bdd1243dSDimitry Andric           continue;
1108bdd1243dSDimitry Andric         }
1109bdd1243dSDimitry Andric         if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
1110bdd1243dSDimitry Andric           QueueValue(Op1);
1111bdd1243dSDimitry Andric           QueueValue(Op0);
1112bdd1243dSDimitry Andric           continue;
1113bdd1243dSDimitry Andric         }
1114bdd1243dSDimitry Andric         if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
1115bdd1243dSDimitry Andric           QueueValue(Op1);
1116bdd1243dSDimitry Andric           QueueValue(Op0);
1117bdd1243dSDimitry Andric           continue;
1118bdd1243dSDimitry Andric         }
1119bdd1243dSDimitry Andric       }
1120e8d8bef9SDimitry Andric     }
112181ad6265SDimitry Andric     return;
1122e8d8bef9SDimitry Andric   }
1123e8d8bef9SDimitry Andric 
112481ad6265SDimitry Andric   auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition());
1125e8d8bef9SDimitry Andric   if (!CmpI)
112681ad6265SDimitry Andric     return;
112781ad6265SDimitry Andric   if (canAddSuccessor(BB, Br->getSuccessor(0)))
11285f757f3fSDimitry Andric     WorkList.emplace_back(FactOrCheck::getConditionFact(
11295f757f3fSDimitry Andric         DT.getNode(Br->getSuccessor(0)), CmpI->getPredicate(),
11305f757f3fSDimitry Andric         CmpI->getOperand(0), CmpI->getOperand(1)));
113181ad6265SDimitry Andric   if (canAddSuccessor(BB, Br->getSuccessor(1)))
11325f757f3fSDimitry Andric     WorkList.emplace_back(FactOrCheck::getConditionFact(
11335f757f3fSDimitry Andric         DT.getNode(Br->getSuccessor(1)),
11345f757f3fSDimitry Andric         CmpInst::getInversePredicate(CmpI->getPredicate()), CmpI->getOperand(0),
11355f757f3fSDimitry Andric         CmpI->getOperand(1)));
1136bdd1243dSDimitry Andric }
1137bdd1243dSDimitry Andric 
11385f757f3fSDimitry Andric #ifndef NDEBUG
11395f757f3fSDimitry Andric static void dumpUnpackedICmp(raw_ostream &OS, ICmpInst::Predicate Pred,
11405f757f3fSDimitry Andric                              Value *LHS, Value *RHS) {
11415f757f3fSDimitry Andric   OS << "icmp " << Pred << ' ';
11425f757f3fSDimitry Andric   LHS->printAsOperand(OS, /*PrintType=*/true);
11435f757f3fSDimitry Andric   OS << ", ";
11445f757f3fSDimitry Andric   RHS->printAsOperand(OS, /*PrintType=*/false);
11455f757f3fSDimitry Andric }
11465f757f3fSDimitry Andric #endif
11475f757f3fSDimitry Andric 
114806c3fb27SDimitry Andric namespace {
114906c3fb27SDimitry Andric /// Helper to keep track of a condition and if it should be treated as negated
115006c3fb27SDimitry Andric /// for reproducer construction.
115106c3fb27SDimitry Andric /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a
115206c3fb27SDimitry Andric /// placeholder to keep the ReproducerCondStack in sync with DFSInStack.
115306c3fb27SDimitry Andric struct ReproducerEntry {
115406c3fb27SDimitry Andric   ICmpInst::Predicate Pred;
115506c3fb27SDimitry Andric   Value *LHS;
115606c3fb27SDimitry Andric   Value *RHS;
115706c3fb27SDimitry Andric 
115806c3fb27SDimitry Andric   ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS)
115906c3fb27SDimitry Andric       : Pred(Pred), LHS(LHS), RHS(RHS) {}
116006c3fb27SDimitry Andric };
116106c3fb27SDimitry Andric } // namespace
116206c3fb27SDimitry Andric 
116306c3fb27SDimitry Andric /// Helper function to generate a reproducer function for simplifying \p Cond.
116406c3fb27SDimitry Andric /// The reproducer function contains a series of @llvm.assume calls, one for
116506c3fb27SDimitry Andric /// each condition in \p Stack. For each condition, the operand instruction are
116606c3fb27SDimitry Andric /// cloned until we reach operands that have an entry in \p Value2Index. Those
116706c3fb27SDimitry Andric /// will then be added as function arguments. \p DT is used to order cloned
116806c3fb27SDimitry Andric /// instructions. The reproducer function will get added to \p M, if it is
116906c3fb27SDimitry Andric /// non-null. Otherwise no reproducer function is generated.
117006c3fb27SDimitry Andric static void generateReproducer(CmpInst *Cond, Module *M,
117106c3fb27SDimitry Andric                                ArrayRef<ReproducerEntry> Stack,
117206c3fb27SDimitry Andric                                ConstraintInfo &Info, DominatorTree &DT) {
117306c3fb27SDimitry Andric   if (!M)
117406c3fb27SDimitry Andric     return;
117506c3fb27SDimitry Andric 
117606c3fb27SDimitry Andric   LLVMContext &Ctx = Cond->getContext();
117706c3fb27SDimitry Andric 
117806c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n");
117906c3fb27SDimitry Andric 
118006c3fb27SDimitry Andric   ValueToValueMapTy Old2New;
118106c3fb27SDimitry Andric   SmallVector<Value *> Args;
118206c3fb27SDimitry Andric   SmallPtrSet<Value *, 8> Seen;
118306c3fb27SDimitry Andric   // Traverse Cond and its operands recursively until we reach a value that's in
118406c3fb27SDimitry Andric   // Value2Index or not an instruction, or not a operation that
118506c3fb27SDimitry Andric   // ConstraintElimination can decompose. Such values will be considered as
118606c3fb27SDimitry Andric   // external inputs to the reproducer, they are collected and added as function
118706c3fb27SDimitry Andric   // arguments later.
118806c3fb27SDimitry Andric   auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) {
118906c3fb27SDimitry Andric     auto &Value2Index = Info.getValue2Index(IsSigned);
119006c3fb27SDimitry Andric     SmallVector<Value *, 4> WorkList(Ops);
119106c3fb27SDimitry Andric     while (!WorkList.empty()) {
119206c3fb27SDimitry Andric       Value *V = WorkList.pop_back_val();
119306c3fb27SDimitry Andric       if (!Seen.insert(V).second)
119406c3fb27SDimitry Andric         continue;
119506c3fb27SDimitry Andric       if (Old2New.find(V) != Old2New.end())
119606c3fb27SDimitry Andric         continue;
119706c3fb27SDimitry Andric       if (isa<Constant>(V))
119806c3fb27SDimitry Andric         continue;
119906c3fb27SDimitry Andric 
120006c3fb27SDimitry Andric       auto *I = dyn_cast<Instruction>(V);
120106c3fb27SDimitry Andric       if (Value2Index.contains(V) || !I ||
120206c3fb27SDimitry Andric           !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) {
120306c3fb27SDimitry Andric         Old2New[V] = V;
120406c3fb27SDimitry Andric         Args.push_back(V);
120506c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "  found external input " << *V << "\n");
120606c3fb27SDimitry Andric       } else {
120706c3fb27SDimitry Andric         append_range(WorkList, I->operands());
120806c3fb27SDimitry Andric       }
120906c3fb27SDimitry Andric     }
121006c3fb27SDimitry Andric   };
121106c3fb27SDimitry Andric 
121206c3fb27SDimitry Andric   for (auto &Entry : Stack)
121306c3fb27SDimitry Andric     if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE)
121406c3fb27SDimitry Andric       CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred));
121506c3fb27SDimitry Andric   CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate()));
121606c3fb27SDimitry Andric 
121706c3fb27SDimitry Andric   SmallVector<Type *> ParamTys;
121806c3fb27SDimitry Andric   for (auto *P : Args)
121906c3fb27SDimitry Andric     ParamTys.push_back(P->getType());
122006c3fb27SDimitry Andric 
122106c3fb27SDimitry Andric   FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys,
122206c3fb27SDimitry Andric                                         /*isVarArg=*/false);
122306c3fb27SDimitry Andric   Function *F = Function::Create(FTy, Function::ExternalLinkage,
122406c3fb27SDimitry Andric                                  Cond->getModule()->getName() +
122506c3fb27SDimitry Andric                                      Cond->getFunction()->getName() + "repro",
122606c3fb27SDimitry Andric                                  M);
122706c3fb27SDimitry Andric   // Add arguments to the reproducer function for each external value collected.
122806c3fb27SDimitry Andric   for (unsigned I = 0; I < Args.size(); ++I) {
122906c3fb27SDimitry Andric     F->getArg(I)->setName(Args[I]->getName());
123006c3fb27SDimitry Andric     Old2New[Args[I]] = F->getArg(I);
123106c3fb27SDimitry Andric   }
123206c3fb27SDimitry Andric 
123306c3fb27SDimitry Andric   BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
123406c3fb27SDimitry Andric   IRBuilder<> Builder(Entry);
123506c3fb27SDimitry Andric   Builder.CreateRet(Builder.getTrue());
123606c3fb27SDimitry Andric   Builder.SetInsertPoint(Entry->getTerminator());
123706c3fb27SDimitry Andric 
123806c3fb27SDimitry Andric   // Clone instructions in \p Ops and their operands recursively until reaching
123906c3fb27SDimitry Andric   // an value in Value2Index (external input to the reproducer). Update Old2New
124006c3fb27SDimitry Andric   // mapping for the original and cloned instructions. Sort instructions to
124106c3fb27SDimitry Andric   // clone by dominance, then insert the cloned instructions in the function.
124206c3fb27SDimitry Andric   auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) {
124306c3fb27SDimitry Andric     SmallVector<Value *, 4> WorkList(Ops);
124406c3fb27SDimitry Andric     SmallVector<Instruction *> ToClone;
124506c3fb27SDimitry Andric     auto &Value2Index = Info.getValue2Index(IsSigned);
124606c3fb27SDimitry Andric     while (!WorkList.empty()) {
124706c3fb27SDimitry Andric       Value *V = WorkList.pop_back_val();
124806c3fb27SDimitry Andric       if (Old2New.find(V) != Old2New.end())
124906c3fb27SDimitry Andric         continue;
125006c3fb27SDimitry Andric 
125106c3fb27SDimitry Andric       auto *I = dyn_cast<Instruction>(V);
125206c3fb27SDimitry Andric       if (!Value2Index.contains(V) && I) {
125306c3fb27SDimitry Andric         Old2New[V] = nullptr;
125406c3fb27SDimitry Andric         ToClone.push_back(I);
125506c3fb27SDimitry Andric         append_range(WorkList, I->operands());
125606c3fb27SDimitry Andric       }
125706c3fb27SDimitry Andric     }
125806c3fb27SDimitry Andric 
125906c3fb27SDimitry Andric     sort(ToClone,
126006c3fb27SDimitry Andric          [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); });
126106c3fb27SDimitry Andric     for (Instruction *I : ToClone) {
126206c3fb27SDimitry Andric       Instruction *Cloned = I->clone();
126306c3fb27SDimitry Andric       Old2New[I] = Cloned;
126406c3fb27SDimitry Andric       Old2New[I]->setName(I->getName());
126506c3fb27SDimitry Andric       Cloned->insertBefore(&*Builder.GetInsertPoint());
126606c3fb27SDimitry Andric       Cloned->dropUnknownNonDebugMetadata();
126706c3fb27SDimitry Andric       Cloned->setDebugLoc({});
126806c3fb27SDimitry Andric     }
126906c3fb27SDimitry Andric   };
127006c3fb27SDimitry Andric 
127106c3fb27SDimitry Andric   // Materialize the assumptions for the reproducer using the entries in Stack.
127206c3fb27SDimitry Andric   // That is, first clone the operands of the condition recursively until we
127306c3fb27SDimitry Andric   // reach an external input to the reproducer and add them to the reproducer
127406c3fb27SDimitry Andric   // function. Then add an ICmp for the condition (with the inverse predicate if
127506c3fb27SDimitry Andric   // the entry is negated) and an assert using the ICmp.
127606c3fb27SDimitry Andric   for (auto &Entry : Stack) {
127706c3fb27SDimitry Andric     if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE)
127806c3fb27SDimitry Andric       continue;
127906c3fb27SDimitry Andric 
12805f757f3fSDimitry Andric     LLVM_DEBUG(dbgs() << "  Materializing assumption ";
12815f757f3fSDimitry Andric                dumpUnpackedICmp(dbgs(), Entry.Pred, Entry.LHS, Entry.RHS);
12825f757f3fSDimitry Andric                dbgs() << "\n");
128306c3fb27SDimitry Andric     CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred));
128406c3fb27SDimitry Andric 
128506c3fb27SDimitry Andric     auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS);
128606c3fb27SDimitry Andric     Builder.CreateAssumption(Cmp);
128706c3fb27SDimitry Andric   }
128806c3fb27SDimitry Andric 
128906c3fb27SDimitry Andric   // Finally, clone the condition to reproduce and remap instruction operands in
129006c3fb27SDimitry Andric   // the reproducer using Old2New.
129106c3fb27SDimitry Andric   CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate()));
129206c3fb27SDimitry Andric   Entry->getTerminator()->setOperand(0, Cond);
129306c3fb27SDimitry Andric   remapInstructionsInBlocks({Entry}, Old2New);
129406c3fb27SDimitry Andric 
129506c3fb27SDimitry Andric   assert(!verifyFunction(*F, &dbgs()));
129606c3fb27SDimitry Andric }
129706c3fb27SDimitry Andric 
12985f757f3fSDimitry Andric static std::optional<bool> checkCondition(CmpInst::Predicate Pred, Value *A,
12995f757f3fSDimitry Andric                                           Value *B, Instruction *CheckInst,
13005f757f3fSDimitry Andric                                           ConstraintInfo &Info, unsigned NumIn,
13015f757f3fSDimitry Andric                                           unsigned NumOut,
130206c3fb27SDimitry Andric                                           Instruction *ContextInst) {
13035f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "Checking " << *CheckInst << "\n");
1304bdd1243dSDimitry Andric 
1305bdd1243dSDimitry Andric   auto R = Info.getConstraintForSolving(Pred, A, B);
1306bdd1243dSDimitry Andric   if (R.empty() || !R.isValid(Info)){
1307bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "   failed to decompose condition\n");
130806c3fb27SDimitry Andric     return std::nullopt;
1309bdd1243dSDimitry Andric   }
1310bdd1243dSDimitry Andric 
1311bdd1243dSDimitry Andric   auto &CSToUse = Info.getCS(R.IsSigned);
1312bdd1243dSDimitry Andric 
1313bdd1243dSDimitry Andric   // If there was extra information collected during decomposition, apply
1314bdd1243dSDimitry Andric   // it now and remove it immediately once we are done with reasoning
1315bdd1243dSDimitry Andric   // about the constraint.
1316bdd1243dSDimitry Andric   for (auto &Row : R.ExtraInfo)
1317bdd1243dSDimitry Andric     CSToUse.addVariableRow(Row);
1318bdd1243dSDimitry Andric   auto InfoRestorer = make_scope_exit([&]() {
1319bdd1243dSDimitry Andric     for (unsigned I = 0; I < R.ExtraInfo.size(); ++I)
1320bdd1243dSDimitry Andric       CSToUse.popLastConstraint();
1321bdd1243dSDimitry Andric   });
1322bdd1243dSDimitry Andric 
132306c3fb27SDimitry Andric   if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) {
1324bdd1243dSDimitry Andric     if (!DebugCounter::shouldExecute(EliminatedCounter))
132506c3fb27SDimitry Andric       return std::nullopt;
1326bdd1243dSDimitry Andric 
1327bdd1243dSDimitry Andric     LLVM_DEBUG({
13285f757f3fSDimitry Andric       dbgs() << "Condition ";
13295f757f3fSDimitry Andric       dumpUnpackedICmp(
13305f757f3fSDimitry Andric           dbgs(), *ImpliedCondition ? Pred : CmpInst::getInversePredicate(Pred),
13315f757f3fSDimitry Andric           A, B);
133206c3fb27SDimitry Andric       dbgs() << " implied by dominating constraints\n";
133306c3fb27SDimitry Andric       CSToUse.dump();
1334bdd1243dSDimitry Andric     });
133506c3fb27SDimitry Andric     return ImpliedCondition;
133606c3fb27SDimitry Andric   }
133706c3fb27SDimitry Andric 
133806c3fb27SDimitry Andric   return std::nullopt;
133906c3fb27SDimitry Andric }
134006c3fb27SDimitry Andric 
134106c3fb27SDimitry Andric static bool checkAndReplaceCondition(
134206c3fb27SDimitry Andric     CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut,
134306c3fb27SDimitry Andric     Instruction *ContextInst, Module *ReproducerModule,
13445f757f3fSDimitry Andric     ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT,
13455f757f3fSDimitry Andric     SmallVectorImpl<Instruction *> &ToRemove) {
134606c3fb27SDimitry Andric   auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) {
134706c3fb27SDimitry Andric     generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT);
134806c3fb27SDimitry Andric     Constant *ConstantC = ConstantInt::getBool(
134906c3fb27SDimitry Andric         CmpInst::makeCmpResultType(Cmp->getType()), IsTrue);
135006c3fb27SDimitry Andric     Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut,
135106c3fb27SDimitry Andric                                        ContextInst](Use &U) {
135206c3fb27SDimitry Andric       auto *UserI = getContextInstForUse(U);
135306c3fb27SDimitry Andric       auto *DTN = DT.getNode(UserI->getParent());
135406c3fb27SDimitry Andric       if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut)
135506c3fb27SDimitry Andric         return false;
135606c3fb27SDimitry Andric       if (UserI->getParent() == ContextInst->getParent() &&
135706c3fb27SDimitry Andric           UserI->comesBefore(ContextInst))
135806c3fb27SDimitry Andric         return false;
135906c3fb27SDimitry Andric 
1360bdd1243dSDimitry Andric       // Conditions in an assume trivially simplify to true. Skip uses
1361bdd1243dSDimitry Andric       // in assume calls to not destroy the available information.
1362bdd1243dSDimitry Andric       auto *II = dyn_cast<IntrinsicInst>(U.getUser());
1363bdd1243dSDimitry Andric       return !II || II->getIntrinsicID() != Intrinsic::assume;
1364bdd1243dSDimitry Andric     });
1365bdd1243dSDimitry Andric     NumCondsRemoved++;
13665f757f3fSDimitry Andric     if (Cmp->use_empty())
13675f757f3fSDimitry Andric       ToRemove.push_back(Cmp);
136806c3fb27SDimitry Andric     return true;
136906c3fb27SDimitry Andric   };
137006c3fb27SDimitry Andric 
13715f757f3fSDimitry Andric   if (auto ImpliedCondition = checkCondition(
13725f757f3fSDimitry Andric           Cmp->getPredicate(), Cmp->getOperand(0), Cmp->getOperand(1), Cmp,
13735f757f3fSDimitry Andric           Info, NumIn, NumOut, ContextInst))
137406c3fb27SDimitry Andric     return ReplaceCmpWithConstant(Cmp, *ImpliedCondition);
137506c3fb27SDimitry Andric   return false;
1376bdd1243dSDimitry Andric }
137706c3fb27SDimitry Andric 
137806c3fb27SDimitry Andric static void
137906c3fb27SDimitry Andric removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info,
138006c3fb27SDimitry Andric                      Module *ReproducerModule,
138106c3fb27SDimitry Andric                      SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
138206c3fb27SDimitry Andric                      SmallVectorImpl<StackEntry> &DFSInStack) {
138306c3fb27SDimitry Andric   Info.popLastConstraint(E.IsSigned);
138406c3fb27SDimitry Andric   // Remove variables in the system that went out of scope.
138506c3fb27SDimitry Andric   auto &Mapping = Info.getValue2Index(E.IsSigned);
138606c3fb27SDimitry Andric   for (Value *V : E.ValuesToRelease)
138706c3fb27SDimitry Andric     Mapping.erase(V);
138806c3fb27SDimitry Andric   Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size());
138906c3fb27SDimitry Andric   DFSInStack.pop_back();
139006c3fb27SDimitry Andric   if (ReproducerModule)
139106c3fb27SDimitry Andric     ReproducerCondStack.pop_back();
139206c3fb27SDimitry Andric }
139306c3fb27SDimitry Andric 
1394cb14a3feSDimitry Andric /// Check if either the first condition of an AND or OR is implied by the
1395cb14a3feSDimitry Andric /// (negated in case of OR) second condition or vice versa.
1396cb14a3feSDimitry Andric static bool checkOrAndOpImpliedByOther(
139706c3fb27SDimitry Andric     FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule,
139806c3fb27SDimitry Andric     SmallVectorImpl<ReproducerEntry> &ReproducerCondStack,
139906c3fb27SDimitry Andric     SmallVectorImpl<StackEntry> &DFSInStack) {
14005f757f3fSDimitry Andric 
140106c3fb27SDimitry Andric   CmpInst::Predicate Pred;
140206c3fb27SDimitry Andric   Value *A, *B;
1403cb14a3feSDimitry Andric   Instruction *JoinOp = CB.getContextInst();
1404cb14a3feSDimitry Andric   CmpInst *CmpToCheck = cast<CmpInst>(CB.getInstructionToSimplify());
1405cb14a3feSDimitry Andric   unsigned OtherOpIdx = JoinOp->getOperand(0) == CmpToCheck ? 1 : 0;
1406cb14a3feSDimitry Andric 
1407cb14a3feSDimitry Andric   // Don't try to simplify the first condition of a select by the second, as
1408cb14a3feSDimitry Andric   // this may make the select more poisonous than the original one.
1409cb14a3feSDimitry Andric   // TODO: check if the first operand may be poison.
1410cb14a3feSDimitry Andric   if (OtherOpIdx != 0 && isa<SelectInst>(JoinOp))
1411bdd1243dSDimitry Andric     return false;
1412bdd1243dSDimitry Andric 
1413cb14a3feSDimitry Andric   if (!match(JoinOp->getOperand(OtherOpIdx),
1414cb14a3feSDimitry Andric              m_ICmp(Pred, m_Value(A), m_Value(B))))
1415cb14a3feSDimitry Andric     return false;
1416cb14a3feSDimitry Andric 
1417cb14a3feSDimitry Andric   // For OR, check if the negated condition implies CmpToCheck.
1418cb14a3feSDimitry Andric   bool IsOr = match(JoinOp, m_LogicalOr());
1419cb14a3feSDimitry Andric   if (IsOr)
1420cb14a3feSDimitry Andric     Pred = CmpInst::getInversePredicate(Pred);
1421cb14a3feSDimitry Andric 
142206c3fb27SDimitry Andric   // Optimistically add fact from first condition.
142306c3fb27SDimitry Andric   unsigned OldSize = DFSInStack.size();
142406c3fb27SDimitry Andric   Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
142506c3fb27SDimitry Andric   if (OldSize == DFSInStack.size())
142606c3fb27SDimitry Andric     return false;
142706c3fb27SDimitry Andric 
142806c3fb27SDimitry Andric   bool Changed = false;
142906c3fb27SDimitry Andric   // Check if the second condition can be simplified now.
1430cb14a3feSDimitry Andric   if (auto ImpliedCondition =
1431cb14a3feSDimitry Andric           checkCondition(CmpToCheck->getPredicate(), CmpToCheck->getOperand(0),
1432cb14a3feSDimitry Andric                          CmpToCheck->getOperand(1), CmpToCheck, Info, CB.NumIn,
1433cb14a3feSDimitry Andric                          CB.NumOut, CB.getContextInst())) {
1434cb14a3feSDimitry Andric     if (IsOr && isa<SelectInst>(JoinOp)) {
1435cb14a3feSDimitry Andric       JoinOp->setOperand(
1436cb14a3feSDimitry Andric           OtherOpIdx == 0 ? 2 : 0,
1437cb14a3feSDimitry Andric           ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1438cb14a3feSDimitry Andric     } else
1439cb14a3feSDimitry Andric       JoinOp->setOperand(
1440cb14a3feSDimitry Andric           1 - OtherOpIdx,
1441cb14a3feSDimitry Andric           ConstantInt::getBool(JoinOp->getType(), *ImpliedCondition));
1442cb14a3feSDimitry Andric 
1443bdd1243dSDimitry Andric     Changed = true;
1444bdd1243dSDimitry Andric   }
144506c3fb27SDimitry Andric 
144606c3fb27SDimitry Andric   // Remove entries again.
144706c3fb27SDimitry Andric   while (OldSize < DFSInStack.size()) {
144806c3fb27SDimitry Andric     StackEntry E = DFSInStack.back();
144906c3fb27SDimitry Andric     removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack,
145006c3fb27SDimitry Andric                          DFSInStack);
145106c3fb27SDimitry Andric   }
1452bdd1243dSDimitry Andric   return Changed;
1453e8d8bef9SDimitry Andric }
1454e8d8bef9SDimitry Andric 
145581ad6265SDimitry Andric void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B,
1456bdd1243dSDimitry Andric                              unsigned NumIn, unsigned NumOut,
145781ad6265SDimitry Andric                              SmallVectorImpl<StackEntry> &DFSInStack) {
145881ad6265SDimitry Andric   // If the constraint has a pre-condition, skip the constraint if it does not
145981ad6265SDimitry Andric   // hold.
1460bdd1243dSDimitry Andric   SmallVector<Value *> NewVariables;
1461bdd1243dSDimitry Andric   auto R = getConstraint(Pred, A, B, NewVariables);
146206c3fb27SDimitry Andric 
146306c3fb27SDimitry Andric   // TODO: Support non-equality for facts as well.
146406c3fb27SDimitry Andric   if (!R.isValid(*this) || R.isNe())
146581ad6265SDimitry Andric     return;
146681ad6265SDimitry Andric 
14675f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "Adding '"; dumpUnpackedICmp(dbgs(), Pred, A, B);
14685f757f3fSDimitry Andric              dbgs() << "'\n");
146981ad6265SDimitry Andric   bool Added = false;
147081ad6265SDimitry Andric   auto &CSToUse = getCS(R.IsSigned);
147181ad6265SDimitry Andric   if (R.Coefficients.empty())
147281ad6265SDimitry Andric     return;
147381ad6265SDimitry Andric 
147481ad6265SDimitry Andric   Added |= CSToUse.addVariableRowFill(R.Coefficients);
147581ad6265SDimitry Andric 
1476bdd1243dSDimitry Andric   // If R has been added to the system, add the new variables and queue it for
1477bdd1243dSDimitry Andric   // removal once it goes out-of-scope.
147881ad6265SDimitry Andric   if (Added) {
147981ad6265SDimitry Andric     SmallVector<Value *, 2> ValuesToRelease;
1480bdd1243dSDimitry Andric     auto &Value2Index = getValue2Index(R.IsSigned);
1481bdd1243dSDimitry Andric     for (Value *V : NewVariables) {
1482bdd1243dSDimitry Andric       Value2Index.insert({V, Value2Index.size() + 1});
1483bdd1243dSDimitry Andric       ValuesToRelease.push_back(V);
148481ad6265SDimitry Andric     }
148581ad6265SDimitry Andric 
148681ad6265SDimitry Andric     LLVM_DEBUG({
148781ad6265SDimitry Andric       dbgs() << "  constraint: ";
148806c3fb27SDimitry Andric       dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned));
1489bdd1243dSDimitry Andric       dbgs() << "\n";
149081ad6265SDimitry Andric     });
149181ad6265SDimitry Andric 
1492bdd1243dSDimitry Andric     DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1493bdd1243dSDimitry Andric                             std::move(ValuesToRelease));
149481ad6265SDimitry Andric 
1495cb14a3feSDimitry Andric     if (!R.IsSigned) {
1496cb14a3feSDimitry Andric       for (Value *V : NewVariables) {
1497cb14a3feSDimitry Andric         ConstraintTy VarPos(SmallVector<int64_t, 8>(Value2Index.size() + 1, 0),
1498cb14a3feSDimitry Andric                             false, false, false);
1499cb14a3feSDimitry Andric         VarPos.Coefficients[Value2Index[V]] = -1;
1500cb14a3feSDimitry Andric         CSToUse.addVariableRow(VarPos.Coefficients);
1501cb14a3feSDimitry Andric         DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
1502cb14a3feSDimitry Andric                                 SmallVector<Value *, 2>());
1503cb14a3feSDimitry Andric       }
1504cb14a3feSDimitry Andric     }
1505cb14a3feSDimitry Andric 
150606c3fb27SDimitry Andric     if (R.isEq()) {
150781ad6265SDimitry Andric       // Also add the inverted constraint for equality constraints.
150881ad6265SDimitry Andric       for (auto &Coeff : R.Coefficients)
150981ad6265SDimitry Andric         Coeff *= -1;
151081ad6265SDimitry Andric       CSToUse.addVariableRowFill(R.Coefficients);
151181ad6265SDimitry Andric 
1512bdd1243dSDimitry Andric       DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned,
151381ad6265SDimitry Andric                               SmallVector<Value *, 2>());
151481ad6265SDimitry Andric     }
151581ad6265SDimitry Andric   }
151681ad6265SDimitry Andric }
151781ad6265SDimitry Andric 
1518bdd1243dSDimitry Andric static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B,
1519bdd1243dSDimitry Andric                                    SmallVectorImpl<Instruction *> &ToRemove) {
1520bdd1243dSDimitry Andric   bool Changed = false;
1521bdd1243dSDimitry Andric   IRBuilder<> Builder(II->getParent(), II->getIterator());
1522bdd1243dSDimitry Andric   Value *Sub = nullptr;
1523bdd1243dSDimitry Andric   for (User *U : make_early_inc_range(II->users())) {
1524bdd1243dSDimitry Andric     if (match(U, m_ExtractValue<0>(m_Value()))) {
1525bdd1243dSDimitry Andric       if (!Sub)
1526bdd1243dSDimitry Andric         Sub = Builder.CreateSub(A, B);
1527bdd1243dSDimitry Andric       U->replaceAllUsesWith(Sub);
1528bdd1243dSDimitry Andric       Changed = true;
1529bdd1243dSDimitry Andric     } else if (match(U, m_ExtractValue<1>(m_Value()))) {
1530bdd1243dSDimitry Andric       U->replaceAllUsesWith(Builder.getFalse());
1531bdd1243dSDimitry Andric       Changed = true;
1532bdd1243dSDimitry Andric     } else
1533bdd1243dSDimitry Andric       continue;
1534bdd1243dSDimitry Andric 
1535bdd1243dSDimitry Andric     if (U->use_empty()) {
1536bdd1243dSDimitry Andric       auto *I = cast<Instruction>(U);
1537bdd1243dSDimitry Andric       ToRemove.push_back(I);
1538bdd1243dSDimitry Andric       I->setOperand(0, PoisonValue::get(II->getType()));
1539bdd1243dSDimitry Andric       Changed = true;
1540bdd1243dSDimitry Andric     }
1541bdd1243dSDimitry Andric   }
1542bdd1243dSDimitry Andric 
1543bdd1243dSDimitry Andric   if (II->use_empty()) {
1544bdd1243dSDimitry Andric     II->eraseFromParent();
1545bdd1243dSDimitry Andric     Changed = true;
1546bdd1243dSDimitry Andric   }
1547bdd1243dSDimitry Andric   return Changed;
1548bdd1243dSDimitry Andric }
1549bdd1243dSDimitry Andric 
1550bdd1243dSDimitry Andric static bool
155181ad6265SDimitry Andric tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info,
155281ad6265SDimitry Andric                           SmallVectorImpl<Instruction *> &ToRemove) {
155381ad6265SDimitry Andric   auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B,
155481ad6265SDimitry Andric                               ConstraintInfo &Info) {
1555bdd1243dSDimitry Andric     auto R = Info.getConstraintForSolving(Pred, A, B);
1556bdd1243dSDimitry Andric     if (R.size() < 2 || !R.isValid(Info))
155781ad6265SDimitry Andric       return false;
155881ad6265SDimitry Andric 
1559bdd1243dSDimitry Andric     auto &CSToUse = Info.getCS(R.IsSigned);
156081ad6265SDimitry Andric     return CSToUse.isConditionImplied(R.Coefficients);
156181ad6265SDimitry Andric   };
156281ad6265SDimitry Andric 
1563bdd1243dSDimitry Andric   bool Changed = false;
156481ad6265SDimitry Andric   if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) {
156581ad6265SDimitry Andric     // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and
156681ad6265SDimitry Andric     // can be simplified to a regular sub.
156781ad6265SDimitry Andric     Value *A = II->getArgOperand(0);
156881ad6265SDimitry Andric     Value *B = II->getArgOperand(1);
156981ad6265SDimitry Andric     if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) ||
157081ad6265SDimitry Andric         !DoesConditionHold(CmpInst::ICMP_SGE, B,
157181ad6265SDimitry Andric                            ConstantInt::get(A->getType(), 0), Info))
1572bdd1243dSDimitry Andric       return false;
1573bdd1243dSDimitry Andric     Changed = replaceSubOverflowUses(II, A, B, ToRemove);
157481ad6265SDimitry Andric   }
1575bdd1243dSDimitry Andric   return Changed;
157681ad6265SDimitry Andric }
157781ad6265SDimitry Andric 
15785f757f3fSDimitry Andric static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI,
15795f757f3fSDimitry Andric                                  ScalarEvolution &SE,
158006c3fb27SDimitry Andric                                  OptimizationRemarkEmitter &ORE) {
158181ad6265SDimitry Andric   bool Changed = false;
158281ad6265SDimitry Andric   DT.updateDFSNumbers();
158306c3fb27SDimitry Andric   SmallVector<Value *> FunctionArgs;
158406c3fb27SDimitry Andric   for (Value &Arg : F.args())
158506c3fb27SDimitry Andric     FunctionArgs.push_back(&Arg);
158606c3fb27SDimitry Andric   ConstraintInfo Info(F.getParent()->getDataLayout(), FunctionArgs);
15875f757f3fSDimitry Andric   State S(DT, LI, SE);
158806c3fb27SDimitry Andric   std::unique_ptr<Module> ReproducerModule(
158906c3fb27SDimitry Andric       DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr);
159081ad6265SDimitry Andric 
159181ad6265SDimitry Andric   // First, collect conditions implied by branches and blocks with their
159281ad6265SDimitry Andric   // Dominator DFS in and out numbers.
159381ad6265SDimitry Andric   for (BasicBlock &BB : F) {
159481ad6265SDimitry Andric     if (!DT.getNode(&BB))
159581ad6265SDimitry Andric       continue;
159681ad6265SDimitry Andric     S.addInfoFor(BB);
159781ad6265SDimitry Andric   }
159881ad6265SDimitry Andric 
1599bdd1243dSDimitry Andric   // Next, sort worklist by dominance, so that dominating conditions to check
1600bdd1243dSDimitry Andric   // and facts come before conditions and facts dominated by them. If a
1601bdd1243dSDimitry Andric   // condition to check and a fact have the same numbers, conditional facts come
1602bdd1243dSDimitry Andric   // first. Assume facts and checks are ordered according to their relative
1603bdd1243dSDimitry Andric   // order in the containing basic block. Also make sure conditions with
1604bdd1243dSDimitry Andric   // constant operands come before conditions without constant operands. This
1605bdd1243dSDimitry Andric   // increases the effectiveness of the current signed <-> unsigned fact
1606bdd1243dSDimitry Andric   // transfer logic.
1607bdd1243dSDimitry Andric   stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) {
1608bdd1243dSDimitry Andric     auto HasNoConstOp = [](const FactOrCheck &B) {
16095f757f3fSDimitry Andric       Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0);
16105f757f3fSDimitry Andric       Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1);
16115f757f3fSDimitry Andric       return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1);
1612bdd1243dSDimitry Andric     };
1613bdd1243dSDimitry Andric     // If both entries have the same In numbers, conditional facts come first.
1614bdd1243dSDimitry Andric     // Otherwise use the relative order in the basic block.
1615bdd1243dSDimitry Andric     if (A.NumIn == B.NumIn) {
1616bdd1243dSDimitry Andric       if (A.isConditionFact() && B.isConditionFact()) {
1617bdd1243dSDimitry Andric         bool NoConstOpA = HasNoConstOp(A);
1618bdd1243dSDimitry Andric         bool NoConstOpB = HasNoConstOp(B);
1619bdd1243dSDimitry Andric         return NoConstOpA < NoConstOpB;
1620bdd1243dSDimitry Andric       }
1621bdd1243dSDimitry Andric       if (A.isConditionFact())
1622bdd1243dSDimitry Andric         return true;
1623bdd1243dSDimitry Andric       if (B.isConditionFact())
1624bdd1243dSDimitry Andric         return false;
162506c3fb27SDimitry Andric       auto *InstA = A.getContextInst();
162606c3fb27SDimitry Andric       auto *InstB = B.getContextInst();
162706c3fb27SDimitry Andric       return InstA->comesBefore(InstB);
1628bdd1243dSDimitry Andric     }
1629bdd1243dSDimitry Andric     return A.NumIn < B.NumIn;
1630e8d8bef9SDimitry Andric   });
1631e8d8bef9SDimitry Andric 
163281ad6265SDimitry Andric   SmallVector<Instruction *> ToRemove;
163381ad6265SDimitry Andric 
1634e8d8bef9SDimitry Andric   // Finally, process ordered worklist and eliminate implied conditions.
1635e8d8bef9SDimitry Andric   SmallVector<StackEntry, 16> DFSInStack;
163606c3fb27SDimitry Andric   SmallVector<ReproducerEntry> ReproducerCondStack;
1637bdd1243dSDimitry Andric   for (FactOrCheck &CB : S.WorkList) {
1638e8d8bef9SDimitry Andric     // First, pop entries from the stack that are out-of-scope for CB. Remove
1639e8d8bef9SDimitry Andric     // the corresponding entry from the constraint system.
1640e8d8bef9SDimitry Andric     while (!DFSInStack.empty()) {
1641e8d8bef9SDimitry Andric       auto &E = DFSInStack.back();
1642e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
1643e8d8bef9SDimitry Andric                         << "\n");
1644e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
1645e8d8bef9SDimitry Andric       assert(E.NumIn <= CB.NumIn);
1646e8d8bef9SDimitry Andric       if (CB.NumOut <= E.NumOut)
1647e8d8bef9SDimitry Andric         break;
164881ad6265SDimitry Andric       LLVM_DEBUG({
164981ad6265SDimitry Andric         dbgs() << "Removing ";
165006c3fb27SDimitry Andric         dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(),
165181ad6265SDimitry Andric                        Info.getValue2Index(E.IsSigned));
165281ad6265SDimitry Andric         dbgs() << "\n";
165381ad6265SDimitry Andric       });
165406c3fb27SDimitry Andric       removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack,
165506c3fb27SDimitry Andric                            DFSInStack);
1656e8d8bef9SDimitry Andric     }
1657e8d8bef9SDimitry Andric 
165806c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "Processing ");
1659e8d8bef9SDimitry Andric 
1660e8d8bef9SDimitry Andric     // For a block, check if any CmpInsts become known based on the current set
1661e8d8bef9SDimitry Andric     // of constraints.
166206c3fb27SDimitry Andric     if (CB.isCheck()) {
166306c3fb27SDimitry Andric       Instruction *Inst = CB.getInstructionToSimplify();
166406c3fb27SDimitry Andric       if (!Inst)
166506c3fb27SDimitry Andric         continue;
166606c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "condition to simplify: " << *Inst << "\n");
166706c3fb27SDimitry Andric       if (auto *II = dyn_cast<WithOverflowInst>(Inst)) {
1668bdd1243dSDimitry Andric         Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove);
166906c3fb27SDimitry Andric       } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) {
167006c3fb27SDimitry Andric         bool Simplified = checkAndReplaceCondition(
167106c3fb27SDimitry Andric             Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(),
16725f757f3fSDimitry Andric             ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove);
1673cb14a3feSDimitry Andric         if (!Simplified &&
1674cb14a3feSDimitry Andric             match(CB.getContextInst(), m_LogicalOp(m_Value(), m_Value()))) {
167506c3fb27SDimitry Andric           Simplified =
1676cb14a3feSDimitry Andric               checkOrAndOpImpliedByOther(CB, Info, ReproducerModule.get(),
167706c3fb27SDimitry Andric                                          ReproducerCondStack, DFSInStack);
167806c3fb27SDimitry Andric         }
167906c3fb27SDimitry Andric         Changed |= Simplified;
1680e8d8bef9SDimitry Andric       }
1681e8d8bef9SDimitry Andric       continue;
1682e8d8bef9SDimitry Andric     }
1683e8d8bef9SDimitry Andric 
168406c3fb27SDimitry Andric     auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) {
16855f757f3fSDimitry Andric       LLVM_DEBUG(dbgs() << "fact to add to the system: ";
16865f757f3fSDimitry Andric                  dumpUnpackedICmp(dbgs(), Pred, A, B); dbgs() << "\n");
1687bdd1243dSDimitry Andric       if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) {
1688bdd1243dSDimitry Andric         LLVM_DEBUG(
1689bdd1243dSDimitry Andric             dbgs()
1690bdd1243dSDimitry Andric             << "Skip adding constraint because system has too many rows.\n");
169106c3fb27SDimitry Andric         return;
169206c3fb27SDimitry Andric       }
169306c3fb27SDimitry Andric 
169406c3fb27SDimitry Andric       Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
169506c3fb27SDimitry Andric       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size())
169606c3fb27SDimitry Andric         ReproducerCondStack.emplace_back(Pred, A, B);
169706c3fb27SDimitry Andric 
169806c3fb27SDimitry Andric       Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack);
169906c3fb27SDimitry Andric       if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) {
170006c3fb27SDimitry Andric         // Add dummy entries to ReproducerCondStack to keep it in sync with
170106c3fb27SDimitry Andric         // DFSInStack.
170206c3fb27SDimitry Andric         for (unsigned I = 0,
170306c3fb27SDimitry Andric                       E = (DFSInStack.size() - ReproducerCondStack.size());
170406c3fb27SDimitry Andric              I < E; ++I) {
170506c3fb27SDimitry Andric           ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE,
170606c3fb27SDimitry Andric                                            nullptr, nullptr);
170706c3fb27SDimitry Andric         }
170806c3fb27SDimitry Andric       }
170906c3fb27SDimitry Andric     };
171006c3fb27SDimitry Andric 
171106c3fb27SDimitry Andric     ICmpInst::Predicate Pred;
17125f757f3fSDimitry Andric     if (!CB.isConditionFact()) {
1713*647cbc5dSDimitry Andric       Value *X;
1714*647cbc5dSDimitry Andric       if (match(CB.Inst, m_Intrinsic<Intrinsic::abs>(m_Value(X)))) {
1715*647cbc5dSDimitry Andric         // TODO: Add CB.Inst >= 0 fact.
1716*647cbc5dSDimitry Andric         AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
1717*647cbc5dSDimitry Andric         continue;
1718*647cbc5dSDimitry Andric       }
1719*647cbc5dSDimitry Andric 
172006c3fb27SDimitry Andric       if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) {
172106c3fb27SDimitry Andric         Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
172206c3fb27SDimitry Andric         AddFact(Pred, MinMax, MinMax->getLHS());
172306c3fb27SDimitry Andric         AddFact(Pred, MinMax, MinMax->getRHS());
1724bdd1243dSDimitry Andric         continue;
1725bdd1243dSDimitry Andric       }
1726e8d8bef9SDimitry Andric     }
17275f757f3fSDimitry Andric 
17285f757f3fSDimitry Andric     Value *A = nullptr, *B = nullptr;
17295f757f3fSDimitry Andric     if (CB.isConditionFact()) {
17305f757f3fSDimitry Andric       Pred = CB.Cond.Pred;
17315f757f3fSDimitry Andric       A = CB.Cond.Op0;
17325f757f3fSDimitry Andric       B = CB.Cond.Op1;
17335f757f3fSDimitry Andric       if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE &&
17345f757f3fSDimitry Andric           !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1))
17355f757f3fSDimitry Andric         continue;
17365f757f3fSDimitry Andric     } else {
17375f757f3fSDimitry Andric       bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>(
17385f757f3fSDimitry Andric                                         m_ICmp(Pred, m_Value(A), m_Value(B))));
17395f757f3fSDimitry Andric       (void)Matched;
17405f757f3fSDimitry Andric       assert(Matched && "Must have an assume intrinsic with a icmp operand");
17415f757f3fSDimitry Andric     }
17425f757f3fSDimitry Andric     AddFact(Pred, A, B);
1743fe6060f1SDimitry Andric   }
1744e8d8bef9SDimitry Andric 
174506c3fb27SDimitry Andric   if (ReproducerModule && !ReproducerModule->functions().empty()) {
174606c3fb27SDimitry Andric     std::string S;
174706c3fb27SDimitry Andric     raw_string_ostream StringS(S);
174806c3fb27SDimitry Andric     ReproducerModule->print(StringS, nullptr);
174906c3fb27SDimitry Andric     StringS.flush();
175006c3fb27SDimitry Andric     OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F);
175106c3fb27SDimitry Andric     Rem << ore::NV("module") << S;
175206c3fb27SDimitry Andric     ORE.emit(Rem);
175306c3fb27SDimitry Andric   }
175406c3fb27SDimitry Andric 
175581ad6265SDimitry Andric #ifndef NDEBUG
175681ad6265SDimitry Andric   unsigned SignedEntries =
175781ad6265SDimitry Andric       count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; });
1758cb14a3feSDimitry Andric   assert(Info.getCS(false).size() - FunctionArgs.size() ==
1759cb14a3feSDimitry Andric              DFSInStack.size() - SignedEntries &&
1760fe6060f1SDimitry Andric          "updates to CS and DFSInStack are out of sync");
176181ad6265SDimitry Andric   assert(Info.getCS(true).size() == SignedEntries &&
176281ad6265SDimitry Andric          "updates to CS and DFSInStack are out of sync");
176381ad6265SDimitry Andric #endif
176481ad6265SDimitry Andric 
176581ad6265SDimitry Andric   for (Instruction *I : ToRemove)
176681ad6265SDimitry Andric     I->eraseFromParent();
1767e8d8bef9SDimitry Andric   return Changed;
1768e8d8bef9SDimitry Andric }
1769e8d8bef9SDimitry Andric 
1770e8d8bef9SDimitry Andric PreservedAnalyses ConstraintEliminationPass::run(Function &F,
1771e8d8bef9SDimitry Andric                                                  FunctionAnalysisManager &AM) {
1772e8d8bef9SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
17735f757f3fSDimitry Andric   auto &LI = AM.getResult<LoopAnalysis>(F);
17745f757f3fSDimitry Andric   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
177506c3fb27SDimitry Andric   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
17765f757f3fSDimitry Andric   if (!eliminateConstraints(F, DT, LI, SE, ORE))
1777e8d8bef9SDimitry Andric     return PreservedAnalyses::all();
1778e8d8bef9SDimitry Andric 
1779e8d8bef9SDimitry Andric   PreservedAnalyses PA;
1780e8d8bef9SDimitry Andric   PA.preserve<DominatorTreeAnalysis>();
17815f757f3fSDimitry Andric   PA.preserve<LoopAnalysis>();
17825f757f3fSDimitry Andric   PA.preserve<ScalarEvolutionAnalysis>();
1783e8d8bef9SDimitry Andric   PA.preserveSet<CFGAnalyses>();
1784e8d8bef9SDimitry Andric   return PA;
1785e8d8bef9SDimitry Andric }
1786