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