xref: /llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision ce190e41445eb52e560ac70dd1df74717a1e80d2)
1 //===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Eliminate conditions based on constraints collected from dominating
10 // conditions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/ConstraintSystem.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/InitializePasses.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/DebugCounter.h"
30 #include "llvm/Transforms/Scalar.h"
31 
32 using namespace llvm;
33 using namespace PatternMatch;
34 
35 #define DEBUG_TYPE "constraint-elimination"
36 
37 STATISTIC(NumCondsRemoved, "Number of instructions removed");
38 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
39               "Controls which conditions are eliminated");
40 
41 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
42 
43 // Decomposes \p V into a vector of pairs of the form { c, X } where c * X. The
44 // sum of the pairs equals \p V.  The first pair is the constant-factor and X
45 // must be nullptr. If the expression cannot be decomposed, returns an empty
46 // vector.
47 static SmallVector<std::pair<int64_t, Value *>, 4> decompose(Value *V) {
48   if (auto *CI = dyn_cast<ConstantInt>(V)) {
49     if (CI->isNegative() || CI->uge(MaxConstraintValue))
50       return {};
51     return {{CI->getSExtValue(), nullptr}};
52   }
53   auto *GEP = dyn_cast<GetElementPtrInst>(V);
54   if (GEP && GEP->getNumOperands() == 2) {
55     if (isa<ConstantInt>(GEP->getOperand(GEP->getNumOperands() - 1))) {
56       return {{cast<ConstantInt>(GEP->getOperand(GEP->getNumOperands() - 1))
57                    ->getSExtValue(),
58                nullptr},
59               {1, GEP->getPointerOperand()}};
60     }
61     Value *Op0;
62     ConstantInt *CI;
63     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
64               m_NUWShl(m_Value(Op0), m_ConstantInt(CI))))
65       return {{0, nullptr},
66               {1, GEP->getPointerOperand()},
67               {std::pow(int64_t(2), CI->getSExtValue()), Op0}};
68     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
69               m_ZExt(m_NUWShl(m_Value(Op0), m_ConstantInt(CI)))))
70       return {{0, nullptr},
71               {1, GEP->getPointerOperand()},
72               {std::pow(int64_t(2), CI->getSExtValue()), Op0}};
73 
74     return {{0, nullptr},
75             {1, GEP->getPointerOperand()},
76             {1, GEP->getOperand(GEP->getNumOperands() - 1)}};
77   }
78 
79   Value *Op0;
80   Value *Op1;
81   ConstantInt *CI;
82   if (match(V, m_NUWAdd(m_Value(Op0), m_ConstantInt(CI))))
83     return {{CI->getSExtValue(), nullptr}, {1, Op0}};
84   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1))))
85     return {{0, nullptr}, {1, Op0}, {1, Op1}};
86 
87   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))))
88     return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}};
89   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
90     return {{0, nullptr}, {1, Op0}, {1, Op1}};
91 
92   return {{0, nullptr}, {1, V}};
93 }
94 
95 /// Turn a condition \p CmpI into a constraint vector, using indices from \p
96 /// Value2Index. If \p ShouldAdd is true, new indices are added for values not
97 /// yet in \p Value2Index.
98 static SmallVector<int64_t, 8>
99 getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
100               DenseMap<Value *, unsigned> &Value2Index, bool ShouldAdd) {
101   int64_t Offset1 = 0;
102   int64_t Offset2 = 0;
103 
104   auto TryToGetIndex = [ShouldAdd,
105                         &Value2Index](Value *V) -> Optional<unsigned> {
106     if (ShouldAdd) {
107       Value2Index.insert({V, Value2Index.size() + 1});
108       return Value2Index[V];
109     }
110     auto I = Value2Index.find(V);
111     if (I == Value2Index.end())
112       return None;
113     return I->second;
114   };
115 
116   if (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE)
117     return getConstraint(CmpInst::getSwappedPredicate(Pred), Op1, Op0,
118                          Value2Index, ShouldAdd);
119 
120   // Only ULE and ULT predicates are supported at the moment.
121   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT)
122     return {};
123 
124   auto ADec = decompose(Op0);
125   auto BDec = decompose(Op1);
126   // Skip if decomposing either of the values failed.
127   if (ADec.empty() || BDec.empty())
128     return {};
129 
130   // Skip trivial constraints without any variables.
131   if (ADec.size() == 1 && BDec.size() == 1)
132     return {};
133 
134   Offset1 = ADec[0].first;
135   Offset2 = BDec[0].first;
136   Offset1 *= -1;
137 
138   // Create iterator ranges that skip the constant-factor.
139   auto VariablesA = make_range(std::next(ADec.begin()), ADec.end());
140   auto VariablesB = make_range(std::next(BDec.begin()), BDec.end());
141 
142   // Check if each referenced value in the constraint is already in the system
143   // or can be added (if ShouldAdd is true).
144   for (const auto &KV :
145        concat<std::pair<int64_t, Value *>>(VariablesA, VariablesB))
146     if (!TryToGetIndex(KV.second))
147       return {};
148 
149   // Build result constraint, by first adding all coefficients from A and then
150   // subtracting all coefficients from B.
151   SmallVector<int64_t, 8> R(Value2Index.size() + 1, 0);
152   for (const auto &KV : VariablesA)
153     R[Value2Index[KV.second]] += KV.first;
154 
155   for (const auto &KV : VariablesB)
156     R[Value2Index[KV.second]] -= KV.first;
157 
158   R[0] = Offset1 + Offset2 + (Pred == CmpInst::ICMP_ULT ? -1 : 0);
159   return R;
160 }
161 
162 static SmallVector<int64_t, 8>
163 getConstraint(CmpInst *Cmp, DenseMap<Value *, unsigned> &Value2Index,
164               bool ShouldAdd) {
165   return getConstraint(Cmp->getPredicate(), Cmp->getOperand(0),
166                        Cmp->getOperand(1), Value2Index, ShouldAdd);
167 }
168 
169 namespace {
170 /// Represents either a condition that holds on entry to a block or a basic
171 /// block, with their respective Dominator DFS in and out numbers.
172 struct ConstraintOrBlock {
173   unsigned NumIn;
174   unsigned NumOut;
175   bool IsBlock;
176   bool Not;
177   union {
178     BasicBlock *BB;
179     CmpInst *Condition;
180   };
181 
182   ConstraintOrBlock(DomTreeNode *DTN)
183       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
184         BB(DTN->getBlock()) {}
185   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
186       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
187         Not(Not), Condition(Condition) {}
188 };
189 
190 struct StackEntry {
191   unsigned NumIn;
192   unsigned NumOut;
193   CmpInst *Condition;
194   bool IsNot;
195 
196   StackEntry(unsigned NumIn, unsigned NumOut, CmpInst *Condition, bool IsNot)
197       : NumIn(NumIn), NumOut(NumOut), Condition(Condition), IsNot(IsNot) {}
198 };
199 } // namespace
200 
201 static bool eliminateConstraints(Function &F, DominatorTree &DT) {
202   bool Changed = false;
203   DT.updateDFSNumbers();
204   ConstraintSystem CS;
205 
206   SmallVector<ConstraintOrBlock, 64> WorkList;
207 
208   // First, collect conditions implied by branches and blocks with their
209   // Dominator DFS in and out numbers.
210   for (BasicBlock &BB : F) {
211     if (!DT.getNode(&BB))
212       continue;
213     WorkList.emplace_back(DT.getNode(&BB));
214 
215     auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
216     if (!Br || !Br->isConditional())
217       continue;
218 
219     // If the condition is an OR of 2 compares and the false successor only has
220     // the current block as predecessor, queue both negated conditions for the
221     // false successor.
222     Value *Op0, *Op1;
223     if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) &&
224         match(Op0, m_Cmp()) && match(Op1, m_Cmp())) {
225       BasicBlock *FalseSuccessor = Br->getSuccessor(1);
226       if (FalseSuccessor->getSinglePredecessor()) {
227         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<CmpInst>(Op0),
228                               true);
229         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<CmpInst>(Op1),
230                               true);
231       }
232       continue;
233     }
234 
235     // If the condition is an AND of 2 compares and the true successor only has
236     // the current block as predecessor, queue both conditions for the true
237     // successor.
238     if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) &&
239         match(Op0, m_Cmp()) && match(Op1, m_Cmp())) {
240       BasicBlock *TrueSuccessor = Br->getSuccessor(0);
241       if (TrueSuccessor->getSinglePredecessor()) {
242         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<CmpInst>(Op0),
243                               false);
244         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<CmpInst>(Op1),
245                               false);
246       }
247       continue;
248     }
249 
250     auto *CmpI = dyn_cast<CmpInst>(Br->getCondition());
251     if (!CmpI)
252       continue;
253     if (Br->getSuccessor(0)->getSinglePredecessor())
254       WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
255     if (Br->getSuccessor(1)->getSinglePredecessor())
256       WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
257   }
258 
259   // Next, sort worklist by dominance, so that dominating blocks and conditions
260   // come before blocks and conditions dominated by them. If a block and a
261   // condition have the same numbers, the condition comes before the block, as
262   // it holds on entry to the block.
263   sort(WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
264     return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock);
265   });
266 
267   // Finally, process ordered worklist and eliminate implied conditions.
268   SmallVector<StackEntry, 16> DFSInStack;
269   DenseMap<Value *, unsigned> Value2Index;
270   for (ConstraintOrBlock &CB : WorkList) {
271     // First, pop entries from the stack that are out-of-scope for CB. Remove
272     // the corresponding entry from the constraint system.
273     while (!DFSInStack.empty()) {
274       auto &E = DFSInStack.back();
275       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
276                         << "\n");
277       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
278       assert(E.NumIn <= CB.NumIn);
279       if (CB.NumOut <= E.NumOut)
280         break;
281       LLVM_DEBUG(dbgs() << "Removing " << *E.Condition << " " << E.IsNot
282                         << "\n");
283       DFSInStack.pop_back();
284       CS.popLastConstraint();
285     }
286 
287     LLVM_DEBUG({
288       dbgs() << "Processing ";
289       if (CB.IsBlock)
290         dbgs() << *CB.BB;
291       else
292         dbgs() << *CB.Condition;
293       dbgs() << "\n";
294     });
295 
296     // For a block, check if any CmpInsts become known based on the current set
297     // of constraints.
298     if (CB.IsBlock) {
299       for (Instruction &I : *CB.BB) {
300         auto *Cmp = dyn_cast<CmpInst>(&I);
301         if (!Cmp)
302           continue;
303         auto R = getConstraint(Cmp, Value2Index, false);
304         if (R.empty() || R.size() == 1)
305           continue;
306         if (CS.isConditionImplied(R)) {
307           if (!DebugCounter::shouldExecute(EliminatedCounter))
308             continue;
309 
310           LLVM_DEBUG(dbgs() << "Condition " << *Cmp
311                             << " implied by dominating constraints\n");
312           LLVM_DEBUG({
313             for (auto &E : reverse(DFSInStack))
314               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
315           });
316           Cmp->replaceAllUsesWith(
317               ConstantInt::getTrue(F.getParent()->getContext()));
318           NumCondsRemoved++;
319           Changed = true;
320         }
321         if (CS.isConditionImplied(ConstraintSystem::negate(R))) {
322           if (!DebugCounter::shouldExecute(EliminatedCounter))
323             continue;
324 
325           LLVM_DEBUG(dbgs() << "Condition !" << *Cmp
326                             << " implied by dominating constraints\n");
327           LLVM_DEBUG({
328             for (auto &E : reverse(DFSInStack))
329               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
330           });
331           Cmp->replaceAllUsesWith(
332               ConstantInt::getFalse(F.getParent()->getContext()));
333           NumCondsRemoved++;
334           Changed = true;
335         }
336       }
337       continue;
338     }
339 
340     // Set up a function to restore the predicate at the end of the scope if it
341     // has been negated. Negate the predicate in-place, if required.
342     auto *CI = dyn_cast<CmpInst>(CB.Condition);
343     auto PredicateRestorer = make_scope_exit([CI, &CB]() {
344       if (CB.Not && CI)
345         CI->setPredicate(CI->getInversePredicate());
346     });
347     if (CB.Not) {
348       if (CI) {
349         CI->setPredicate(CI->getInversePredicate());
350       } else {
351         LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n");
352         continue;
353       }
354     }
355 
356     // Otherwise, add the condition to the system and stack, if we can transform
357     // it into a constraint.
358     auto R = getConstraint(CB.Condition, Value2Index, true);
359     if (R.empty())
360       continue;
361 
362     LLVM_DEBUG(dbgs() << "Adding " << *CB.Condition << " " << CB.Not << "\n");
363 
364     // If R has been added to the system, queue it for removal once it goes
365     // out-of-scope.
366     if (CS.addVariableRowFill(R))
367       DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not);
368   }
369 
370   assert(CS.size() == DFSInStack.size() &&
371          "updates to CS and DFSInStack are out of sync");
372   return Changed;
373 }
374 
375 PreservedAnalyses ConstraintEliminationPass::run(Function &F,
376                                                  FunctionAnalysisManager &AM) {
377   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
378   if (!eliminateConstraints(F, DT))
379     return PreservedAnalyses::all();
380 
381   PreservedAnalyses PA;
382   PA.preserve<DominatorTreeAnalysis>();
383   PA.preserve<GlobalsAA>();
384   PA.preserveSet<CFGAnalyses>();
385   return PA;
386 }
387 
388 namespace {
389 
390 class ConstraintElimination : public FunctionPass {
391 public:
392   static char ID;
393 
394   ConstraintElimination() : FunctionPass(ID) {
395     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
396   }
397 
398   bool runOnFunction(Function &F) override {
399     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
400     return eliminateConstraints(F, DT);
401   }
402 
403   void getAnalysisUsage(AnalysisUsage &AU) const override {
404     AU.setPreservesCFG();
405     AU.addRequired<DominatorTreeWrapperPass>();
406     AU.addPreserved<GlobalsAAWrapperPass>();
407     AU.addPreserved<DominatorTreeWrapperPass>();
408   }
409 };
410 
411 } // end anonymous namespace
412 
413 char ConstraintElimination::ID = 0;
414 
415 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
416                       "Constraint Elimination", false, false)
417 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
418 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
419 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
420                     "Constraint Elimination", false, false)
421 
422 FunctionPass *llvm::createConstraintEliminationPass() {
423   return new ConstraintElimination();
424 }
425