blob: d8bc7fa19ae5cc53cb5194e17595c7a8d5e8d5c2 [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
Philip Reames23aed5e2018-03-20 22:45:23 +000025/// Computes loop safety information, checks loop body & header
26/// for the possibility of may throw exception.
27///
28void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
29 assert(CurLoop != nullptr && "CurLoop cant be null");
30 BasicBlock *Header = CurLoop->getHeader();
31 // Setting default safety values.
32 SafetyInfo->MayThrow = false;
33 SafetyInfo->HeaderMayThrow = false;
34 // Iterate over header and compute safety info.
35 SafetyInfo->HeaderMayThrow =
36 !isGuaranteedToTransferExecutionToSuccessor(Header);
37
38 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
39 // Iterate over loop instructions and compute safety info.
40 // Skip header as it has been computed and stored in HeaderMayThrow.
41 // The first block in loopinfo.Blocks is guaranteed to be the header.
42 assert(Header == *CurLoop->getBlocks().begin() &&
43 "First block must be header");
44 for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
45 BBE = CurLoop->block_end();
46 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
47 SafetyInfo->MayThrow |=
48 !isGuaranteedToTransferExecutionToSuccessor(*BB);
49
50 // Compute funclet colors if we might sink/hoist in a function with a funclet
51 // personality routine.
52 Function *Fn = CurLoop->getHeader()->getParent();
53 if (Fn->hasPersonalityFn())
54 if (Constant *PersonalityFn = Fn->getPersonalityFn())
Heejin Ahnb4be38f2018-05-17 20:52:03 +000055 if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
Philip Reames23aed5e2018-03-20 22:45:23 +000056 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
57}
58
59/// Return true if we can prove that the given ExitBlock is not reached on the
60/// first iteration of the given loop. That is, the backedge of the loop must
61/// be executed before the ExitBlock is executed in any dynamic execution trace.
62static bool CanProveNotTakenFirstIteration(BasicBlock *ExitBlock,
63 const DominatorTree *DT,
64 const Loop *CurLoop) {
65 auto *CondExitBlock = ExitBlock->getSinglePredecessor();
66 if (!CondExitBlock)
67 // expect unique exits
68 return false;
69 assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
70 auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
71 if (!BI || !BI->isConditional())
72 return false;
73 auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
74 if (!Cond)
75 return false;
76 // todo: this would be a lot more powerful if we used scev, but all the
77 // plumbing is currently missing to pass a pointer in from the pass
78 // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
79 auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
80 auto *RHS = Cond->getOperand(1);
81 if (!LHS || LHS->getParent() != CurLoop->getHeader())
82 return false;
83 auto DL = ExitBlock->getModule()->getDataLayout();
84 auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
85 auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
86 IVStart, RHS,
87 {DL, /*TLI*/ nullptr,
88 DT, /*AC*/ nullptr, BI});
89 auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
90 if (!SimpleCst)
91 return false;
92 if (ExitBlock == BI->getSuccessor(0))
93 return SimpleCst->isZeroValue();
94 assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
95 return SimpleCst->isAllOnesValue();
96}
97
98/// Returns true if the instruction in a loop is guaranteed to execute at least
99/// once.
100bool llvm::isGuaranteedToExecute(const Instruction &Inst,
101 const DominatorTree *DT, const Loop *CurLoop,
102 const LoopSafetyInfo *SafetyInfo) {
103 // We have to check to make sure that the instruction dominates all
104 // of the exit blocks. If it doesn't, then there is a path out of the loop
105 // which does not execute this instruction, so we can't hoist it.
106
107 // If the instruction is in the header block for the loop (which is very
108 // common), it is always guaranteed to dominate the exit blocks. Since this
109 // is a common case, and can save some work, check it now.
110 if (Inst.getParent() == CurLoop->getHeader())
111 // If there's a throw in the header block, we can't guarantee we'll reach
Philip Reamese4ec4732018-04-27 20:44:01 +0000112 // Inst unless we can prove that Inst comes before the potential implicit
113 // exit. At the moment, we use a (cheap) hack for the common case where
114 // the instruction of interest is the first one in the block.
115 return !SafetyInfo->HeaderMayThrow ||
116 Inst.getParent()->getFirstNonPHI() == &Inst;
Philip Reames23aed5e2018-03-20 22:45:23 +0000117
118 // Somewhere in this loop there is an instruction which may throw and make us
119 // exit the loop.
120 if (SafetyInfo->MayThrow)
121 return false;
122
123 // Note: There are two styles of reasoning intermixed below for
124 // implementation efficiency reasons. They are:
125 // 1) If we can prove that the instruction dominates all exit blocks, then we
126 // know the instruction must have executed on *some* iteration before we
127 // exit. We do not prove *which* iteration the instruction must execute on.
128 // 2) If we can prove that the instruction dominates the latch and all exits
129 // which might be taken on the first iteration, we know the instruction must
130 // execute on the first iteration. This second style allows a conditional
131 // exit before the instruction of interest which is provably not taken on the
132 // first iteration. This is a quite common case for range check like
133 // patterns. TODO: support loops with multiple latches.
134
135 const bool InstDominatesLatch =
136 CurLoop->getLoopLatch() != nullptr &&
137 DT->dominates(Inst.getParent(), CurLoop->getLoopLatch());
138
139 // Get the exit blocks for the current loop.
140 SmallVector<BasicBlock *, 8> ExitBlocks;
141 CurLoop->getExitBlocks(ExitBlocks);
142
143 // Verify that the block dominates each of the exit blocks of the loop.
144 for (BasicBlock *ExitBlock : ExitBlocks)
145 if (!DT->dominates(Inst.getParent(), ExitBlock))
146 if (!InstDominatesLatch ||
147 !CanProveNotTakenFirstIteration(ExitBlock, DT, CurLoop))
148 return false;
149
150 // As a degenerate case, if the loop is statically infinite then we haven't
151 // proven anything since there are no exit blocks.
152 if (ExitBlocks.empty())
153 return false;
154
155 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
156 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
157 // just a special case of this.)
158 return true;
159}
160
161
Philip Reames89f22412018-03-20 17:09:21 +0000162namespace {
163 struct MustExecutePrinter : public FunctionPass {
Philip Reames89f22412018-03-20 17:09:21 +0000164
165 static char ID; // Pass identification, replacement for typeid
166 MustExecutePrinter() : FunctionPass(ID) {
167 initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
168 }
169 void getAnalysisUsage(AnalysisUsage &AU) const override {
170 AU.setPreservesAll();
171 AU.addRequired<DominatorTreeWrapperPass>();
172 AU.addRequired<LoopInfoWrapperPass>();
173 }
174 bool runOnFunction(Function &F) override;
Philip Reames89f22412018-03-20 17:09:21 +0000175 };
176}
177
178char MustExecutePrinter::ID = 0;
179INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
180 "Instructions which execute on loop entry", false, true)
181INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
182INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
183INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
184 "Instructions which execute on loop entry", false, true)
185
186FunctionPass *llvm::createMustExecutePrinter() {
187 return new MustExecutePrinter();
188}
189
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000190static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
Philip Reames37a1a292018-03-20 23:00:54 +0000191 // TODO: merge these two routines. For the moment, we display the best
192 // result obtained by *either* implementation. This is a bit unfair since no
193 // caller actually gets the full power at the moment.
194 LoopSafetyInfo LSI;
195 computeLoopSafetyInfo(&LSI, L);
196 return isGuaranteedToExecute(I, DT, L, &LSI) ||
197 isGuaranteedToExecuteForEveryIteration(&I, L);
Philip Reames89f22412018-03-20 17:09:21 +0000198}
199
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000200namespace {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000201/// An assembly annotator class to print must execute information in
Philip Reamesce998ad2018-03-20 18:43:44 +0000202/// comments.
203class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
204 DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
Philip Reames89f22412018-03-20 17:09:21 +0000205
Philip Reamesce998ad2018-03-20 18:43:44 +0000206public:
207 MustExecuteAnnotatedWriter(const Function &F,
208 DominatorTree &DT, LoopInfo &LI) {
209 for (auto &I: instructions(F)) {
210 Loop *L = LI.getLoopFor(I.getParent());
211 while (L) {
212 if (isMustExecuteIn(I, L, &DT)) {
213 MustExec[&I].push_back(L);
214 }
215 L = L->getParentLoop();
216 };
217 }
218 }
219 MustExecuteAnnotatedWriter(const Module &M,
220 DominatorTree &DT, LoopInfo &LI) {
221 for (auto &F : M)
222 for (auto &I: instructions(F)) {
223 Loop *L = LI.getLoopFor(I.getParent());
224 while (L) {
225 if (isMustExecuteIn(I, L, &DT)) {
226 MustExec[&I].push_back(L);
227 }
228 L = L->getParentLoop();
229 };
230 }
231 }
232
233
234 void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
235 if (!MustExec.count(&V))
236 return;
237
238 const auto &Loops = MustExec.lookup(&V);
239 const auto NumLoops = Loops.size();
Philip Reames89f22412018-03-20 17:09:21 +0000240 if (NumLoops > 1)
Philip Reamesce998ad2018-03-20 18:43:44 +0000241 OS << " ; (mustexec in " << NumLoops << " loops: ";
Philip Reames89f22412018-03-20 17:09:21 +0000242 else
Philip Reamesce998ad2018-03-20 18:43:44 +0000243 OS << " ; (mustexec in: ";
Philip Reames89f22412018-03-20 17:09:21 +0000244
245 bool first = true;
Philip Reamesce998ad2018-03-20 18:43:44 +0000246 for (const Loop *L : Loops) {
Philip Reames89f22412018-03-20 17:09:21 +0000247 if (!first)
248 OS << ", ";
249 first = false;
250 OS << L->getHeader()->getName();
251 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000252 OS << ")";
Philip Reames89f22412018-03-20 17:09:21 +0000253 }
Philip Reamesce998ad2018-03-20 18:43:44 +0000254};
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000255} // namespace
Philip Reamesce998ad2018-03-20 18:43:44 +0000256
257bool MustExecutePrinter::runOnFunction(Function &F) {
258 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
259 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
260
261 MustExecuteAnnotatedWriter Writer(F, DT, LI);
262 F.print(dbgs(), &Writer);
263
264 return false;
Philip Reames89f22412018-03-20 17:09:21 +0000265}