xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
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"
21*349cc55cSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
22e8d8bef9SDimitry Andric #include "llvm/IR/DataLayout.h"
23e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h"
24e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
25e8d8bef9SDimitry Andric #include "llvm/IR/Instructions.h"
26e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h"
27e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h"
28e8d8bef9SDimitry Andric #include "llvm/Pass.h"
29e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h"
30e8d8bef9SDimitry Andric #include "llvm/Support/DebugCounter.h"
31e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar.h"
32e8d8bef9SDimitry Andric 
33fe6060f1SDimitry Andric #include <string>
34fe6060f1SDimitry Andric 
35e8d8bef9SDimitry Andric using namespace llvm;
36e8d8bef9SDimitry Andric using namespace PatternMatch;
37e8d8bef9SDimitry Andric 
38e8d8bef9SDimitry Andric #define DEBUG_TYPE "constraint-elimination"
39e8d8bef9SDimitry Andric 
40e8d8bef9SDimitry Andric STATISTIC(NumCondsRemoved, "Number of instructions removed");
41e8d8bef9SDimitry Andric DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
42e8d8bef9SDimitry Andric               "Controls which conditions are eliminated");
43e8d8bef9SDimitry Andric 
44e8d8bef9SDimitry Andric static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
45e8d8bef9SDimitry Andric 
46e8d8bef9SDimitry Andric // Decomposes \p V into a vector of pairs of the form { c, X } where c * X. The
47e8d8bef9SDimitry Andric // sum of the pairs equals \p V.  The first pair is the constant-factor and X
48e8d8bef9SDimitry Andric // must be nullptr. If the expression cannot be decomposed, returns an empty
49e8d8bef9SDimitry Andric // vector.
50e8d8bef9SDimitry Andric static SmallVector<std::pair<int64_t, Value *>, 4> decompose(Value *V) {
51e8d8bef9SDimitry Andric   if (auto *CI = dyn_cast<ConstantInt>(V)) {
52e8d8bef9SDimitry Andric     if (CI->isNegative() || CI->uge(MaxConstraintValue))
53e8d8bef9SDimitry Andric       return {};
54e8d8bef9SDimitry Andric     return {{CI->getSExtValue(), nullptr}};
55e8d8bef9SDimitry Andric   }
56e8d8bef9SDimitry Andric   auto *GEP = dyn_cast<GetElementPtrInst>(V);
57fe6060f1SDimitry Andric   if (GEP && GEP->getNumOperands() == 2 && GEP->isInBounds()) {
58fe6060f1SDimitry Andric     Value *Op0, *Op1;
59e8d8bef9SDimitry Andric     ConstantInt *CI;
60fe6060f1SDimitry Andric 
61fe6060f1SDimitry Andric     // If the index is zero-extended, it is guaranteed to be positive.
62fe6060f1SDimitry Andric     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
63fe6060f1SDimitry Andric               m_ZExt(m_Value(Op0)))) {
64fe6060f1SDimitry Andric       if (match(Op0, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))))
65fe6060f1SDimitry Andric         return {{0, nullptr},
66fe6060f1SDimitry Andric                 {1, GEP->getPointerOperand()},
67fe6060f1SDimitry Andric                 {std::pow(int64_t(2), CI->getSExtValue()), Op1}};
68fe6060f1SDimitry Andric       if (match(Op0, m_NSWAdd(m_Value(Op1), m_ConstantInt(CI))))
69fe6060f1SDimitry Andric         return {{CI->getSExtValue(), nullptr},
70fe6060f1SDimitry Andric                 {1, GEP->getPointerOperand()},
71fe6060f1SDimitry Andric                 {1, Op1}};
72fe6060f1SDimitry Andric       return {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}};
73fe6060f1SDimitry Andric     }
74fe6060f1SDimitry Andric 
75fe6060f1SDimitry Andric     if (match(GEP->getOperand(GEP->getNumOperands() - 1), m_ConstantInt(CI)) &&
76fe6060f1SDimitry Andric         !CI->isNegative())
77fe6060f1SDimitry Andric       return {{CI->getSExtValue(), nullptr}, {1, GEP->getPointerOperand()}};
78fe6060f1SDimitry Andric 
79fe6060f1SDimitry Andric     SmallVector<std::pair<int64_t, Value *>, 4> Result;
80e8d8bef9SDimitry Andric     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
81e8d8bef9SDimitry Andric               m_NUWShl(m_Value(Op0), m_ConstantInt(CI))))
82fe6060f1SDimitry Andric       Result = {{0, nullptr},
83e8d8bef9SDimitry Andric                 {1, GEP->getPointerOperand()},
84e8d8bef9SDimitry Andric                 {std::pow(int64_t(2), CI->getSExtValue()), Op0}};
85fe6060f1SDimitry Andric     else if (match(GEP->getOperand(GEP->getNumOperands() - 1),
86fe6060f1SDimitry Andric                    m_NSWAdd(m_Value(Op0), m_ConstantInt(CI))))
87fe6060f1SDimitry Andric       Result = {{CI->getSExtValue(), nullptr},
88e8d8bef9SDimitry Andric                 {1, GEP->getPointerOperand()},
89fe6060f1SDimitry Andric                 {1, Op0}};
90fe6060f1SDimitry Andric     else {
91fe6060f1SDimitry Andric       Op0 = GEP->getOperand(GEP->getNumOperands() - 1);
92fe6060f1SDimitry Andric       Result = {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}};
93fe6060f1SDimitry Andric     }
94fe6060f1SDimitry Andric     return Result;
95e8d8bef9SDimitry Andric   }
96e8d8bef9SDimitry Andric 
97e8d8bef9SDimitry Andric   Value *Op0;
98fe6060f1SDimitry Andric   if (match(V, m_ZExt(m_Value(Op0))))
99fe6060f1SDimitry Andric     V = Op0;
100fe6060f1SDimitry Andric 
101e8d8bef9SDimitry Andric   Value *Op1;
102e8d8bef9SDimitry Andric   ConstantInt *CI;
103e8d8bef9SDimitry Andric   if (match(V, m_NUWAdd(m_Value(Op0), m_ConstantInt(CI))))
104e8d8bef9SDimitry Andric     return {{CI->getSExtValue(), nullptr}, {1, Op0}};
105e8d8bef9SDimitry Andric   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1))))
106e8d8bef9SDimitry Andric     return {{0, nullptr}, {1, Op0}, {1, Op1}};
107e8d8bef9SDimitry Andric 
108e8d8bef9SDimitry Andric   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))))
109e8d8bef9SDimitry Andric     return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}};
110e8d8bef9SDimitry Andric   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
111e8d8bef9SDimitry Andric     return {{0, nullptr}, {1, Op0}, {1, Op1}};
112e8d8bef9SDimitry Andric 
113e8d8bef9SDimitry Andric   return {{0, nullptr}, {1, V}};
114e8d8bef9SDimitry Andric }
115e8d8bef9SDimitry Andric 
116fe6060f1SDimitry Andric struct ConstraintTy {
117fe6060f1SDimitry Andric   SmallVector<int64_t, 8> Coefficients;
118fe6060f1SDimitry Andric 
119fe6060f1SDimitry Andric   ConstraintTy(SmallVector<int64_t, 8> Coefficients)
120fe6060f1SDimitry Andric       : Coefficients(Coefficients) {}
121fe6060f1SDimitry Andric 
122fe6060f1SDimitry Andric   unsigned size() const { return Coefficients.size(); }
123fe6060f1SDimitry Andric };
124fe6060f1SDimitry Andric 
125fe6060f1SDimitry Andric /// Turn a condition \p CmpI into a vector of constraints, using indices from \p
126fe6060f1SDimitry Andric /// Value2Index. Additional indices for newly discovered values are added to \p
127fe6060f1SDimitry Andric /// NewIndices.
128fe6060f1SDimitry Andric static SmallVector<ConstraintTy, 4>
129e8d8bef9SDimitry Andric getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
130fe6060f1SDimitry Andric               const DenseMap<Value *, unsigned> &Value2Index,
131fe6060f1SDimitry Andric               DenseMap<Value *, unsigned> &NewIndices) {
132e8d8bef9SDimitry Andric   int64_t Offset1 = 0;
133e8d8bef9SDimitry Andric   int64_t Offset2 = 0;
134e8d8bef9SDimitry Andric 
135fe6060f1SDimitry Andric   // First try to look up \p V in Value2Index and NewIndices. Otherwise add a
136fe6060f1SDimitry Andric   // new entry to NewIndices.
137fe6060f1SDimitry Andric   auto GetOrAddIndex = [&Value2Index, &NewIndices](Value *V) -> unsigned {
138fe6060f1SDimitry Andric     auto V2I = Value2Index.find(V);
139fe6060f1SDimitry Andric     if (V2I != Value2Index.end())
140fe6060f1SDimitry Andric       return V2I->second;
141fe6060f1SDimitry Andric     auto NewI = NewIndices.find(V);
142fe6060f1SDimitry Andric     if (NewI != NewIndices.end())
143fe6060f1SDimitry Andric       return NewI->second;
144fe6060f1SDimitry Andric     auto Insert =
145fe6060f1SDimitry Andric         NewIndices.insert({V, Value2Index.size() + NewIndices.size() + 1});
146fe6060f1SDimitry Andric     return Insert.first->second;
147e8d8bef9SDimitry Andric   };
148e8d8bef9SDimitry Andric 
149e8d8bef9SDimitry Andric   if (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE)
150e8d8bef9SDimitry Andric     return getConstraint(CmpInst::getSwappedPredicate(Pred), Op1, Op0,
151fe6060f1SDimitry Andric                          Value2Index, NewIndices);
152fe6060f1SDimitry Andric 
153fe6060f1SDimitry Andric   if (Pred == CmpInst::ICMP_EQ) {
154fe6060f1SDimitry Andric     auto A =
155fe6060f1SDimitry Andric         getConstraint(CmpInst::ICMP_UGE, Op0, Op1, Value2Index, NewIndices);
156fe6060f1SDimitry Andric     auto B =
157fe6060f1SDimitry Andric         getConstraint(CmpInst::ICMP_ULE, Op0, Op1, Value2Index, NewIndices);
158fe6060f1SDimitry Andric     append_range(A, B);
159fe6060f1SDimitry Andric     return A;
160fe6060f1SDimitry Andric   }
161fe6060f1SDimitry Andric 
162fe6060f1SDimitry Andric   if (Pred == CmpInst::ICMP_NE && match(Op1, m_Zero())) {
163fe6060f1SDimitry Andric     return getConstraint(CmpInst::ICMP_UGT, Op0, Op1, Value2Index, NewIndices);
164fe6060f1SDimitry Andric   }
165e8d8bef9SDimitry Andric 
166e8d8bef9SDimitry Andric   // Only ULE and ULT predicates are supported at the moment.
167e8d8bef9SDimitry Andric   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT)
168e8d8bef9SDimitry Andric     return {};
169e8d8bef9SDimitry Andric 
170fe6060f1SDimitry Andric   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation());
171fe6060f1SDimitry Andric   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation());
172e8d8bef9SDimitry Andric   // Skip if decomposing either of the values failed.
173e8d8bef9SDimitry Andric   if (ADec.empty() || BDec.empty())
174e8d8bef9SDimitry Andric     return {};
175e8d8bef9SDimitry Andric 
176e8d8bef9SDimitry Andric   // Skip trivial constraints without any variables.
177e8d8bef9SDimitry Andric   if (ADec.size() == 1 && BDec.size() == 1)
178e8d8bef9SDimitry Andric     return {};
179e8d8bef9SDimitry Andric 
180e8d8bef9SDimitry Andric   Offset1 = ADec[0].first;
181e8d8bef9SDimitry Andric   Offset2 = BDec[0].first;
182e8d8bef9SDimitry Andric   Offset1 *= -1;
183e8d8bef9SDimitry Andric 
184e8d8bef9SDimitry Andric   // Create iterator ranges that skip the constant-factor.
185fe6060f1SDimitry Andric   auto VariablesA = llvm::drop_begin(ADec);
186fe6060f1SDimitry Andric   auto VariablesB = llvm::drop_begin(BDec);
187e8d8bef9SDimitry Andric 
188fe6060f1SDimitry Andric   // Make sure all variables have entries in Value2Index or NewIndices.
189e8d8bef9SDimitry Andric   for (const auto &KV :
190e8d8bef9SDimitry Andric        concat<std::pair<int64_t, Value *>>(VariablesA, VariablesB))
191fe6060f1SDimitry Andric     GetOrAddIndex(KV.second);
192e8d8bef9SDimitry Andric 
193e8d8bef9SDimitry Andric   // Build result constraint, by first adding all coefficients from A and then
194e8d8bef9SDimitry Andric   // subtracting all coefficients from B.
195fe6060f1SDimitry Andric   SmallVector<int64_t, 8> R(Value2Index.size() + NewIndices.size() + 1, 0);
196e8d8bef9SDimitry Andric   for (const auto &KV : VariablesA)
197fe6060f1SDimitry Andric     R[GetOrAddIndex(KV.second)] += KV.first;
198e8d8bef9SDimitry Andric 
199e8d8bef9SDimitry Andric   for (const auto &KV : VariablesB)
200fe6060f1SDimitry Andric     R[GetOrAddIndex(KV.second)] -= KV.first;
201e8d8bef9SDimitry Andric 
202e8d8bef9SDimitry Andric   R[0] = Offset1 + Offset2 + (Pred == CmpInst::ICMP_ULT ? -1 : 0);
203fe6060f1SDimitry Andric   return {R};
204e8d8bef9SDimitry Andric }
205e8d8bef9SDimitry Andric 
206fe6060f1SDimitry Andric static SmallVector<ConstraintTy, 4>
207fe6060f1SDimitry Andric getConstraint(CmpInst *Cmp, const DenseMap<Value *, unsigned> &Value2Index,
208fe6060f1SDimitry Andric               DenseMap<Value *, unsigned> &NewIndices) {
209e8d8bef9SDimitry Andric   return getConstraint(Cmp->getPredicate(), Cmp->getOperand(0),
210fe6060f1SDimitry Andric                        Cmp->getOperand(1), Value2Index, NewIndices);
211e8d8bef9SDimitry Andric }
212e8d8bef9SDimitry Andric 
213e8d8bef9SDimitry Andric namespace {
214e8d8bef9SDimitry Andric /// Represents either a condition that holds on entry to a block or a basic
215e8d8bef9SDimitry Andric /// block, with their respective Dominator DFS in and out numbers.
216e8d8bef9SDimitry Andric struct ConstraintOrBlock {
217e8d8bef9SDimitry Andric   unsigned NumIn;
218e8d8bef9SDimitry Andric   unsigned NumOut;
219e8d8bef9SDimitry Andric   bool IsBlock;
220e8d8bef9SDimitry Andric   bool Not;
221e8d8bef9SDimitry Andric   union {
222e8d8bef9SDimitry Andric     BasicBlock *BB;
223e8d8bef9SDimitry Andric     CmpInst *Condition;
224e8d8bef9SDimitry Andric   };
225e8d8bef9SDimitry Andric 
226e8d8bef9SDimitry Andric   ConstraintOrBlock(DomTreeNode *DTN)
227e8d8bef9SDimitry Andric       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
228e8d8bef9SDimitry Andric         BB(DTN->getBlock()) {}
229e8d8bef9SDimitry Andric   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
230e8d8bef9SDimitry Andric       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
231e8d8bef9SDimitry Andric         Not(Not), Condition(Condition) {}
232e8d8bef9SDimitry Andric };
233e8d8bef9SDimitry Andric 
234e8d8bef9SDimitry Andric struct StackEntry {
235e8d8bef9SDimitry Andric   unsigned NumIn;
236e8d8bef9SDimitry Andric   unsigned NumOut;
237e8d8bef9SDimitry Andric   CmpInst *Condition;
238e8d8bef9SDimitry Andric   bool IsNot;
239e8d8bef9SDimitry Andric 
240e8d8bef9SDimitry Andric   StackEntry(unsigned NumIn, unsigned NumOut, CmpInst *Condition, bool IsNot)
241e8d8bef9SDimitry Andric       : NumIn(NumIn), NumOut(NumOut), Condition(Condition), IsNot(IsNot) {}
242e8d8bef9SDimitry Andric };
243e8d8bef9SDimitry Andric } // namespace
244e8d8bef9SDimitry Andric 
245fe6060f1SDimitry Andric #ifndef NDEBUG
246fe6060f1SDimitry Andric static void dumpWithNames(ConstraintTy &C,
247fe6060f1SDimitry Andric                           DenseMap<Value *, unsigned> &Value2Index) {
248fe6060f1SDimitry Andric   SmallVector<std::string> Names(Value2Index.size(), "");
249fe6060f1SDimitry Andric   for (auto &KV : Value2Index) {
250fe6060f1SDimitry Andric     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
251fe6060f1SDimitry Andric   }
252fe6060f1SDimitry Andric   ConstraintSystem CS;
253fe6060f1SDimitry Andric   CS.addVariableRowFill(C.Coefficients);
254fe6060f1SDimitry Andric   CS.dump(Names);
255fe6060f1SDimitry Andric }
256fe6060f1SDimitry Andric #endif
257fe6060f1SDimitry Andric 
258e8d8bef9SDimitry Andric static bool eliminateConstraints(Function &F, DominatorTree &DT) {
259e8d8bef9SDimitry Andric   bool Changed = false;
260e8d8bef9SDimitry Andric   DT.updateDFSNumbers();
261e8d8bef9SDimitry Andric   ConstraintSystem CS;
262e8d8bef9SDimitry Andric 
263e8d8bef9SDimitry Andric   SmallVector<ConstraintOrBlock, 64> WorkList;
264e8d8bef9SDimitry Andric 
265e8d8bef9SDimitry Andric   // First, collect conditions implied by branches and blocks with their
266e8d8bef9SDimitry Andric   // Dominator DFS in and out numbers.
267e8d8bef9SDimitry Andric   for (BasicBlock &BB : F) {
268e8d8bef9SDimitry Andric     if (!DT.getNode(&BB))
269e8d8bef9SDimitry Andric       continue;
270e8d8bef9SDimitry Andric     WorkList.emplace_back(DT.getNode(&BB));
271e8d8bef9SDimitry Andric 
272*349cc55cSDimitry Andric     // True as long as long as the current instruction is guaranteed to execute.
273*349cc55cSDimitry Andric     bool GuaranteedToExecute = true;
274*349cc55cSDimitry Andric     // Scan BB for assume calls.
275*349cc55cSDimitry Andric     // TODO: also use this scan to queue conditions to simplify, so we can
276*349cc55cSDimitry Andric     // interleave facts from assumes and conditions to simplify in a single
277*349cc55cSDimitry Andric     // basic block. And to skip another traversal of each basic block when
278*349cc55cSDimitry Andric     // simplifying.
279*349cc55cSDimitry Andric     for (Instruction &I : BB) {
280*349cc55cSDimitry Andric       Value *Cond;
281*349cc55cSDimitry Andric       // For now, just handle assumes with a single compare as condition.
282*349cc55cSDimitry Andric       if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) &&
283*349cc55cSDimitry Andric           isa<CmpInst>(Cond)) {
284*349cc55cSDimitry Andric         if (GuaranteedToExecute) {
285*349cc55cSDimitry Andric           // The assume is guaranteed to execute when BB is entered, hence Cond
286*349cc55cSDimitry Andric           // holds on entry to BB.
287*349cc55cSDimitry Andric           WorkList.emplace_back(DT.getNode(&BB), cast<CmpInst>(Cond), false);
288*349cc55cSDimitry Andric         } else {
289*349cc55cSDimitry Andric           // Otherwise the condition only holds in the successors.
290*349cc55cSDimitry Andric           for (BasicBlock *Succ : successors(&BB))
291*349cc55cSDimitry Andric             WorkList.emplace_back(DT.getNode(Succ), cast<CmpInst>(Cond), false);
292*349cc55cSDimitry Andric         }
293*349cc55cSDimitry Andric       }
294*349cc55cSDimitry Andric       GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I);
295*349cc55cSDimitry Andric     }
296*349cc55cSDimitry Andric 
297e8d8bef9SDimitry Andric     auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
298e8d8bef9SDimitry Andric     if (!Br || !Br->isConditional())
299e8d8bef9SDimitry Andric       continue;
300e8d8bef9SDimitry Andric 
301fe6060f1SDimitry Andric     // Returns true if we can add a known condition from BB to its successor
302fe6060f1SDimitry Andric     // block Succ. Each predecessor of Succ can either be BB or be dominated by
303fe6060f1SDimitry Andric     // Succ (e.g. the case when adding a condition from a pre-header to a loop
304fe6060f1SDimitry Andric     // header).
305fe6060f1SDimitry Andric     auto CanAdd = [&BB, &DT](BasicBlock *Succ) {
306fe6060f1SDimitry Andric       return all_of(predecessors(Succ), [&BB, &DT, Succ](BasicBlock *Pred) {
307fe6060f1SDimitry Andric         return Pred == &BB || DT.dominates(Succ, Pred);
308fe6060f1SDimitry Andric       });
309fe6060f1SDimitry Andric     };
310e8d8bef9SDimitry Andric     // If the condition is an OR of 2 compares and the false successor only has
311e8d8bef9SDimitry Andric     // the current block as predecessor, queue both negated conditions for the
312e8d8bef9SDimitry Andric     // false successor.
313e8d8bef9SDimitry Andric     Value *Op0, *Op1;
314e8d8bef9SDimitry Andric     if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) &&
315e8d8bef9SDimitry Andric         match(Op0, m_Cmp()) && match(Op1, m_Cmp())) {
316e8d8bef9SDimitry Andric       BasicBlock *FalseSuccessor = Br->getSuccessor(1);
317fe6060f1SDimitry Andric       if (CanAdd(FalseSuccessor)) {
318e8d8bef9SDimitry Andric         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<CmpInst>(Op0),
319e8d8bef9SDimitry Andric                               true);
320e8d8bef9SDimitry Andric         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<CmpInst>(Op1),
321e8d8bef9SDimitry Andric                               true);
322e8d8bef9SDimitry Andric       }
323e8d8bef9SDimitry Andric       continue;
324e8d8bef9SDimitry Andric     }
325e8d8bef9SDimitry Andric 
326e8d8bef9SDimitry Andric     // If the condition is an AND of 2 compares and the true successor only has
327e8d8bef9SDimitry Andric     // the current block as predecessor, queue both conditions for the true
328e8d8bef9SDimitry Andric     // successor.
329e8d8bef9SDimitry Andric     if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) &&
330e8d8bef9SDimitry Andric         match(Op0, m_Cmp()) && match(Op1, m_Cmp())) {
331e8d8bef9SDimitry Andric       BasicBlock *TrueSuccessor = Br->getSuccessor(0);
332fe6060f1SDimitry Andric       if (CanAdd(TrueSuccessor)) {
333e8d8bef9SDimitry Andric         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<CmpInst>(Op0),
334e8d8bef9SDimitry Andric                               false);
335e8d8bef9SDimitry Andric         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<CmpInst>(Op1),
336e8d8bef9SDimitry Andric                               false);
337e8d8bef9SDimitry Andric       }
338e8d8bef9SDimitry Andric       continue;
339e8d8bef9SDimitry Andric     }
340e8d8bef9SDimitry Andric 
341e8d8bef9SDimitry Andric     auto *CmpI = dyn_cast<CmpInst>(Br->getCondition());
342e8d8bef9SDimitry Andric     if (!CmpI)
343e8d8bef9SDimitry Andric       continue;
344fe6060f1SDimitry Andric     if (CanAdd(Br->getSuccessor(0)))
345e8d8bef9SDimitry Andric       WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
346fe6060f1SDimitry Andric     if (CanAdd(Br->getSuccessor(1)))
347e8d8bef9SDimitry Andric       WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
348e8d8bef9SDimitry Andric   }
349e8d8bef9SDimitry Andric 
350e8d8bef9SDimitry Andric   // Next, sort worklist by dominance, so that dominating blocks and conditions
351e8d8bef9SDimitry Andric   // come before blocks and conditions dominated by them. If a block and a
352e8d8bef9SDimitry Andric   // condition have the same numbers, the condition comes before the block, as
353e8d8bef9SDimitry Andric   // it holds on entry to the block.
354e8d8bef9SDimitry Andric   sort(WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
355e8d8bef9SDimitry Andric     return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock);
356e8d8bef9SDimitry Andric   });
357e8d8bef9SDimitry Andric 
358e8d8bef9SDimitry Andric   // Finally, process ordered worklist and eliminate implied conditions.
359e8d8bef9SDimitry Andric   SmallVector<StackEntry, 16> DFSInStack;
360e8d8bef9SDimitry Andric   DenseMap<Value *, unsigned> Value2Index;
361e8d8bef9SDimitry Andric   for (ConstraintOrBlock &CB : WorkList) {
362e8d8bef9SDimitry Andric     // First, pop entries from the stack that are out-of-scope for CB. Remove
363e8d8bef9SDimitry Andric     // the corresponding entry from the constraint system.
364e8d8bef9SDimitry Andric     while (!DFSInStack.empty()) {
365e8d8bef9SDimitry Andric       auto &E = DFSInStack.back();
366e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
367e8d8bef9SDimitry Andric                         << "\n");
368e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
369e8d8bef9SDimitry Andric       assert(E.NumIn <= CB.NumIn);
370e8d8bef9SDimitry Andric       if (CB.NumOut <= E.NumOut)
371e8d8bef9SDimitry Andric         break;
372e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Removing " << *E.Condition << " " << E.IsNot
373e8d8bef9SDimitry Andric                         << "\n");
374e8d8bef9SDimitry Andric       DFSInStack.pop_back();
375e8d8bef9SDimitry Andric       CS.popLastConstraint();
376e8d8bef9SDimitry Andric     }
377e8d8bef9SDimitry Andric 
378e8d8bef9SDimitry Andric     LLVM_DEBUG({
379e8d8bef9SDimitry Andric       dbgs() << "Processing ";
380e8d8bef9SDimitry Andric       if (CB.IsBlock)
381e8d8bef9SDimitry Andric         dbgs() << *CB.BB;
382e8d8bef9SDimitry Andric       else
383e8d8bef9SDimitry Andric         dbgs() << *CB.Condition;
384e8d8bef9SDimitry Andric       dbgs() << "\n";
385e8d8bef9SDimitry Andric     });
386e8d8bef9SDimitry Andric 
387e8d8bef9SDimitry Andric     // For a block, check if any CmpInsts become known based on the current set
388e8d8bef9SDimitry Andric     // of constraints.
389e8d8bef9SDimitry Andric     if (CB.IsBlock) {
390e8d8bef9SDimitry Andric       for (Instruction &I : *CB.BB) {
391e8d8bef9SDimitry Andric         auto *Cmp = dyn_cast<CmpInst>(&I);
392e8d8bef9SDimitry Andric         if (!Cmp)
393e8d8bef9SDimitry Andric           continue;
394fe6060f1SDimitry Andric 
395fe6060f1SDimitry Andric         DenseMap<Value *, unsigned> NewIndices;
396fe6060f1SDimitry Andric         auto R = getConstraint(Cmp, Value2Index, NewIndices);
397fe6060f1SDimitry Andric         if (R.size() != 1)
398e8d8bef9SDimitry Andric           continue;
399fe6060f1SDimitry Andric 
400fe6060f1SDimitry Andric         // Check if all coefficients of new indices are 0 after building the
401fe6060f1SDimitry Andric         // constraint. Skip if any of the new indices has a non-null
402fe6060f1SDimitry Andric         // coefficient.
403fe6060f1SDimitry Andric         bool HasNewIndex = false;
404fe6060f1SDimitry Andric         for (unsigned I = 0; I < NewIndices.size(); ++I) {
405fe6060f1SDimitry Andric           int64_t Last = R[0].Coefficients.pop_back_val();
406fe6060f1SDimitry Andric           if (Last != 0) {
407fe6060f1SDimitry Andric             HasNewIndex = true;
408fe6060f1SDimitry Andric             break;
409fe6060f1SDimitry Andric           }
410fe6060f1SDimitry Andric         }
411fe6060f1SDimitry Andric         if (HasNewIndex || R[0].size() == 1)
412fe6060f1SDimitry Andric           continue;
413fe6060f1SDimitry Andric 
414fe6060f1SDimitry Andric         if (CS.isConditionImplied(R[0].Coefficients)) {
415e8d8bef9SDimitry Andric           if (!DebugCounter::shouldExecute(EliminatedCounter))
416e8d8bef9SDimitry Andric             continue;
417e8d8bef9SDimitry Andric 
418e8d8bef9SDimitry Andric           LLVM_DEBUG(dbgs() << "Condition " << *Cmp
419e8d8bef9SDimitry Andric                             << " implied by dominating constraints\n");
420e8d8bef9SDimitry Andric           LLVM_DEBUG({
421e8d8bef9SDimitry Andric             for (auto &E : reverse(DFSInStack))
422e8d8bef9SDimitry Andric               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
423e8d8bef9SDimitry Andric           });
424*349cc55cSDimitry Andric           Cmp->replaceUsesWithIf(
425*349cc55cSDimitry Andric               ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) {
426*349cc55cSDimitry Andric                 // Conditions in an assume trivially simplify to true. Skip uses
427*349cc55cSDimitry Andric                 // in assume calls to not destroy the available information.
428*349cc55cSDimitry Andric                 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
429*349cc55cSDimitry Andric                 return !II || II->getIntrinsicID() != Intrinsic::assume;
430*349cc55cSDimitry Andric               });
431e8d8bef9SDimitry Andric           NumCondsRemoved++;
432e8d8bef9SDimitry Andric           Changed = true;
433e8d8bef9SDimitry Andric         }
434fe6060f1SDimitry Andric         if (CS.isConditionImplied(
435fe6060f1SDimitry Andric                 ConstraintSystem::negate(R[0].Coefficients))) {
436e8d8bef9SDimitry Andric           if (!DebugCounter::shouldExecute(EliminatedCounter))
437e8d8bef9SDimitry Andric             continue;
438e8d8bef9SDimitry Andric 
439e8d8bef9SDimitry Andric           LLVM_DEBUG(dbgs() << "Condition !" << *Cmp
440e8d8bef9SDimitry Andric                             << " implied by dominating constraints\n");
441e8d8bef9SDimitry Andric           LLVM_DEBUG({
442e8d8bef9SDimitry Andric             for (auto &E : reverse(DFSInStack))
443e8d8bef9SDimitry Andric               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
444e8d8bef9SDimitry Andric           });
445e8d8bef9SDimitry Andric           Cmp->replaceAllUsesWith(
446e8d8bef9SDimitry Andric               ConstantInt::getFalse(F.getParent()->getContext()));
447e8d8bef9SDimitry Andric           NumCondsRemoved++;
448e8d8bef9SDimitry Andric           Changed = true;
449e8d8bef9SDimitry Andric         }
450e8d8bef9SDimitry Andric       }
451e8d8bef9SDimitry Andric       continue;
452e8d8bef9SDimitry Andric     }
453e8d8bef9SDimitry Andric 
454fe6060f1SDimitry Andric     // Set up a function to restore the predicate at the end of the scope if it
455fe6060f1SDimitry Andric     // has been negated. Negate the predicate in-place, if required.
456fe6060f1SDimitry Andric     auto *CI = dyn_cast<CmpInst>(CB.Condition);
457fe6060f1SDimitry Andric     auto PredicateRestorer = make_scope_exit([CI, &CB]() {
458fe6060f1SDimitry Andric       if (CB.Not && CI)
459fe6060f1SDimitry Andric         CI->setPredicate(CI->getInversePredicate());
460fe6060f1SDimitry Andric     });
461fe6060f1SDimitry Andric     if (CB.Not) {
462fe6060f1SDimitry Andric       if (CI) {
463fe6060f1SDimitry Andric         CI->setPredicate(CI->getInversePredicate());
464fe6060f1SDimitry Andric       } else {
465fe6060f1SDimitry Andric         LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n");
466fe6060f1SDimitry Andric         continue;
467fe6060f1SDimitry Andric       }
468fe6060f1SDimitry Andric     }
469fe6060f1SDimitry Andric 
470e8d8bef9SDimitry Andric     // Otherwise, add the condition to the system and stack, if we can transform
471e8d8bef9SDimitry Andric     // it into a constraint.
472fe6060f1SDimitry Andric     DenseMap<Value *, unsigned> NewIndices;
473fe6060f1SDimitry Andric     auto R = getConstraint(CB.Condition, Value2Index, NewIndices);
474e8d8bef9SDimitry Andric     if (R.empty())
475e8d8bef9SDimitry Andric       continue;
476e8d8bef9SDimitry Andric 
477fe6060f1SDimitry Andric     for (auto &KV : NewIndices)
478fe6060f1SDimitry Andric       Value2Index.insert(KV);
479e8d8bef9SDimitry Andric 
480fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Adding " << *CB.Condition << " " << CB.Not << "\n");
481fe6060f1SDimitry Andric     bool Added = false;
482fe6060f1SDimitry Andric     for (auto &C : R) {
483fe6060f1SDimitry Andric       auto Coeffs = C.Coefficients;
484fe6060f1SDimitry Andric       LLVM_DEBUG({
485fe6060f1SDimitry Andric         dbgs() << "  constraint: ";
486fe6060f1SDimitry Andric         dumpWithNames(C, Value2Index);
487fe6060f1SDimitry Andric       });
488fe6060f1SDimitry Andric       Added |= CS.addVariableRowFill(Coeffs);
489e8d8bef9SDimitry Andric       // If R has been added to the system, queue it for removal once it goes
490e8d8bef9SDimitry Andric       // out-of-scope.
491fe6060f1SDimitry Andric       if (Added)
492e8d8bef9SDimitry Andric         DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not);
493e8d8bef9SDimitry Andric     }
494fe6060f1SDimitry Andric   }
495e8d8bef9SDimitry Andric 
496fe6060f1SDimitry Andric   assert(CS.size() == DFSInStack.size() &&
497fe6060f1SDimitry Andric          "updates to CS and DFSInStack are out of sync");
498e8d8bef9SDimitry Andric   return Changed;
499e8d8bef9SDimitry Andric }
500e8d8bef9SDimitry Andric 
501e8d8bef9SDimitry Andric PreservedAnalyses ConstraintEliminationPass::run(Function &F,
502e8d8bef9SDimitry Andric                                                  FunctionAnalysisManager &AM) {
503e8d8bef9SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
504e8d8bef9SDimitry Andric   if (!eliminateConstraints(F, DT))
505e8d8bef9SDimitry Andric     return PreservedAnalyses::all();
506e8d8bef9SDimitry Andric 
507e8d8bef9SDimitry Andric   PreservedAnalyses PA;
508e8d8bef9SDimitry Andric   PA.preserve<DominatorTreeAnalysis>();
509e8d8bef9SDimitry Andric   PA.preserveSet<CFGAnalyses>();
510e8d8bef9SDimitry Andric   return PA;
511e8d8bef9SDimitry Andric }
512e8d8bef9SDimitry Andric 
513e8d8bef9SDimitry Andric namespace {
514e8d8bef9SDimitry Andric 
515e8d8bef9SDimitry Andric class ConstraintElimination : public FunctionPass {
516e8d8bef9SDimitry Andric public:
517e8d8bef9SDimitry Andric   static char ID;
518e8d8bef9SDimitry Andric 
519e8d8bef9SDimitry Andric   ConstraintElimination() : FunctionPass(ID) {
520e8d8bef9SDimitry Andric     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
521e8d8bef9SDimitry Andric   }
522e8d8bef9SDimitry Andric 
523e8d8bef9SDimitry Andric   bool runOnFunction(Function &F) override {
524e8d8bef9SDimitry Andric     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
525e8d8bef9SDimitry Andric     return eliminateConstraints(F, DT);
526e8d8bef9SDimitry Andric   }
527e8d8bef9SDimitry Andric 
528e8d8bef9SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
529e8d8bef9SDimitry Andric     AU.setPreservesCFG();
530e8d8bef9SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
531e8d8bef9SDimitry Andric     AU.addPreserved<GlobalsAAWrapperPass>();
532e8d8bef9SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
533e8d8bef9SDimitry Andric   }
534e8d8bef9SDimitry Andric };
535e8d8bef9SDimitry Andric 
536e8d8bef9SDimitry Andric } // end anonymous namespace
537e8d8bef9SDimitry Andric 
538e8d8bef9SDimitry Andric char ConstraintElimination::ID = 0;
539e8d8bef9SDimitry Andric 
540e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
541e8d8bef9SDimitry Andric                       "Constraint Elimination", false, false)
542e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
543e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
544e8d8bef9SDimitry Andric INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
545e8d8bef9SDimitry Andric                     "Constraint Elimination", false, false)
546e8d8bef9SDimitry Andric 
547e8d8bef9SDimitry Andric FunctionPass *llvm::createConstraintEliminationPass() {
548e8d8bef9SDimitry Andric   return new ConstraintElimination();
549e8d8bef9SDimitry Andric }
550