blob: 4e42f336dc77a7c33ba18396183f19c818c6288c [file] [log] [blame]
Philip Reames89f22412018-03-20 17:09:21 +00001//===- MustExecute.cpp - Printer for isGuaranteedToExecute ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Philip Reamese4b728e2018-03-29 19:22:12 +000010#include "llvm/Analysis/MustExecute.h"
Philip Reames23aed5e2018-03-20 22:45:23 +000011#include "llvm/Analysis/InstructionSimplify.h"
Philip Reames89f22412018-03-20 17:09:21 +000012#include "llvm/Analysis/LoopInfo.h"
13#include "llvm/Analysis/Passes.h"
14#include "llvm/Analysis/ValueTracking.h"
Philip Reamesce998ad2018-03-20 18:43:44 +000015#include "llvm/IR/AssemblyAnnotationWriter.h"
Philip Reames89f22412018-03-20 17:09:21 +000016#include "llvm/IR/DataLayout.h"
17#include "llvm/IR/InstIterator.h"
18#include "llvm/IR/LLVMContext.h"
19#include "llvm/IR/Module.h"
20#include "llvm/Support/ErrorHandling.h"
Philip Reamesce998ad2018-03-20 18:43:44 +000021#include "llvm/Support/FormattedStream.h"
Philip Reames89f22412018-03-20 17:09:21 +000022#include "llvm/Support/raw_ostream.h"
Philip Reames89f22412018-03-20 17:09:21 +000023using namespace llvm;
24
Max Kazantsev8d56be72018-10-16 08:07:14 +000025const DenseMap<BasicBlock *, ColorVector> &
26LoopSafetyInfo::getBlockColors() const {
27 return BlockColors;
28}
29
30void LoopSafetyInfo::copyColors(BasicBlock *New, BasicBlock *Old) {
31 ColorVector &ColorsForNewBlock = BlockColors[New];
32 ColorVector &ColorsForOldBlock = BlockColors[Old];
33 ColorsForNewBlock = ColorsForOldBlock;
34}
35
Max Kazantsev9c90ec22018-10-16 08:31:05 +000036bool SimpleLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
Max Kazantsev6a4f5e22018-10-16 07:50:14 +000037 (void)BB;
38 return anyBlockMayThrow();
39}
40
Max Kazantsev9c90ec22018-10-16 08:31:05 +000041bool SimpleLoopSafetyInfo::anyBlockMayThrow() const {
Max Kazantsev530b8d12018-08-15 05:55:43 +000042 return MayThrow;
43}
44
Max Kazantsev9c90ec22018-10-16 08:31:05 +000045void SimpleLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
Shoaib Meenaia57d7132018-07-19 19:11:29 +000046 assert(CurLoop != nullptr && "CurLoop can't be null");
Philip Reames23aed5e2018-03-20 22:45:23 +000047 BasicBlock *Header = CurLoop->getHeader();
Philip Reames23aed5e2018-03-20 22:45:23 +000048 // Iterate over header and compute safety info.
Max Kazantsev530b8d12018-08-15 05:55:43 +000049 HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
50 MayThrow = HeaderMayThrow;
Philip Reames23aed5e2018-03-20 22:45:23 +000051 // Iterate over loop instructions and compute safety info.
52 // Skip header as it has been computed and stored in HeaderMayThrow.
53 // The first block in loopinfo.Blocks is guaranteed to be the header.
54 assert(Header == *CurLoop->getBlocks().begin() &&
55 "First block must be header");
56 for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
57 BBE = CurLoop->block_end();
Max Kazantsev530b8d12018-08-15 05:55:43 +000058 (BB != BBE) && !MayThrow; ++BB)
59 MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB);
Philip Reames23aed5e2018-03-20 22:45:23 +000060
Max Kazantsev8d56be72018-10-16 08:07:14 +000061 computeBlockColors(CurLoop);
62}
63
64void LoopSafetyInfo::computeBlockColors(const Loop *CurLoop) {
Philip Reames23aed5e2018-03-20 22:45:23 +000065 // Compute funclet colors if we might sink/hoist in a function with a funclet
66 // personality routine.
67 Function *Fn = CurLoop->getHeader()->getParent();
68 if (Fn->hasPersonalityFn())
69 if (Constant *PersonalityFn = Fn->getPersonalityFn())
Heejin Ahnb4be38f2018-05-17 20:52:03 +000070 if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
Max Kazantsev530b8d12018-08-15 05:55:43 +000071 BlockColors = colorEHFunclets(*Fn);
Philip Reames23aed5e2018-03-20 22:45:23 +000072}
73
74/// Return true if we can prove that the given ExitBlock is not reached on the
75/// first iteration of the given loop. That is, the backedge of the loop must
76/// be executed before the ExitBlock is executed in any dynamic execution trace.
Max Kazantseva7415872018-08-16 06:28:04 +000077static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
Philip Reames23aed5e2018-03-20 22:45:23 +000078 const DominatorTree *DT,
79 const Loop *CurLoop) {
80 auto *CondExitBlock = ExitBlock->getSinglePredecessor();
81 if (!CondExitBlock)
82 // expect unique exits
83 return false;
84 assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
85 auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
86 if (!BI || !BI->isConditional())
87 return false;
Serguei Katkov50958832018-05-18 04:56:28 +000088 // If condition is constant and false leads to ExitBlock then we always
89 // execute the true branch.
90 if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
91 return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
Philip Reames23aed5e2018-03-20 22:45:23 +000092 auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
93 if (!Cond)
94 return false;
95 // todo: this would be a lot more powerful if we used scev, but all the
96 // plumbing is currently missing to pass a pointer in from the pass
97 // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
98 auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
99 auto *RHS = Cond->getOperand(1);
100 if (!LHS || LHS->getParent() != CurLoop->getHeader())
101 return false;
102 auto DL = ExitBlock->getModule()->getDataLayout();
103 auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
104 auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
105 IVStart, RHS,
106 {DL, /*TLI*/ nullptr,
107 DT, /*AC*/ nullptr, BI});
108 auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
109 if (!SimpleCst)
110 return false;
111 if (ExitBlock == BI->getSuccessor(0))
112 return SimpleCst->isZeroValue();
113 assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
114 return SimpleCst->isAllOnesValue();
115}
116
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000117void LoopSafetyInfo::collectTransitivePredecessors(
118 const Loop *CurLoop, const BasicBlock *BB,
119 SmallPtrSetImpl<const BasicBlock *> &Predecessors) const {
120 assert(Predecessors.empty() && "Garbage in predecessors set?");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000121 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
Max Kazantsev7b78d392018-08-17 06:19:17 +0000122 if (BB == CurLoop->getHeader())
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000123 return;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000124 SmallVector<const BasicBlock *, 4> WorkList;
125 for (auto *Pred : predecessors(BB)) {
126 Predecessors.insert(Pred);
127 WorkList.push_back(Pred);
128 }
129 while (!WorkList.empty()) {
130 auto *Pred = WorkList.pop_back_val();
131 assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
132 // We are not interested in backedges and we don't want to leave loop.
133 if (Pred == CurLoop->getHeader())
134 continue;
135 // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
136 // blocks of this inner loop, even those that are always executed AFTER the
137 // BB. It may make our analysis more conservative than it could be, see test
138 // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
139 // We can ignore backedge of all loops containing BB to get a sligtly more
140 // optimistic result.
141 for (auto *PredPred : predecessors(Pred))
142 if (Predecessors.insert(PredPred).second)
143 WorkList.push_back(PredPred);
144 }
Max Kazantsevbfbd4d12018-08-21 07:15:06 +0000145}
146
147bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop,
148 const BasicBlock *BB,
149 const DominatorTree *DT) const {
150 assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
151
152 // Fast path: header is always reached once the loop is entered.
153 if (BB == CurLoop->getHeader())
154 return true;
155
156 // Collect all transitive predecessors of BB in the same loop. This set will
157 // be a subset of the blocks within the loop.
158 SmallPtrSet<const BasicBlock *, 4> Predecessors;
159 collectTransitivePredecessors(CurLoop, BB, Predecessors);
Max Kazantsev7b78d392018-08-17 06:19:17 +0000160
161 // Make sure that all successors of all predecessors of BB are either:
162 // 1) BB,
163 // 2) Also predecessors of BB,
164 // 3) Exit blocks which are not taken on 1st iteration.
165 // Memoize blocks we've already checked.
166 SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000167 for (auto *Pred : Predecessors) {
168 // Predecessor block may throw, so it has a side exit.
169 if (blockMayThrow(Pred))
170 return false;
Max Kazantsev7b78d392018-08-17 06:19:17 +0000171 for (auto *Succ : successors(Pred))
172 if (CheckedSuccessors.insert(Succ).second &&
173 Succ != BB && !Predecessors.count(Succ))
174 // By discharging conditions that are not executed on the 1st iteration,
175 // we guarantee that *at least* on the first iteration all paths from
176 // header that *may* execute will lead us to the block of interest. So
177 // that if we had virtually peeled one iteration away, in this peeled
178 // iteration the set of predecessors would contain only paths from
179 // header to BB without any exiting edges that may execute.
180 //
181 // TODO: We only do it for exiting edges currently. We could use the
182 // same function to skip some of the edges within the loop if we know
183 // that they will not be taken on the 1st iteration.
184 //
185 // TODO: If we somehow know the number of iterations in loop, the same
186 // check may be done for any arbitrary N-th iteration as long as N is
187 // not greater than minimum number of iterations in this loop.
188 if (CurLoop->contains(Succ) ||
189 !CanProveNotTakenFirstIteration(Succ, DT, CurLoop))
190 return false;
Max Kazantsev6a4f5e22018-10-16 07:50:14 +0000191 }
Max Kazantsev7b78d392018-08-17 06:19:17 +0000192
193 // All predecessors can only lead us to BB.
194 return true;
195}
196
Philip Reames23aed5e2018-03-20 22:45:23 +0000197/// Returns true if the instruction in a loop is guaranteed to execute at least
198/// once.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000199bool SimpleLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
200 const DominatorTree *DT,
201 const Loop *CurLoop) const {
Philip Reames23aed5e2018-03-20 22:45:23 +0000202 // If the instruction is in the header block for the loop (which is very
203 // common), it is always guaranteed to dominate the exit blocks. Since this
204 // is a common case, and can save some work, check it now.
205 if (Inst.getParent() == CurLoop->getHeader())
206 // If there's a throw in the header block, we can't guarantee we'll reach
Philip Reamese4ec4732018-04-27 20:44:01 +0000207 // Inst unless we can prove that Inst comes before the potential implicit
208 // exit. At the moment, we use a (cheap) hack for the common case where
209 // the instruction of interest is the first one in the block.
Max Kazantsev87de55a2018-10-16 09:11:25 +0000210 return !HeaderMayThrow ||
Max Kazantsevc8466f92018-10-16 06:34:53 +0000211 Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
Philip Reames23aed5e2018-03-20 22:45:23 +0000212
Max Kazantsev7b78d392018-08-17 06:19:17 +0000213 // If there is a path from header to exit or latch that doesn't lead to our
214 // instruction's block, return false.
Max Kazantsev87de55a2018-10-16 09:11:25 +0000215 return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
Philip Reames23aed5e2018-03-20 22:45:23 +0000216}
217
218
Philip Reames89f22412018-03-20 17:09:21 +0000219namespace {
220 struct MustExecutePrinter : public FunctionPass {
Philip Reames89f22412018-03-20 17:09:21 +0000221
222 static char ID; // Pass identification, replacement for typeid
223 MustExecutePrinter() : FunctionPass(ID) {
224 initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
225 }
226 void getAnalysisUsage(AnalysisUsage &AU) const override {
227 AU.setPreservesAll();
228 AU.addRequired<DominatorTreeWrapperPass>();
229 AU.addRequired<LoopInfoWrapperPass>();
230 }
231 bool runOnFunction(Function &F) override;
Philip Reames89f22412018-03-20 17:09:21 +0000232 };
233}
234
235char MustExecutePrinter::ID = 0;
236INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
237 "Instructions which execute on loop entry", false, true)
238INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
239INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
240INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
241 "Instructions which execute on loop entry", false, true)
242
243FunctionPass *llvm::createMustExecutePrinter() {
244 return new MustExecutePrinter();
245}
246
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000247static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
Philip Reames37a1a292018-03-20 23:00:54 +0000248 // TODO: merge these two routines. For the moment, we display the best
249 // result obtained by *either* implementation. This is a bit unfair since no
250 // caller actually gets the full power at the moment.
Max Kazantsev9c90ec22018-10-16 08:31:05 +0000251 SimpleLoopSafetyInfo LSI;
Max Kazantsev530b8d12018-08-15 05:55:43 +0000252 LSI.computeLoopSafetyInfo(L);
Max Kazantsevc8466f92018-10-16 06:34:53 +0000253 return LSI.isGuaranteedToExecute(I, DT, L) ||
Philip Reames37a1a292018-03-20 23:00:54 +0000254 isGuaranteedToExecuteForEveryIteration(&I, L);
Philip Reames89f22412018-03-20 17:09:21 +0000255}
256
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000257namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000258/// An assembly annotator class to print must execute information in
Philip Reamesce998ad2018-03-20 18:43:44 +0000259/// comments.
260class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
261 DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
Philip Reames89f22412018-03-20 17:09:21 +0000262
Philip Reamesce998ad2018-03-20 18:43:44 +0000263public:
264 MustExecuteAnnotatedWriter(const Function &F,
265 DominatorTree &DT, LoopInfo &LI) {
266 for (auto &I: instructions(F)) {
267 Loop *L = LI.getLoopFor(I.getParent());
268 while (L) {
269 if (isMustExecuteIn(I, L, &DT)) {
270 MustExec[&I].push_back(L);
271 }
272 L = L->getParentLoop();
273 };
274 }
275 }
276 MustExecuteAnnotatedWriter(const Module &M,
277 DominatorTree &DT, LoopInfo &LI) {
278 for (auto &F : M)
279 for (auto &I: instructions(F)) {
280 Loop *L = LI.getLoopFor(I.getParent());
281 while (L) {
282 if (isMustExecuteIn(I, L, &DT)) {
283 MustExec[&I].push_back(L);
284 }
285 L = L->getParentLoop();
286 };
287 }
288 }
289
290
Fangrui Songf78650a2018-07-30 19:41:25 +0000291 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
Philip Reamesce998ad2018-03-20 18:43:44 +0000292 if (!MustExec.count(&V))
293 return;
294
295 const auto &Loops = MustExec.lookup(&V);
296 const auto NumLoops = Loops.size();
Philip Reames89f22412018-03-20 17:09:21 +0000297 if (NumLoops > 1)
Philip Reamesce998ad2018-03-20 18:43:44 +0000298 OS << " ; (mustexec in " << NumLoops << " loops: ";
Philip Reames89f22412018-03-20 17:09:21 +0000299 else
Philip Reamesce998ad2018-03-20 18:43:44 +0000300 OS << " ; (mustexec in: ";
Fangrui Songf78650a2018-07-30 19:41:25 +0000301
Philip Reames89f22412018-03-20 17:09:21 +0000302 bool first = true;
Philip Reamesce998ad2018-03-20 18:43:44 +0000303 for (const Loop *L : Loops) {
Philip Reames89f22412018-03-20 17:09:21 +0000304 if (!first)
305 OS << ", ";
306 first = false;
307 OS << L->getHeader()->getName();
308 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000309 OS << ")";
Philip Reames89f22412018-03-20 17:09:21 +0000310 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000311};
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000312} // namespace
Philip Reamesce998ad2018-03-20 18:43:44 +0000313
314bool MustExecutePrinter::runOnFunction(Function &F) {
315 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
316 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
317
318 MustExecuteAnnotatedWriter Writer(F, DT, LI);
319 F.print(dbgs(), &Writer);
Fangrui Songf78650a2018-07-30 19:41:25 +0000320
Philip Reamesce998ad2018-03-20 18:43:44 +0000321 return false;
Philip Reames89f22412018-03-20 17:09:21 +0000322}