xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/LoopPass.cpp (revision fe815331bb40604ba31312acf7e4619674631777)
1 //===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===//
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 // This file implements LoopPass and LPPassManager. All loop optimization
10 // and transformation passes are derived from LoopPass. LPPassManager is
11 // responsible for managing LoopPasses.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/LoopPass.h"
16 #include "llvm/Analysis/LoopAnalysisManager.h"
17 #include "llvm/IR/Dominators.h"
18 #include "llvm/IR/IRPrintingPasses.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/OptBisect.h"
21 #include "llvm/IR/PassManager.h"
22 #include "llvm/IR/PassTimingInfo.h"
23 #include "llvm/InitializePasses.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/TimeProfiler.h"
26 #include "llvm/Support/Timer.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "loop-pass-manager"
31 
32 namespace {
33 
34 /// PrintLoopPass - Print a Function corresponding to a Loop.
35 ///
36 class PrintLoopPassWrapper : public LoopPass {
37   raw_ostream &OS;
38   std::string Banner;
39 
40 public:
41   static char ID;
42   PrintLoopPassWrapper() : LoopPass(ID), OS(dbgs()) {}
43   PrintLoopPassWrapper(raw_ostream &OS, const std::string &Banner)
44       : LoopPass(ID), OS(OS), Banner(Banner) {}
45 
46   void getAnalysisUsage(AnalysisUsage &AU) const override {
47     AU.setPreservesAll();
48   }
49 
50   bool runOnLoop(Loop *L, LPPassManager &) override {
51     auto BBI = llvm::find_if(L->blocks(), [](BasicBlock *BB) { return BB; });
52     if (BBI != L->blocks().end() &&
53         isFunctionInPrintList((*BBI)->getParent()->getName())) {
54       printLoop(*L, OS, Banner);
55     }
56     return false;
57   }
58 
59   StringRef getPassName() const override { return "Print Loop IR"; }
60 };
61 
62 char PrintLoopPassWrapper::ID = 0;
63 }
64 
65 //===----------------------------------------------------------------------===//
66 // LPPassManager
67 //
68 
69 char LPPassManager::ID = 0;
70 
71 LPPassManager::LPPassManager()
72   : FunctionPass(ID), PMDataManager() {
73   LI = nullptr;
74   CurrentLoop = nullptr;
75 }
76 
77 // Insert loop into loop nest (LoopInfo) and loop queue (LQ).
78 void LPPassManager::addLoop(Loop &L) {
79   if (!L.getParentLoop()) {
80     // This is the top level loop.
81     LQ.push_front(&L);
82     return;
83   }
84 
85   // Insert L into the loop queue after the parent loop.
86   for (auto I = LQ.begin(), E = LQ.end(); I != E; ++I) {
87     if (*I == L.getParentLoop()) {
88       // deque does not support insert after.
89       ++I;
90       LQ.insert(I, 1, &L);
91       return;
92     }
93   }
94 }
95 
96 // Recurse through all subloops and all loops  into LQ.
97 static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
98   LQ.push_back(L);
99   for (Loop *I : reverse(*L))
100     addLoopIntoQueue(I, LQ);
101 }
102 
103 /// Pass Manager itself does not invalidate any analysis info.
104 void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
105   // LPPassManager needs LoopInfo. In the long term LoopInfo class will
106   // become part of LPPassManager.
107   Info.addRequired<LoopInfoWrapperPass>();
108   Info.addRequired<DominatorTreeWrapperPass>();
109   Info.setPreservesAll();
110 }
111 
112 void LPPassManager::markLoopAsDeleted(Loop &L) {
113   assert((&L == CurrentLoop || CurrentLoop->contains(&L)) &&
114          "Must not delete loop outside the current loop tree!");
115   // If this loop appears elsewhere within the queue, we also need to remove it
116   // there. However, we have to be careful to not remove the back of the queue
117   // as that is assumed to match the current loop.
118   assert(LQ.back() == CurrentLoop && "Loop queue back isn't the current loop!");
119   LQ.erase(std::remove(LQ.begin(), LQ.end(), &L), LQ.end());
120 
121   if (&L == CurrentLoop) {
122     CurrentLoopDeleted = true;
123     // Add this loop back onto the back of the queue to preserve our invariants.
124     LQ.push_back(&L);
125   }
126 }
127 
128 /// run - Execute all of the passes scheduled for execution.  Keep track of
129 /// whether any of the passes modifies the function, and if so, return true.
130 bool LPPassManager::runOnFunction(Function &F) {
131   auto &LIWP = getAnalysis<LoopInfoWrapperPass>();
132   LI = &LIWP.getLoopInfo();
133   Module &M = *F.getParent();
134 #if 0
135   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
136 #endif
137   bool Changed = false;
138 
139   // Collect inherited analysis from Module level pass manager.
140   populateInheritedAnalysis(TPM->activeStack);
141 
142   // Populate the loop queue in reverse program order. There is no clear need to
143   // process sibling loops in either forward or reverse order. There may be some
144   // advantage in deleting uses in a later loop before optimizing the
145   // definitions in an earlier loop. If we find a clear reason to process in
146   // forward order, then a forward variant of LoopPassManager should be created.
147   //
148   // Note that LoopInfo::iterator visits loops in reverse program
149   // order. Here, reverse_iterator gives us a forward order, and the LoopQueue
150   // reverses the order a third time by popping from the back.
151   for (Loop *L : reverse(*LI))
152     addLoopIntoQueue(L, LQ);
153 
154   if (LQ.empty()) // No loops, skip calling finalizers
155     return false;
156 
157   // Initialization
158   for (Loop *L : LQ) {
159     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
160       LoopPass *P = getContainedPass(Index);
161       Changed |= P->doInitialization(L, *this);
162     }
163   }
164 
165   // Walk Loops
166   unsigned InstrCount, FunctionSize = 0;
167   StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
168   bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
169   // Collect the initial size of the module and the function we're looking at.
170   if (EmitICRemark) {
171     InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
172     FunctionSize = F.getInstructionCount();
173   }
174   while (!LQ.empty()) {
175     CurrentLoopDeleted = false;
176     CurrentLoop = LQ.back();
177 
178     // Run all passes on the current Loop.
179     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
180       LoopPass *P = getContainedPass(Index);
181 
182       llvm::TimeTraceScope LoopPassScope("RunLoopPass", P->getPassName());
183 
184       dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
185                    CurrentLoop->getHeader()->getName());
186       dumpRequiredSet(P);
187 
188       initializeAnalysisImpl(P);
189 
190       bool LocalChanged = false;
191       {
192         PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
193         TimeRegion PassTimer(getPassTimer(P));
194         LocalChanged = P->runOnLoop(CurrentLoop, *this);
195         Changed |= LocalChanged;
196         if (EmitICRemark) {
197           unsigned NewSize = F.getInstructionCount();
198           // Update the size of the function, emit a remark, and update the
199           // size of the module.
200           if (NewSize != FunctionSize) {
201             int64_t Delta = static_cast<int64_t>(NewSize) -
202                             static_cast<int64_t>(FunctionSize);
203             emitInstrCountChangedRemark(P, M, Delta, InstrCount,
204                                         FunctionToInstrCount, &F);
205             InstrCount = static_cast<int64_t>(InstrCount) + Delta;
206             FunctionSize = NewSize;
207           }
208         }
209       }
210 
211       if (LocalChanged)
212         dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
213                      CurrentLoopDeleted ? "<deleted loop>"
214                                         : CurrentLoop->getName());
215       dumpPreservedSet(P);
216 
217       if (!CurrentLoopDeleted) {
218         // Manually check that this loop is still healthy. This is done
219         // instead of relying on LoopInfo::verifyLoop since LoopInfo
220         // is a function pass and it's really expensive to verify every
221         // loop in the function every time. That level of checking can be
222         // enabled with the -verify-loop-info option.
223         {
224           TimeRegion PassTimer(getPassTimer(&LIWP));
225           CurrentLoop->verifyLoop();
226         }
227         // Here we apply same reasoning as in the above case. Only difference
228         // is that LPPassManager might run passes which do not require LCSSA
229         // form (LoopPassPrinter for example). We should skip verification for
230         // such passes.
231         // FIXME: Loop-sink currently break LCSSA. Fix it and reenable the
232         // verification!
233 #if 0
234         if (mustPreserveAnalysisID(LCSSAVerificationPass::ID))
235           assert(CurrentLoop->isRecursivelyLCSSAForm(*DT, *LI));
236 #endif
237 
238         // Then call the regular verifyAnalysis functions.
239         verifyPreservedAnalysis(P);
240 
241         F.getContext().yield();
242       }
243 
244       removeNotPreservedAnalysis(P);
245       recordAvailableAnalysis(P);
246       removeDeadPasses(P,
247                        CurrentLoopDeleted ? "<deleted>"
248                                           : CurrentLoop->getHeader()->getName(),
249                        ON_LOOP_MSG);
250 
251       if (CurrentLoopDeleted)
252         // Do not run other passes on this loop.
253         break;
254     }
255 
256     // If the loop was deleted, release all the loop passes. This frees up
257     // some memory, and avoids trouble with the pass manager trying to call
258     // verifyAnalysis on them.
259     if (CurrentLoopDeleted) {
260       for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
261         Pass *P = getContainedPass(Index);
262         freePass(P, "<deleted>", ON_LOOP_MSG);
263       }
264     }
265 
266     // Pop the loop from queue after running all passes.
267     LQ.pop_back();
268   }
269 
270   // Finalization
271   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
272     LoopPass *P = getContainedPass(Index);
273     Changed |= P->doFinalization();
274   }
275 
276   return Changed;
277 }
278 
279 /// Print passes managed by this manager
280 void LPPassManager::dumpPassStructure(unsigned Offset) {
281   errs().indent(Offset*2) << "Loop Pass Manager\n";
282   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
283     Pass *P = getContainedPass(Index);
284     P->dumpPassStructure(Offset + 1);
285     dumpLastUses(P, Offset+1);
286   }
287 }
288 
289 
290 //===----------------------------------------------------------------------===//
291 // LoopPass
292 
293 Pass *LoopPass::createPrinterPass(raw_ostream &O,
294                                   const std::string &Banner) const {
295   return new PrintLoopPassWrapper(O, Banner);
296 }
297 
298 // Check if this pass is suitable for the current LPPassManager, if
299 // available. This pass P is not suitable for a LPPassManager if P
300 // is not preserving higher level analysis info used by other
301 // LPPassManager passes. In such case, pop LPPassManager from the
302 // stack. This will force assignPassManager() to create new
303 // LPPassManger as expected.
304 void LoopPass::preparePassManager(PMStack &PMS) {
305 
306   // Find LPPassManager
307   while (!PMS.empty() &&
308          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
309     PMS.pop();
310 
311   // If this pass is destroying high level information that is used
312   // by other passes that are managed by LPM then do not insert
313   // this pass in current LPM. Use new LPPassManager.
314   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager &&
315       !PMS.top()->preserveHigherLevelAnalysis(this))
316     PMS.pop();
317 }
318 
319 /// Assign pass manager to manage this pass.
320 void LoopPass::assignPassManager(PMStack &PMS,
321                                  PassManagerType PreferredType) {
322   // Find LPPassManager
323   while (!PMS.empty() &&
324          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
325     PMS.pop();
326 
327   LPPassManager *LPPM;
328   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager)
329     LPPM = (LPPassManager*)PMS.top();
330   else {
331     // Create new Loop Pass Manager if it does not exist.
332     assert (!PMS.empty() && "Unable to create Loop Pass Manager");
333     PMDataManager *PMD = PMS.top();
334 
335     // [1] Create new Loop Pass Manager
336     LPPM = new LPPassManager();
337     LPPM->populateInheritedAnalysis(PMS);
338 
339     // [2] Set up new manager's top level manager
340     PMTopLevelManager *TPM = PMD->getTopLevelManager();
341     TPM->addIndirectPassManager(LPPM);
342 
343     // [3] Assign manager to manage this new manager. This may create
344     // and push new managers into PMS
345     Pass *P = LPPM->getAsPass();
346     TPM->schedulePass(P);
347 
348     // [4] Push new manager into PMS
349     PMS.push(LPPM);
350   }
351 
352   LPPM->add(this);
353 }
354 
355 static std::string getDescription(const Loop &L) {
356   return "loop";
357 }
358 
359 bool LoopPass::skipLoop(const Loop *L) const {
360   const Function *F = L->getHeader()->getParent();
361   if (!F)
362     return false;
363   // Check the opt bisect limit.
364   OptPassGate &Gate = F->getContext().getOptPassGate();
365   if (Gate.isEnabled() && !Gate.shouldRunPass(this, getDescription(*L)))
366     return true;
367   // Check for the OptimizeNone attribute.
368   if (F->hasOptNone()) {
369     // FIXME: Report this to dbgs() only once per function.
370     LLVM_DEBUG(dbgs() << "Skipping pass '" << getPassName() << "' in function "
371                       << F->getName() << "\n");
372     // FIXME: Delete loop from pass manager's queue?
373     return true;
374   }
375   return false;
376 }
377 
378 LCSSAVerificationPass::LCSSAVerificationPass() : FunctionPass(ID) {
379   initializeLCSSAVerificationPassPass(*PassRegistry::getPassRegistry());
380 }
381 
382 char LCSSAVerificationPass::ID = 0;
383 INITIALIZE_PASS(LCSSAVerificationPass, "lcssa-verification", "LCSSA Verifier",
384                 false, false)
385