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/BasicAliasAnalysis.h"
12 #include "llvm/Analysis/BlockFrequencyInfo.h"
13 #include "llvm/Analysis/GlobalsModRef.h"
14 #include "llvm/Analysis/MemorySSA.h"
15 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
16 #include "llvm/Analysis/TargetLibraryInfo.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/TimeProfiler.h"
19 
20 using namespace llvm;
21 
22 namespace llvm {
23 
24 /// Explicitly specialize the pass manager's run method to handle loop nest
25 /// structure updates.
26 PreservedAnalyses
27 PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
28             LPMUpdater &>::run(Loop &L, LoopAnalysisManager &AM,
29                                LoopStandardAnalysisResults &AR, LPMUpdater &U) {
30   // Runs loop-nest passes only when the current loop is a top-level one.
31   PreservedAnalyses PA = (L.isOutermost() && !LoopNestPasses.empty())
32                              ? runWithLoopNestPasses(L, AM, AR, U)
33                              : runWithoutLoopNestPasses(L, AM, AR, U);
34 
35   // Invalidation for the current loop should be handled above, and other loop
36   // analysis results shouldn't be impacted by runs over this loop. Therefore,
37   // the remaining analysis results in the AnalysisManager are preserved. We
38   // mark this with a set so that we don't need to inspect each one
39   // individually.
40   // FIXME: This isn't correct! This loop and all nested loops' analyses should
41   // be preserved, but unrolling should invalidate the parent loop's analyses.
42   PA.preserveSet<AllAnalysesOn<Loop>>();
43 
44   return PA;
45 }
46 
47 void PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &,
48                  LPMUpdater &>::printPipeline(raw_ostream &OS,
49                                               function_ref<StringRef(StringRef)>
50                                                   MapClassName2PassName) {
51   for (unsigned Idx = 0, Size = LoopPasses.size(); Idx != Size; ++Idx) {
52     auto *P = LoopPasses[Idx].get();
53     P->printPipeline(OS, MapClassName2PassName);
54     if (Idx + 1 < Size)
55       OS << ",";
56   }
57 }
58 
59 // Run both loop passes and loop-nest passes on top-level loop \p L.
60 PreservedAnalyses
61 LoopPassManager::runWithLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
62                                        LoopStandardAnalysisResults &AR,
63                                        LPMUpdater &U) {
64   assert(L.isOutermost() &&
65          "Loop-nest passes should only run on top-level loops.");
66   PreservedAnalyses PA = PreservedAnalyses::all();
67 
68   // Request PassInstrumentation from analysis manager, will use it to run
69   // instrumenting callbacks for the passes later.
70   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
71 
72   unsigned LoopPassIndex = 0, LoopNestPassIndex = 0;
73 
74   // `LoopNestPtr` points to the `LoopNest` object for the current top-level
75   // loop and `IsLoopNestPtrValid` indicates whether the pointer is still valid.
76   // The `LoopNest` object will have to be re-constructed if the pointer is
77   // invalid when encountering a loop-nest pass.
78   std::unique_ptr<LoopNest> LoopNestPtr;
79   bool IsLoopNestPtrValid = false;
80 
81   for (size_t I = 0, E = IsLoopNestPass.size(); I != E; ++I) {
82     Optional<PreservedAnalyses> PassPA;
83     if (!IsLoopNestPass[I]) {
84       // The `I`-th pass is a loop pass.
85       auto &Pass = LoopPasses[LoopPassIndex++];
86       PassPA = runSinglePass(L, Pass, AM, AR, U, PI);
87     } else {
88       // The `I`-th pass is a loop-nest pass.
89       auto &Pass = LoopNestPasses[LoopNestPassIndex++];
90 
91       // If the loop-nest object calculated before is no longer valid,
92       // re-calculate it here before running the loop-nest pass.
93       if (!IsLoopNestPtrValid) {
94         LoopNestPtr = LoopNest::getLoopNest(L, AR.SE);
95         IsLoopNestPtrValid = true;
96       }
97       PassPA = runSinglePass(*LoopNestPtr, Pass, AM, AR, U, PI);
98     }
99 
100     // `PassPA` is `None` means that the before-pass callbacks in
101     // `PassInstrumentation` return false. The pass does not run in this case,
102     // so we can skip the following procedure.
103     if (!PassPA)
104       continue;
105 
106     // If the loop was deleted, abort the run and return to the outer walk.
107     if (U.skipCurrentLoop()) {
108       PA.intersect(std::move(*PassPA));
109       break;
110     }
111 
112     // Update the analysis manager as each pass runs and potentially
113     // invalidates analyses.
114     AM.invalidate(L, *PassPA);
115 
116     // Finally, we intersect the final preserved analyses to compute the
117     // aggregate preserved set for this pass manager.
118     PA.intersect(std::move(*PassPA));
119 
120     // Check if the current pass preserved the loop-nest object or not.
121     IsLoopNestPtrValid &= PassPA->getChecker<LoopNestAnalysis>().preserved();
122 
123     // After running the loop pass, the parent loop might change and we need to
124     // notify the updater, otherwise U.ParentL might gets outdated and triggers
125     // assertion failures in addSiblingLoops and addChildLoops.
126     U.setParentLoop(L.getParentLoop());
127 
128     // FIXME: Historically, the pass managers all called the LLVM context's
129     // yield function here. We don't have a generic way to acquire the
130     // context and it isn't yet clear what the right pattern is for yielding
131     // in the new pass manager so it is currently omitted.
132     // ...getContext().yield();
133   }
134   return PA;
135 }
136 
137 // Run all loop passes on loop \p L. Loop-nest passes don't run either because
138 // \p L is not a top-level one or simply because there are no loop-nest passes
139 // in the pass manager at all.
140 PreservedAnalyses
141 LoopPassManager::runWithoutLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
142                                           LoopStandardAnalysisResults &AR,
143                                           LPMUpdater &U) {
144   PreservedAnalyses PA = PreservedAnalyses::all();
145 
146   // Request PassInstrumentation from analysis manager, will use it to run
147   // instrumenting callbacks for the passes later.
148   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
149   for (auto &Pass : LoopPasses) {
150     Optional<PreservedAnalyses> PassPA = runSinglePass(L, Pass, AM, AR, U, PI);
151 
152     // `PassPA` is `None` means that the before-pass callbacks in
153     // `PassInstrumentation` return false. The pass does not run in this case,
154     // so we can skip the following procedure.
155     if (!PassPA)
156       continue;
157 
158     // If the loop was deleted, abort the run and return to the outer walk.
159     if (U.skipCurrentLoop()) {
160       PA.intersect(std::move(*PassPA));
161       break;
162     }
163 
164     // Update the analysis manager as each pass runs and potentially
165     // invalidates analyses.
166     AM.invalidate(L, *PassPA);
167 
168     // Finally, we intersect the final preserved analyses to compute the
169     // aggregate preserved set for this pass manager.
170     PA.intersect(std::move(*PassPA));
171 
172     // After running the loop pass, the parent loop might change and we need to
173     // notify the updater, otherwise U.ParentL might gets outdated and triggers
174     // assertion failures in addSiblingLoops and addChildLoops.
175     U.setParentLoop(L.getParentLoop());
176 
177     // FIXME: Historically, the pass managers all called the LLVM context's
178     // yield function here. We don't have a generic way to acquire the
179     // context and it isn't yet clear what the right pattern is for yielding
180     // in the new pass manager so it is currently omitted.
181     // ...getContext().yield();
182   }
183   return PA;
184 }
185 } // namespace llvm
186 
187 void FunctionToLoopPassAdaptor::printPipeline(
188     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
189   OS << (UseMemorySSA ? "loop-mssa(" : "loop(");
190   Pass->printPipeline(OS, MapClassName2PassName);
191   OS << ")";
192 }
193 PreservedAnalyses FunctionToLoopPassAdaptor::run(Function &F,
194                                                  FunctionAnalysisManager &AM) {
195   // Before we even compute any loop analyses, first run a miniature function
196   // pass pipeline to put loops into their canonical form. Note that we can
197   // directly build up function analyses after this as the function pass
198   // manager handles all the invalidation at that layer.
199   PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(F);
200 
201   PreservedAnalyses PA = PreservedAnalyses::all();
202   // Check the PassInstrumentation's BeforePass callbacks before running the
203   // canonicalization pipeline.
204   if (PI.runBeforePass<Function>(LoopCanonicalizationFPM, F)) {
205     PA = LoopCanonicalizationFPM.run(F, AM);
206     PI.runAfterPass<Function>(LoopCanonicalizationFPM, F, PA);
207   }
208 
209   // Get the loop structure for this function
210   LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
211 
212   // If there are no loops, there is nothing to do here.
213   if (LI.empty())
214     return PA;
215 
216   // Get the analysis results needed by loop passes.
217   MemorySSA *MSSA =
218       UseMemorySSA ? (&AM.getResult<MemorySSAAnalysis>(F).getMSSA()) : nullptr;
219   BlockFrequencyInfo *BFI = UseBlockFrequencyInfo && F.hasProfileData()
220                                 ? (&AM.getResult<BlockFrequencyAnalysis>(F))
221                                 : nullptr;
222   LoopStandardAnalysisResults LAR = {AM.getResult<AAManager>(F),
223                                      AM.getResult<AssumptionAnalysis>(F),
224                                      AM.getResult<DominatorTreeAnalysis>(F),
225                                      AM.getResult<LoopAnalysis>(F),
226                                      AM.getResult<ScalarEvolutionAnalysis>(F),
227                                      AM.getResult<TargetLibraryAnalysis>(F),
228                                      AM.getResult<TargetIRAnalysis>(F),
229                                      BFI,
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     // Note that we don't LAR.SE.verify() because that can change observed SE
313     // queries. See PR44815.
314     if (VerifyDomInfo)
315       LAR.DT.verify();
316     if (VerifyLoopInfo)
317       LAR.LI.verify(LAR.DT);
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 (UseMemorySSA)
351     PA.preserve<MemorySSAAnalysis>();
352   return PA;
353 }
354 
355 PrintLoopPass::PrintLoopPass() : OS(dbgs()) {}
356 PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
357     : OS(OS), Banner(Banner) {}
358 
359 PreservedAnalyses PrintLoopPass::run(Loop &L, LoopAnalysisManager &,
360                                      LoopStandardAnalysisResults &,
361                                      LPMUpdater &) {
362   printLoop(L, OS, Banner);
363   return PreservedAnalyses::all();
364 }
365