1 //===- LoopPassManager.cpp - Loop pass management -------------------------===//
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 #include "llvm/Transforms/Scalar/LoopPassManager.h"
10 #include "llvm/Analysis/AssumptionCache.h"
11 #include "llvm/Analysis/BlockFrequencyInfo.h"
12 #include "llvm/Analysis/BranchProbabilityInfo.h"
13 #include "llvm/Analysis/MemorySSA.h"
14 #include "llvm/Analysis/ScalarEvolution.h"
15 #include "llvm/Analysis/TargetLibraryInfo.h"
16 #include "llvm/Analysis/TargetTransformInfo.h"
17 #include "llvm/Support/TimeProfiler.h"
18 
19 using namespace llvm;
20 
21 namespace llvm {
22 
23 /// Explicitly specialize the pass manager's run method to handle loop nest
24 /// structure updates.
25 PreservedAnalyses
26 PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
27             LPMUpdater &>::run(Loop &L, LoopAnalysisManager &AM,
28                                LoopStandardAnalysisResults &AR, LPMUpdater &U) {
29   // Runs loop-nest passes only when the current loop is a top-level one.
30   PreservedAnalyses PA = (L.isOutermost() && !LoopNestPasses.empty())
31                              ? runWithLoopNestPasses(L, AM, AR, U)
32                              : runWithoutLoopNestPasses(L, AM, AR, U);
33 
34   // Invalidation for the current loop should be handled above, and other loop
35   // analysis results shouldn't be impacted by runs over this loop. Therefore,
36   // the remaining analysis results in the AnalysisManager are preserved. We
37   // mark this with a set so that we don't need to inspect each one
38   // individually.
39   // FIXME: This isn't correct! This loop and all nested loops' analyses should
40   // be preserved, but unrolling should invalidate the parent loop's analyses.
41   PA.preserveSet<AllAnalysesOn<Loop>>();
42 
43   return PA;
44 }
45 
46 void PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
47                  LPMUpdater &>::printPipeline(raw_ostream &OS,
48                                               function_ref<StringRef(StringRef)>
49                                                   MapClassName2PassName) {
50   assert(LoopPasses.size() + LoopNestPasses.size() == IsLoopNestPass.size());
51 
52   unsigned IdxLP = 0, IdxLNP = 0;
53   for (unsigned Idx = 0, Size = IsLoopNestPass.size(); Idx != Size; ++Idx) {
54     if (IsLoopNestPass[Idx]) {
55       auto *P = LoopNestPasses[IdxLNP++].get();
56       P->printPipeline(OS, MapClassName2PassName);
57     } else {
58       auto *P = LoopPasses[IdxLP++].get();
59       P->printPipeline(OS, MapClassName2PassName);
60     }
61     if (Idx + 1 < Size)
62       OS << ",";
63   }
64 }
65 
66 // Run both loop passes and loop-nest passes on top-level loop \p L.
67 PreservedAnalyses
68 LoopPassManager::runWithLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
69                                        LoopStandardAnalysisResults &AR,
70                                        LPMUpdater &U) {
71   assert(L.isOutermost() &&
72          "Loop-nest passes should only run on top-level loops.");
73   PreservedAnalyses PA = PreservedAnalyses::all();
74 
75   // Request PassInstrumentation from analysis manager, will use it to run
76   // instrumenting callbacks for the passes later.
77   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
78 
79   unsigned LoopPassIndex = 0, LoopNestPassIndex = 0;
80 
81   // `LoopNestPtr` points to the `LoopNest` object for the current top-level
82   // loop and `IsLoopNestPtrValid` indicates whether the pointer is still valid.
83   // The `LoopNest` object will have to be re-constructed if the pointer is
84   // invalid when encountering a loop-nest pass.
85   std::unique_ptr<LoopNest> LoopNestPtr;
86   bool IsLoopNestPtrValid = false;
87 
88   for (size_t I = 0, E = IsLoopNestPass.size(); I != E; ++I) {
89     Optional<PreservedAnalyses> PassPA;
90     if (!IsLoopNestPass[I]) {
91       // The `I`-th pass is a loop pass.
92       auto &Pass = LoopPasses[LoopPassIndex++];
93       PassPA = runSinglePass(L, Pass, AM, AR, U, PI);
94     } else {
95       // The `I`-th pass is a loop-nest pass.
96       auto &Pass = LoopNestPasses[LoopNestPassIndex++];
97 
98       // If the loop-nest object calculated before is no longer valid,
99       // re-calculate it here before running the loop-nest pass.
100       if (!IsLoopNestPtrValid) {
101         LoopNestPtr = LoopNest::getLoopNest(L, AR.SE);
102         IsLoopNestPtrValid = true;
103       }
104       PassPA = runSinglePass(*LoopNestPtr, Pass, AM, AR, U, PI);
105     }
106 
107     // `PassPA` is `None` means that the before-pass callbacks in
108     // `PassInstrumentation` return false. The pass does not run in this case,
109     // so we can skip the following procedure.
110     if (!PassPA)
111       continue;
112 
113     // If the loop was deleted, abort the run and return to the outer walk.
114     if (U.skipCurrentLoop()) {
115       PA.intersect(std::move(*PassPA));
116       break;
117     }
118 
119     // Update the analysis manager as each pass runs and potentially
120     // invalidates analyses.
121     AM.invalidate(L, *PassPA);
122 
123     // Finally, we intersect the final preserved analyses to compute the
124     // aggregate preserved set for this pass manager.
125     PA.intersect(std::move(*PassPA));
126 
127     // Check if the current pass preserved the loop-nest object or not.
128     IsLoopNestPtrValid &= PassPA->getChecker<LoopNestAnalysis>().preserved();
129 
130     // After running the loop pass, the parent loop might change and we need to
131     // notify the updater, otherwise U.ParentL might gets outdated and triggers
132     // assertion failures in addSiblingLoops and addChildLoops.
133     U.setParentLoop(L.getParentLoop());
134   }
135   return PA;
136 }
137 
138 // Run all loop passes on loop \p L. Loop-nest passes don't run either because
139 // \p L is not a top-level one or simply because there are no loop-nest passes
140 // in the pass manager at all.
141 PreservedAnalyses
142 LoopPassManager::runWithoutLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
143                                           LoopStandardAnalysisResults &AR,
144                                           LPMUpdater &U) {
145   PreservedAnalyses PA = PreservedAnalyses::all();
146 
147   // Request PassInstrumentation from analysis manager, will use it to run
148   // instrumenting callbacks for the passes later.
149   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
150   for (auto &Pass : LoopPasses) {
151     Optional<PreservedAnalyses> PassPA = runSinglePass(L, Pass, AM, AR, U, PI);
152 
153     // `PassPA` is `None` means that the before-pass callbacks in
154     // `PassInstrumentation` return false. The pass does not run in this case,
155     // so we can skip the following procedure.
156     if (!PassPA)
157       continue;
158 
159     // If the loop was deleted, abort the run and return to the outer walk.
160     if (U.skipCurrentLoop()) {
161       PA.intersect(std::move(*PassPA));
162       break;
163     }
164 
165     // Update the analysis manager as each pass runs and potentially
166     // invalidates analyses.
167     AM.invalidate(L, *PassPA);
168 
169     // Finally, we intersect the final preserved analyses to compute the
170     // aggregate preserved set for this pass manager.
171     PA.intersect(std::move(*PassPA));
172 
173     // After running the loop pass, the parent loop might change and we need to
174     // notify the updater, otherwise U.ParentL might gets outdated and triggers
175     // assertion failures in addSiblingLoops and addChildLoops.
176     U.setParentLoop(L.getParentLoop());
177   }
178   return PA;
179 }
180 } // namespace llvm
181 
182 void FunctionToLoopPassAdaptor::printPipeline(
183     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
184   OS << (UseMemorySSA ? "loop-mssa(" : "loop(");
185   Pass->printPipeline(OS, MapClassName2PassName);
186   OS << ")";
187 }
188 PreservedAnalyses FunctionToLoopPassAdaptor::run(Function &F,
189                                                  FunctionAnalysisManager &AM) {
190   // Before we even compute any loop analyses, first run a miniature function
191   // pass pipeline to put loops into their canonical form. Note that we can
192   // directly build up function analyses after this as the function pass
193   // manager handles all the invalidation at that layer.
194   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(F);
195 
196   PreservedAnalyses PA = PreservedAnalyses::all();
197   // Check the PassInstrumentation's BeforePass callbacks before running the
198   // canonicalization pipeline.
199   if (PI.runBeforePass<Function>(LoopCanonicalizationFPM, F)) {
200     PA = LoopCanonicalizationFPM.run(F, AM);
201     PI.runAfterPass<Function>(LoopCanonicalizationFPM, F, PA);
202   }
203 
204   // Get the loop structure for this function
205   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
206 
207   // If there are no loops, there is nothing to do here.
208   if (LI.empty())
209     return PA;
210 
211   // Get the analysis results needed by loop passes.
212   MemorySSA *MSSA =
213       UseMemorySSA ? (&AM.getResult<MemorySSAAnalysis>(F).getMSSA()) : nullptr;
214   BlockFrequencyInfo *BFI = UseBlockFrequencyInfo && F.hasProfileData()
215                                 ? (&AM.getResult<BlockFrequencyAnalysis>(F))
216                                 : nullptr;
217   BranchProbabilityInfo *BPI =
218       UseBranchProbabilityInfo && F.hasProfileData()
219           ? (&AM.getResult<BranchProbabilityAnalysis>(F))
220           : nullptr;
221   LoopStandardAnalysisResults LAR = {AM.getResult<AAManager>(F),
222                                      AM.getResult<AssumptionAnalysis>(F),
223                                      AM.getResult<DominatorTreeAnalysis>(F),
224                                      AM.getResult<LoopAnalysis>(F),
225                                      AM.getResult<ScalarEvolutionAnalysis>(F),
226                                      AM.getResult<TargetLibraryAnalysis>(F),
227                                      AM.getResult<TargetIRAnalysis>(F),
228                                      BFI,
229                                      BPI,
230                                      MSSA};
231 
232   // Setup the loop analysis manager from its proxy. It is important that
233   // this is only done when there are loops to process and we have built the
234   // LoopStandardAnalysisResults object. The loop analyses cached in this
235   // manager have access to those analysis results and so it must invalidate
236   // itself when they go away.
237   auto &LAMFP = AM.getResult<LoopAnalysisManagerFunctionProxy>(F);
238   if (UseMemorySSA)
239     LAMFP.markMSSAUsed();
240   LoopAnalysisManager &LAM = LAMFP.getManager();
241 
242   // A postorder worklist of loops to process.
243   SmallPriorityWorklist<Loop *, 4> Worklist;
244 
245   // Register the worklist and loop analysis manager so that loop passes can
246   // update them when they mutate the loop nest structure.
247   LPMUpdater Updater(Worklist, LAM, LoopNestMode);
248 
249   // Add the loop nests in the reverse order of LoopInfo. See method
250   // declaration.
251   if (!LoopNestMode) {
252     appendLoopsToWorklist(LI, Worklist);
253   } else {
254     for (Loop *L : LI)
255       Worklist.insert(L);
256   }
257 
258 #ifndef NDEBUG
259   PI.pushBeforeNonSkippedPassCallback([&LAR, &LI](StringRef PassID, Any IR) {
260     if (isSpecialPass(PassID, {"PassManager"}))
261       return;
262     assert(any_isa<const Loop *>(IR) || any_isa<const LoopNest *>(IR));
263     const Loop *L = any_isa<const Loop *>(IR)
264                         ? any_cast<const Loop *>(IR)
265                         : &any_cast<const LoopNest *>(IR)->getOutermostLoop();
266     assert(L && "Loop should be valid for printing");
267 
268     // Verify the loop structure and LCSSA form before visiting the loop.
269     L->verifyLoop();
270     assert(L->isRecursivelyLCSSAForm(LAR.DT, LI) &&
271            "Loops must remain in LCSSA form!");
272   });
273 #endif
274 
275   do {
276     Loop *L = Worklist.pop_back_val();
277     assert(!(LoopNestMode && L->getParentLoop()) &&
278            "L should be a top-level loop in loop-nest mode.");
279 
280     // Reset the update structure for this loop.
281     Updater.CurrentL = L;
282     Updater.SkipCurrentLoop = false;
283 
284 #ifndef NDEBUG
285     // Save a parent loop pointer for asserts.
286     Updater.ParentL = L->getParentLoop();
287 #endif
288     // Check the PassInstrumentation's BeforePass callbacks before running the
289     // pass, skip its execution completely if asked to (callback returns
290     // false).
291     if (!PI.runBeforePass<Loop>(*Pass, *L))
292       continue;
293 
294     PreservedAnalyses PassPA;
295     {
296       TimeTraceScope TimeScope(Pass->name());
297       PassPA = Pass->run(*L, LAM, LAR, Updater);
298     }
299 
300     // Do not pass deleted Loop into the instrumentation.
301     if (Updater.skipCurrentLoop())
302       PI.runAfterPassInvalidated<Loop>(*Pass, PassPA);
303     else
304       PI.runAfterPass<Loop>(*Pass, *L, PassPA);
305 
306     if (LAR.MSSA && !PassPA.getChecker<MemorySSAAnalysis>().preserved())
307       report_fatal_error("Loop pass manager using MemorySSA contains a pass "
308                          "that does not preserve MemorySSA");
309 
310 #ifndef NDEBUG
311     // LoopAnalysisResults should always be valid.
312     if (VerifyDomInfo)
313       LAR.DT.verify();
314     if (VerifyLoopInfo)
315       LAR.LI.verify(LAR.DT);
316     if (VerifySCEV)
317       LAR.SE.verify();
318     if (LAR.MSSA && VerifyMemorySSA)
319       LAR.MSSA->verifyMemorySSA();
320 #endif
321 
322     // If the loop hasn't been deleted, we need to handle invalidation here.
323     if (!Updater.skipCurrentLoop())
324       // We know that the loop pass couldn't have invalidated any other
325       // loop's analyses (that's the contract of a loop pass), so directly
326       // handle the loop analysis manager's invalidation here.
327       LAM.invalidate(*L, PassPA);
328 
329     // Then intersect the preserved set so that invalidation of module
330     // analyses will eventually occur when the module pass completes.
331     PA.intersect(std::move(PassPA));
332   } while (!Worklist.empty());
333 
334 #ifndef NDEBUG
335   PI.popBeforeNonSkippedPassCallback();
336 #endif
337 
338   // By definition we preserve the proxy. We also preserve all analyses on
339   // Loops. This precludes *any* invalidation of loop analyses by the proxy,
340   // but that's OK because we've taken care to invalidate analyses in the
341   // loop analysis manager incrementally above.
342   PA.preserveSet<AllAnalysesOn<Loop>>();
343   PA.preserve<LoopAnalysisManagerFunctionProxy>();
344   // We also preserve the set of standard analyses.
345   PA.preserve<DominatorTreeAnalysis>();
346   PA.preserve<LoopAnalysis>();
347   PA.preserve<ScalarEvolutionAnalysis>();
348   if (UseBlockFrequencyInfo && F.hasProfileData())
349     PA.preserve<BlockFrequencyAnalysis>();
350   if (UseBranchProbabilityInfo && F.hasProfileData())
351     PA.preserve<BranchProbabilityAnalysis>();
352   if (UseMemorySSA)
353     PA.preserve<MemorySSAAnalysis>();
354   return PA;
355 }
356 
357 PrintLoopPass::PrintLoopPass() : OS(dbgs()) {}
358 PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
359     : OS(OS), Banner(Banner) {}
360 
361 PreservedAnalyses PrintLoopPass::run(Loop &L, LoopAnalysisManager &,
362                                      LoopStandardAnalysisResults &,
363                                      LPMUpdater &) {
364   printLoop(L, OS, Banner);
365   return PreservedAnalyses::all();
366 }
367