LLVM 22.0.0git
LoopPassManager.cpp
Go to the documentation of this file.
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
16
17using namespace llvm;
18
19/// Explicitly specialize the pass manager's run method to handle loop nest
20/// structure updates.
23 LPMUpdater &>::run(Loop &L, LoopAnalysisManager &AM,
25 // Runs loop-nest passes only when the current loop is a top-level one.
26 PreservedAnalyses PA = (L.isOutermost() && !LoopNestPasses.empty())
27 ? runWithLoopNestPasses(L, AM, AR, U)
28 : runWithoutLoopNestPasses(L, AM, AR, U);
29
30 // Invalidation for the current loop should be handled above, and other loop
31 // analysis results shouldn't be impacted by runs over this loop. Therefore,
32 // the remaining analysis results in the AnalysisManager are preserved. We
33 // mark this with a set so that we don't need to inspect each one
34 // individually.
35 // FIXME: This isn't correct! This loop and all nested loops' analyses should
36 // be preserved, but unrolling should invalidate the parent loop's analyses.
38
39 return PA;
40}
41
43 LPMUpdater &>::printPipeline(raw_ostream &OS,
45 MapClassName2PassName) {
46 assert(LoopPasses.size() + LoopNestPasses.size() == IsLoopNestPass.size());
47
48 unsigned IdxLP = 0, IdxLNP = 0;
49 for (unsigned Idx = 0, Size = IsLoopNestPass.size(); Idx != Size; ++Idx) {
50 if (IsLoopNestPass[Idx]) {
51 auto *P = LoopNestPasses[IdxLNP++].get();
52 P->printPipeline(OS, MapClassName2PassName);
53 } else {
54 auto *P = LoopPasses[IdxLP++].get();
55 P->printPipeline(OS, MapClassName2PassName);
56 }
57 if (Idx + 1 < Size)
58 OS << ',';
59 }
60}
61
62// Run both loop passes and loop-nest passes on top-level loop \p L.
64LoopPassManager::runWithLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
66 LPMUpdater &U) {
67 assert(L.isOutermost() &&
68 "Loop-nest passes should only run on top-level loops.");
69 PreservedAnalyses PA = PreservedAnalyses::all();
70
71 // Request PassInstrumentation from analysis manager, will use it to run
72 // instrumenting callbacks for the passes later.
73 PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
74
75 unsigned LoopPassIndex = 0, LoopNestPassIndex = 0;
76
77 // `LoopNestPtr` points to the `LoopNest` object for the current top-level
78 // loop and `IsLoopNestPtrValid` indicates whether the pointer is still valid.
79 // The `LoopNest` object will have to be re-constructed if the pointer is
80 // invalid when encountering a loop-nest pass.
81 std::unique_ptr<LoopNest> LoopNestPtr;
82 bool IsLoopNestPtrValid = false;
83 Loop *OuterMostLoop = &L;
84
85 for (size_t I = 0, E = IsLoopNestPass.size(); I != E; ++I) {
86 std::optional<PreservedAnalyses> PassPA;
87 if (!IsLoopNestPass[I]) {
88 // The `I`-th pass is a loop pass.
89 auto &Pass = LoopPasses[LoopPassIndex++];
90 PassPA = runSinglePass(L, Pass, AM, AR, U, PI);
91 } else {
92 // The `I`-th pass is a loop-nest pass.
93 auto &Pass = LoopNestPasses[LoopNestPassIndex++];
94
95 // If the loop-nest object calculated before is no longer valid,
96 // re-calculate it here before running the loop-nest pass.
97 //
98 // FIXME: PreservedAnalysis should not be abused to tell if the
99 // status of loopnest has been changed. We should use and only
100 // use LPMUpdater for this purpose.
101 if (!IsLoopNestPtrValid || U.isLoopNestChanged()) {
102 while (auto *ParentLoop = OuterMostLoop->getParentLoop())
103 OuterMostLoop = ParentLoop;
104 LoopNestPtr = LoopNest::getLoopNest(*OuterMostLoop, AR.SE);
105 IsLoopNestPtrValid = true;
106 U.markLoopNestChanged(false);
107 }
108
109 PassPA = runSinglePass(*LoopNestPtr, Pass, AM, AR, U, PI);
110 }
111
112 // `PassPA` is `None` means that the before-pass callbacks in
113 // `PassInstrumentation` return false. The pass does not run in this case,
114 // so we can skip the following procedure.
115 if (!PassPA)
116 continue;
117
118 // If the loop was deleted, abort the run and return to the outer walk.
119 if (U.skipCurrentLoop()) {
120 PA.intersect(std::move(*PassPA));
121 break;
122 }
123
124 // Update the analysis manager as each pass runs and potentially
125 // invalidates analyses.
126 AM.invalidate(IsLoopNestPass[I] ? *OuterMostLoop : L, *PassPA);
127
128 // Finally, we intersect the final preserved analyses to compute the
129 // aggregate preserved set for this pass manager.
130 PA.intersect(std::move(*PassPA));
131
132 // Check if the current pass preserved the loop-nest object or not.
133 IsLoopNestPtrValid &= PassPA->getChecker<LoopNestAnalysis>().preserved();
134
135 // After running the loop pass, the parent loop might change and we need to
136 // notify the updater, otherwise U.ParentL might gets outdated and triggers
137 // assertion failures in addSiblingLoops and addChildLoops.
138 U.setParentLoop((IsLoopNestPass[I] ? *OuterMostLoop : L).getParentLoop());
139 }
140 return PA;
141}
142
143// Run all loop passes on loop \p L. Loop-nest passes don't run either because
144// \p L is not a top-level one or simply because there are no loop-nest passes
145// in the pass manager at all.
147LoopPassManager::runWithoutLoopNestPasses(Loop &L, LoopAnalysisManager &AM,
149 LPMUpdater &U) {
150 PreservedAnalyses PA = PreservedAnalyses::all();
151
152 // Request PassInstrumentation from analysis manager, will use it to run
153 // instrumenting callbacks for the passes later.
154 PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR);
155 for (auto &Pass : LoopPasses) {
156 std::optional<PreservedAnalyses> PassPA =
157 runSinglePass(L, Pass, AM, AR, U, PI);
158
159 // `PassPA` is `None` means that the before-pass callbacks in
160 // `PassInstrumentation` return false. The pass does not run in this case,
161 // so we can skip the following procedure.
162 if (!PassPA)
163 continue;
164
165 // If the loop was deleted, abort the run and return to the outer walk.
166 if (U.skipCurrentLoop()) {
167 PA.intersect(std::move(*PassPA));
168 break;
169 }
170
171 // Update the analysis manager as each pass runs and potentially
172 // invalidates analyses.
173 AM.invalidate(L, *PassPA);
174
175 // Finally, we intersect the final preserved analyses to compute the
176 // aggregate preserved set for this pass manager.
177 PA.intersect(std::move(*PassPA));
178
179 // After running the loop pass, the parent loop might change and we need to
180 // notify the updater, otherwise U.ParentL might gets outdated and triggers
181 // assertion failures in addSiblingLoops and addChildLoops.
182 U.setParentLoop(L.getParentLoop());
183 }
184 return PA;
185}
186
188 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
189 OS << (UseMemorySSA ? "loop-mssa(" : "loop(");
190 Pass->printPipeline(OS, MapClassName2PassName);
191 OS << ')';
192}
193
196 // Before we even compute any loop analyses, first run a miniature function
197 // pass pipeline to put loops into their canonical form. Note that we can
198 // directly build up function analyses after this as the function pass
199 // manager handles all the invalidation at that layer.
201
203 // Check the PassInstrumentation's BeforePass callbacks before running the
204 // canonicalization pipeline.
205 if (PI.runBeforePass<Function>(LoopCanonicalizationFPM, F)) {
206 PA = LoopCanonicalizationFPM.run(F, AM);
207 PI.runAfterPass<Function>(LoopCanonicalizationFPM, F, PA);
208 }
209
210 // Get the loop structure for this function
211 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
212
213 // If there are no loops, there is nothing to do here.
214 if (LI.empty())
215 return PA;
216
217 // Get the analysis results needed by loop passes.
218 MemorySSA *MSSA =
219 UseMemorySSA ? (&AM.getResult<MemorySSAAnalysis>(F).getMSSA()) : nullptr;
220 BlockFrequencyInfo *BFI = UseBlockFrequencyInfo && F.hasProfileData()
222 : nullptr;
230 BFI,
231 MSSA};
232
233 // Setup the loop analysis manager from its proxy. It is important that
234 // this is only done when there are loops to process and we have built the
235 // LoopStandardAnalysisResults object. The loop analyses cached in this
236 // manager have access to those analysis results and so it must invalidate
237 // itself when they go away.
238 auto &LAMFP = AM.getResult<LoopAnalysisManagerFunctionProxy>(F);
239 if (UseMemorySSA)
240 LAMFP.markMSSAUsed();
241 LoopAnalysisManager &LAM = LAMFP.getManager();
242
243 // A postorder worklist of loops to process.
245
246 // Register the worklist and loop analysis manager so that loop passes can
247 // update them when they mutate the loop nest structure.
248 LPMUpdater Updater(Worklist, LAM, LoopNestMode);
249
250 // Add the loop nests in the reverse order of LoopInfo. See method
251 // declaration.
252 if (!LoopNestMode) {
253 appendLoopsToWorklist(LI, Worklist);
254 } else {
255 for (Loop *L : LI)
256 Worklist.insert(L);
257 }
258
259#ifndef NDEBUG
260 PI.pushBeforeNonSkippedPassCallback([&LAR, &LI](StringRef PassID, Any IR) {
261 if (isSpecialPass(PassID, {"PassManager"}))
262 return;
264 const Loop **LPtr = llvm::any_cast<const Loop *>(&IR);
265 const Loop *L = LPtr ? *LPtr : nullptr;
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#if LLVM_ENABLE_ABI_BREAKING_CHECKS
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 = Pass->run(*L, LAM, LAR, Updater);
295
296 // Do not pass deleted Loop into the instrumentation.
297 if (Updater.skipCurrentLoop())
298 PI.runAfterPassInvalidated<Loop>(*Pass, PassPA);
299 else
300 PI.runAfterPass<Loop>(*Pass, *L, PassPA);
301
302 if (LAR.MSSA && !PassPA.getChecker<MemorySSAAnalysis>().preserved())
303 reportFatalUsageError("Loop pass manager using MemorySSA contains a pass "
304 "that does not preserve MemorySSA");
305
306#ifndef NDEBUG
307 // LoopAnalysisResults should always be valid.
308 if (VerifyDomInfo)
309 LAR.DT.verify();
310 if (VerifyLoopInfo)
311 LAR.LI.verify(LAR.DT);
312 if (VerifySCEV)
313 LAR.SE.verify();
314 if (LAR.MSSA && VerifyMemorySSA)
315 LAR.MSSA->verifyMemorySSA();
316#endif
317
318 // If the loop hasn't been deleted, we need to handle invalidation here.
319 if (!Updater.skipCurrentLoop())
320 // We know that the loop pass couldn't have invalidated any other
321 // loop's analyses (that's the contract of a loop pass), so directly
322 // handle the loop analysis manager's invalidation here.
323 LAM.invalidate(*L, PassPA);
324
325 // Then intersect the preserved set so that invalidation of module
326 // analyses will eventually occur when the module pass completes.
327 PA.intersect(std::move(PassPA));
328 } while (!Worklist.empty());
329
330#ifndef NDEBUG
332#endif
333
334 // By definition we preserve the proxy. We also preserve all analyses on
335 // Loops. This precludes *any* invalidation of loop analyses by the proxy,
336 // but that's OK because we've taken care to invalidate analyses in the
337 // loop analysis manager incrementally above.
338 PA.preserveSet<AllAnalysesOn<Loop>>();
339 PA.preserve<LoopAnalysisManagerFunctionProxy>();
340 // We also preserve the set of standard analyses.
341 PA.preserve<DominatorTreeAnalysis>();
342 PA.preserve<LoopAnalysis>();
343 PA.preserve<ScalarEvolutionAnalysis>();
344 if (UseMemorySSA)
345 PA.preserve<MemorySSAAnalysis>();
346 return PA;
347}
348
350PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
351 : OS(OS), Banner(Banner) {}
352
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:80
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:270
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define P(N)
LoopAnalysisManager LAM
This pass exposes codegen information to IR-level passes.
A manager for alias analyses.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Analysis pass which computes a DominatorTree.
Definition Dominators.h:284
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Runs the loop passes across every loop in the function.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
bool skipCurrentLoop() const
This can be queried by loop passes which run other loop passes (like pass managers) to know whether t...
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:569
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
static std::unique_ptr< LoopNest > getLoopNest(Loop &Root, ScalarEvolution &SE)
Construct a LoopNest object.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:936
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
Pseudo-analysis pass that exposes the PassInstrumentation to pass managers.
This class provides instrumentation entry points for the Pass Manager, doing calls to callbacks regis...
void runAfterPassInvalidated(const PassT &Pass, const PreservedAnalyses &PA) const
AfterPassInvalidated instrumentation point - takes Pass instance that has just been executed.
void pushBeforeNonSkippedPassCallback(CallableT C)
void runAfterPass(const PassT &Pass, const IRUnitT &IR, const PreservedAnalyses &PA) const
AfterPass instrumentation point - takes Pass instance that has just been executed and constant refere...
bool runBeforePass(const PassT &Pass, const IRUnitT &IR) const
BeforePass instrumentation point - takes Pass instance to be executed and constant reference to IR it...
Manages a sequence of passes over a particular unit of IR.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
void intersect(const PreservedAnalyses &Arg)
Intersect this set with another in place.
Definition Analysis.h:193
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &, LoopStandardAnalysisResults &, LPMUpdater &)
bool empty() const
Determine if the PriorityWorklist is empty or not.
bool insert(const T &X)
Insert a new element into the PriorityWorklist.
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI void verify() const
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
T any_cast(const Any &Value)
Definition Any.h:137
LLVM_ABI bool VerifySCEV
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
LLVM_ABI bool isSpecialPass(StringRef PassID, const std::vector< StringRef > &Specials)
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:51
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:84
LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
Definition LoopInfo.cpp:989
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:180
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...