1 //===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements LoopPass and LPPassManager. All loop optimization
11 // and transformation passes are derived from LoopPass. LPPassManager is
12 // responsible for managing LoopPasses.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Analysis/LoopPass.h"
17 #include "llvm/IR/IRPrintingPasses.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/Timer.h"
23 #define DEBUG_TYPE "loop-pass-manager"
27 /// PrintLoopPass - Print a Function corresponding to a Loop.
29 class PrintLoopPass : public LoopPass {
32 raw_ostream &Out; // raw_ostream to print on.
36 PrintLoopPass(const std::string &B, raw_ostream &o)
37 : LoopPass(ID), Banner(B), Out(o) {}
39 void getAnalysisUsage(AnalysisUsage &AU) const override {
43 bool runOnLoop(Loop *L, LPPassManager &) override {
45 for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
54 char PrintLoopPass::ID = 0;
57 //===----------------------------------------------------------------------===//
61 char LPPassManager::ID = 0;
63 LPPassManager::LPPassManager()
64 : FunctionPass(ID), PMDataManager() {
68 CurrentLoop = nullptr;
71 /// Delete loop from the loop queue and loop hierarchy (LoopInfo).
72 void LPPassManager::deleteLoopFromQueue(Loop *L) {
76 // If L is current loop then skip rest of the passes and let
77 // runOnFunction remove L from LQ. Otherwise, remove L from LQ now
78 // and continue applying other passes on CurrentLoop.
87 for (std::deque<Loop *>::iterator I = LQ.begin(),
88 E = LQ.end(); I != E; ++I) {
96 // Inset loop into loop nest (LoopInfo) and loop queue (LQ).
97 void LPPassManager::insertLoop(Loop *L, Loop *ParentLoop) {
99 assert (CurrentLoop != L && "Cannot insert CurrentLoop");
101 // Insert into loop nest
103 ParentLoop->addChildLoop(L);
105 LI->addTopLevelLoop(L);
107 insertLoopIntoQueue(L);
110 void LPPassManager::insertLoopIntoQueue(Loop *L) {
111 // Insert L into loop queue
112 if (L == CurrentLoop)
114 else if (!L->getParentLoop())
115 // This is top level loop.
118 // Insert L after the parent loop.
119 for (std::deque<Loop *>::iterator I = LQ.begin(),
120 E = LQ.end(); I != E; ++I) {
121 if (*I == L->getParentLoop()) {
122 // deque does not support insert after.
131 // Reoptimize this loop. LPPassManager will re-insert this loop into the
132 // queue. This allows LoopPass to change loop nest for the loop. This
133 // utility may send LPPassManager into infinite loops so use caution.
134 void LPPassManager::redoLoop(Loop *L) {
135 assert (CurrentLoop == L && "Can redo only CurrentLoop");
139 /// cloneBasicBlockSimpleAnalysis - Invoke cloneBasicBlockAnalysis hook for
141 void LPPassManager::cloneBasicBlockSimpleAnalysis(BasicBlock *From,
142 BasicBlock *To, Loop *L) {
143 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
144 LoopPass *LP = getContainedPass(Index);
145 LP->cloneBasicBlockAnalysis(From, To, L);
149 /// deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes.
150 void LPPassManager::deleteSimpleAnalysisValue(Value *V, Loop *L) {
151 if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
152 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;
154 Instruction &I = *BI;
155 deleteSimpleAnalysisValue(&I, L);
158 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
159 LoopPass *LP = getContainedPass(Index);
160 LP->deleteAnalysisValue(V, L);
165 // Recurse through all subloops and all loops into LQ.
166 static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
168 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I)
169 addLoopIntoQueue(*I, LQ);
172 /// Pass Manager itself does not invalidate any analysis info.
173 void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
174 // LPPassManager needs LoopInfo. In the long term LoopInfo class will
175 // become part of LPPassManager.
176 Info.addRequired<LoopInfo>();
177 Info.setPreservesAll();
180 /// run - Execute all of the passes scheduled for execution. Keep track of
181 /// whether any of the passes modifies the function, and if so, return true.
182 bool LPPassManager::runOnFunction(Function &F) {
183 LI = &getAnalysis<LoopInfo>();
184 bool Changed = false;
186 // Collect inherited analysis from Module level pass manager.
187 populateInheritedAnalysis(TPM->activeStack);
189 // Populate the loop queue in reverse program order. There is no clear need to
190 // process sibling loops in either forward or reverse order. There may be some
191 // advantage in deleting uses in a later loop before optimizing the
192 // definitions in an earlier loop. If we find a clear reason to process in
193 // forward order, then a forward variant of LoopPassManager should be created.
195 // Note that LoopInfo::iterator visits loops in reverse program
196 // order. Here, reverse_iterator gives us a forward order, and the LoopQueue
197 // reverses the order a third time by popping from the back.
198 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
199 addLoopIntoQueue(*I, LQ);
201 if (LQ.empty()) // No loops, skip calling finalizers
205 for (std::deque<Loop *>::const_iterator I = LQ.begin(), E = LQ.end();
208 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
209 LoopPass *P = getContainedPass(Index);
210 Changed |= P->doInitialization(L, *this);
215 while (!LQ.empty()) {
217 CurrentLoop = LQ.back();
218 skipThisLoop = false;
219 redoThisLoop = false;
221 // Run all passes on the current Loop.
222 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
223 LoopPass *P = getContainedPass(Index);
225 dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
226 CurrentLoop->getHeader()->getName());
229 initializeAnalysisImpl(P);
232 PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
233 TimeRegion PassTimer(getPassTimer(P));
235 Changed |= P->runOnLoop(CurrentLoop, *this);
239 dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
240 skipThisLoop ? "<deleted>" :
241 CurrentLoop->getHeader()->getName());
245 // Manually check that this loop is still healthy. This is done
246 // instead of relying on LoopInfo::verifyLoop since LoopInfo
247 // is a function pass and it's really expensive to verify every
248 // loop in the function every time. That level of checking can be
249 // enabled with the -verify-loop-info option.
251 TimeRegion PassTimer(getPassTimer(LI));
252 CurrentLoop->verifyLoop();
255 // Then call the regular verifyAnalysis functions.
256 verifyPreservedAnalysis(P);
258 F.getContext().yield();
261 removeNotPreservedAnalysis(P);
262 recordAvailableAnalysis(P);
264 skipThisLoop ? "<deleted>" :
265 CurrentLoop->getHeader()->getName(),
269 // Do not run other passes on this loop.
273 // If the loop was deleted, release all the loop passes. This frees up
274 // some memory, and avoids trouble with the pass manager trying to call
275 // verifyAnalysis on them.
277 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
278 Pass *P = getContainedPass(Index);
279 freePass(P, "<deleted>", ON_LOOP_MSG);
282 // Pop the loop from queue after running all passes.
286 LQ.push_back(CurrentLoop);
290 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
291 LoopPass *P = getContainedPass(Index);
292 Changed |= P->doFinalization();
298 /// Print passes managed by this manager
299 void LPPassManager::dumpPassStructure(unsigned Offset) {
300 errs().indent(Offset*2) << "Loop Pass Manager\n";
301 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
302 Pass *P = getContainedPass(Index);
303 P->dumpPassStructure(Offset + 1);
304 dumpLastUses(P, Offset+1);
309 //===----------------------------------------------------------------------===//
312 Pass *LoopPass::createPrinterPass(raw_ostream &O,
313 const std::string &Banner) const {
314 return new PrintLoopPass(Banner, O);
317 // Check if this pass is suitable for the current LPPassManager, if
318 // available. This pass P is not suitable for a LPPassManager if P
319 // is not preserving higher level analysis info used by other
320 // LPPassManager passes. In such case, pop LPPassManager from the
321 // stack. This will force assignPassManager() to create new
322 // LPPassManger as expected.
323 void LoopPass::preparePassManager(PMStack &PMS) {
325 // Find LPPassManager
326 while (!PMS.empty() &&
327 PMS.top()->getPassManagerType() > PMT_LoopPassManager)
330 // If this pass is destroying high level information that is used
331 // by other passes that are managed by LPM then do not insert
332 // this pass in current LPM. Use new LPPassManager.
333 if (PMS.top()->getPassManagerType() == PMT_LoopPassManager &&
334 !PMS.top()->preserveHigherLevelAnalysis(this))
338 /// Assign pass manager to manage this pass.
339 void LoopPass::assignPassManager(PMStack &PMS,
340 PassManagerType PreferredType) {
341 // Find LPPassManager
342 while (!PMS.empty() &&
343 PMS.top()->getPassManagerType() > PMT_LoopPassManager)
347 if (PMS.top()->getPassManagerType() == PMT_LoopPassManager)
348 LPPM = (LPPassManager*)PMS.top();
350 // Create new Loop Pass Manager if it does not exist.
351 assert (!PMS.empty() && "Unable to create Loop Pass Manager");
352 PMDataManager *PMD = PMS.top();
354 // [1] Create new Loop Pass Manager
355 LPPM = new LPPassManager();
356 LPPM->populateInheritedAnalysis(PMS);
358 // [2] Set up new manager's top level manager
359 PMTopLevelManager *TPM = PMD->getTopLevelManager();
360 TPM->addIndirectPassManager(LPPM);
362 // [3] Assign manager to manage this new manager. This may create
363 // and push new managers into PMS
364 Pass *P = LPPM->getAsPass();
365 TPM->schedulePass(P);
367 // [4] Push new manager into PMS
374 // Containing function has Attribute::OptimizeNone and transformation
375 // passes should skip it.
376 bool LoopPass::skipOptnoneFunction(const Loop *L) const {
377 const Function *F = L->getHeader()->getParent();
378 if (F && F->hasFnAttribute(Attribute::OptimizeNone)) {
379 // FIXME: Report this to dbgs() only once per function.
380 DEBUG(dbgs() << "Skipping pass '" << getPassName()
381 << "' in function " << F->getName() << "\n");
382 // FIXME: Delete loop from pass manager's queue?