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