LLVM 23.0.0git
LegacyPassManager.cpp
Go to the documentation of this file.
1//===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
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// This file implements the legacy LLVM Pass Manager infrastructure.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/MapVector.h"
17#include "llvm/IR/LLVMContext.h"
19#include "llvm/IR/Module.h"
21#include "llvm/IR/PrintPasses.h"
22#include "llvm/Support/Chrono.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Error.h"
29#include "llvm/Support/Timer.h"
31
32using namespace llvm;
33
34// See PassManagers.h for Pass Manager infrastructure overview.
35
36//===----------------------------------------------------------------------===//
37// Pass debugging information. Often it is useful to find out what pass is
38// running when a crash occurs in a utility. When this library is compiled with
39// debugging on, a command line option (--debug-pass) is enabled that causes the
40// pass name to be printed before it executes.
41//
42
43namespace {
44// Different debug levels that can be enabled...
45enum PassDebugLevel {
46 Disabled, Arguments, Structure, Executions, Details
47};
48} // namespace
49
51 "debug-pass", cl::Hidden,
52 cl::desc("Print legacy PassManager debugging information"),
53 cl::values(clEnumVal(Disabled, "disable debug output"),
54 clEnumVal(Arguments, "print pass arguments to pass to 'opt'"),
55 clEnumVal(Structure, "print pass structure before run()"),
56 clEnumVal(Executions, "print pass name before it is executed"),
57 clEnumVal(Details, "print pass details when it is executed")));
58
59/// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
60/// or higher is specified.
62 return PassDebugging >= Executions;
63}
64
66 Module &M, StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount) {
67 // Only calculate getInstructionCount if the size-info remark is requested.
68 unsigned InstrCount = 0;
69
70 // Collect instruction counts for every function. We'll use this to emit
71 // per-function size remarks later.
72 for (Function &F : M) {
73 unsigned FCount = F.getInstructionCount();
74
75 // Insert a record into FunctionToInstrCount keeping track of the current
76 // size of the function as the first member of a pair. Set the second
77 // member to 0; if the function is deleted by the pass, then when we get
78 // here, we'll be able to let the user know that F no longer contributes to
79 // the module.
80 FunctionToInstrCount[F.getName().str()] =
81 std::pair<unsigned, unsigned>(FCount, 0);
82 InstrCount += FCount;
83 }
84 return InstrCount;
85}
86
88 Pass *P, Module &M, int64_t Delta, unsigned CountBefore,
89 StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount,
90 Function *F) {
91 // If it's a pass manager, don't emit a remark. (This hinges on the assumption
92 // that the only passes that return non-null with getAsPMDataManager are pass
93 // managers.) The reason we have to do this is to avoid emitting remarks for
94 // CGSCC passes.
95 if (P->getAsPMDataManager())
96 return;
97
98 // Set to true if this isn't a module pass or CGSCC pass.
99 bool CouldOnlyImpactOneFunction = (F != nullptr);
100
101 // Helper lambda that updates the changes to the size of some function.
102 auto UpdateFunctionChanges =
103 [&FunctionToInstrCount](Function &MaybeChangedFn) {
104 // Update the total module count.
105 unsigned FnSize = MaybeChangedFn.getInstructionCount();
106
107 // If we created a new function, then we need to add it to the map and
108 // say that it changed from 0 instructions to FnSize.
109 auto [It, Inserted] = FunctionToInstrCount.try_emplace(
110 MaybeChangedFn.getName(), 0, FnSize);
111 if (Inserted)
112 return;
113 // Insert the new function size into the second member of the pair. This
114 // tells us whether or not this function changed in size.
115 It->second.second = FnSize;
116 };
117
118 // We need to initially update all of the function sizes.
119 // If no function was passed in, then we're either a module pass or an
120 // CGSCC pass.
121 if (!CouldOnlyImpactOneFunction)
122 llvm::for_each(M, UpdateFunctionChanges);
123 else
124 UpdateFunctionChanges(*F);
125
126 // Do we have a function we can use to emit a remark?
127 if (!CouldOnlyImpactOneFunction) {
128 // We need a function containing at least one basic block in order to output
129 // remarks. Since it's possible that the first function in the module
130 // doesn't actually contain a basic block, we have to go and find one that's
131 // suitable for emitting remarks.
132 auto It = llvm::find_if(M, [](const Function &Fn) { return !Fn.empty(); });
133
134 // Didn't find a function. Quit.
135 if (It == M.end())
136 return;
137
138 // We found a function containing at least one basic block.
139 F = &*It;
140 }
141 int64_t CountAfter = static_cast<int64_t>(CountBefore) + Delta;
142 BasicBlock &BB = *F->begin();
143 OptimizationRemarkAnalysis R("size-info", "IRSizeChange",
144 DiagnosticLocation(), &BB);
145 // FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This
146 // would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.
147 R << DiagnosticInfoOptimizationBase::Argument("Pass", P->getPassName())
148 << ": IR instruction count changed from "
149 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore)
150 << " to "
151 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter)
152 << "; Delta: "
153 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta);
154 F->getContext().diagnose(R); // Not using ORE for layering reasons.
155
156 // Emit per-function size change remarks separately.
157 std::string PassName = P->getPassName().str();
158
159 // Helper lambda that emits a remark when the size of a function has changed.
160 auto EmitFunctionSizeChangedRemark = [&FunctionToInstrCount, &F, &BB,
161 &PassName](StringRef Fname) {
162 unsigned FnCountBefore, FnCountAfter;
163 std::pair<unsigned, unsigned> &Change = FunctionToInstrCount[Fname];
164 std::tie(FnCountBefore, FnCountAfter) = Change;
165 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
166 static_cast<int64_t>(FnCountBefore);
167
168 if (FnDelta == 0)
169 return;
170
171 // FIXME: We shouldn't use BB for the location here. Unfortunately, because
172 // the function that we're looking at could have been deleted, we can't use
173 // it for the source location. We *want* remarks when a function is deleted
174 // though, so we're kind of stuck here as is. (This remark, along with the
175 // whole-module size change remarks really ought not to have source
176 // locations at all.)
177 OptimizationRemarkAnalysis FR("size-info", "FunctionIRSizeChange",
178 DiagnosticLocation(), &BB);
180 << ": Function: "
181 << DiagnosticInfoOptimizationBase::Argument("Function", Fname)
182 << ": IR instruction count changed from "
184 FnCountBefore)
185 << " to "
187 FnCountAfter)
188 << "; Delta: "
189 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", FnDelta);
190 F->getContext().diagnose(FR);
191
192 // Update the function size.
193 Change.first = FnCountAfter;
194 };
195
196 // Are we looking at more than one function? If so, emit remarks for all of
197 // the functions in the module. Otherwise, only emit one remark.
198 if (!CouldOnlyImpactOneFunction)
199 llvm::for_each(FunctionToInstrCount.keys(), EmitFunctionSizeChangedRemark);
200 else
201 EmitFunctionSizeChangedRemark(F->getName().str());
202}
203
205 if (!V && !M)
206 OS << "Releasing pass '";
207 else
208 OS << "Running pass '";
209
210 OS << P->getPassName() << "'";
211
212 if (M) {
213 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
214 return;
215 }
216 if (!V) {
217 OS << '\n';
218 return;
219 }
220
221 OS << " on ";
222 if (isa<Function>(V))
223 OS << "function";
224 else if (isa<BasicBlock>(V))
225 OS << "basic block";
226 else
227 OS << "value";
228
229 OS << " '";
230 V->printAsOperand(OS, /*PrintType=*/false, M);
231 OS << "'\n";
232}
233
234namespace llvm {
235namespace legacy {
237
238//===----------------------------------------------------------------------===//
239// FunctionPassManagerImpl
240//
241/// FunctionPassManagerImpl manages FPPassManagers
243 public PMDataManager,
244 public PMTopLevelManager {
245 virtual void anchor();
246private:
247 bool wasRun;
248public:
249 static char ID;
253
254 /// \copydoc FunctionPassManager::add()
255 void add(Pass *P) {
257 }
258
259 /// createPrinterPass - Get a function printer pass.
261 const std::string &Banner) const override {
262 return createPrintFunctionPass(O, Banner);
263 }
264
265 // Prepare for running an on the fly pass, freeing memory if needed
266 // from a previous run.
268
269 /// run - Execute all of the passes scheduled for execution. Keep track of
270 /// whether any of the passes modifies the module, and if so, return true.
271 bool run(Function &F);
272
273 /// doInitialization - Run all of the initializers for the function passes.
274 ///
275 bool doInitialization(Module &M) override;
276
277 /// doFinalization - Run all of the finalizers for the function passes.
278 ///
279 bool doFinalization(Module &M) override;
280
281
282 PMDataManager *getAsPMDataManager() override { return this; }
283 Pass *getAsPass() override { return this; }
287
288 /// Pass Manager itself does not invalidate any analysis info.
289 void getAnalysisUsage(AnalysisUsage &Info) const override {
290 Info.setPreservesAll();
291 }
292
294 assert(N < PassManagers.size() && "Pass number out of range!");
295 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
296 return FP;
297 }
298
299 void dumpPassStructure(unsigned Offset) override {
300 for (unsigned I = 0; I < getNumContainedManagers(); ++I)
302 }
303};
304
305void FunctionPassManagerImpl::anchor() {}
306
308
309//===----------------------------------------------------------------------===//
310// FunctionPassManagerImpl implementation
311//
313 bool Changed = false;
314
316 dumpPasses();
317
318 for (ImmutablePass *ImPass : getImmutablePasses())
319 Changed |= ImPass->doInitialization(M);
320
321 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
323
324 return Changed;
325}
326
328 bool Changed = false;
329
330 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
332
333 for (ImmutablePass *ImPass : getImmutablePasses())
334 Changed |= ImPass->doFinalization(M);
335
336 return Changed;
337}
338
340 if (!wasRun)
341 return;
342 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
343 FPPassManager *FPPM = getContainedManager(Index);
344 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
345 FPPM->getContainedPass(Index)->releaseMemory();
346 }
347 }
348 wasRun = false;
349}
350
351// Execute all the passes managed by this top level manager.
352// Return true if any function is modified by a pass.
354 bool Changed = false;
355
357 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
359 F.getContext().yield();
360 }
361
362 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
364
365 wasRun = true;
366 return Changed;
367}
368} // namespace legacy
369} // namespace llvm
370
371namespace {
372//===----------------------------------------------------------------------===//
373// MPPassManager
374//
375/// MPPassManager manages ModulePasses and function pass managers.
376/// It batches all Module passes and function pass managers together and
377/// sequences them to process one module.
378class MPPassManager : public Pass, public PMDataManager {
379public:
380 static char ID;
381 explicit MPPassManager() : Pass(PT_PassManager, ID) {}
382
383 // Delete on the fly managers.
384 ~MPPassManager() override {
385 for (auto &OnTheFlyManager : OnTheFlyManagers) {
386 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
387 delete FPP;
388 }
389 }
390
391 /// createPrinterPass - Get a module printer pass.
392 Pass *createPrinterPass(raw_ostream &O,
393 const std::string &Banner) const override {
394 return createPrintModulePass(O, Banner);
395 }
396
397 /// run - Execute all of the passes scheduled for execution. Keep track of
398 /// whether any of the passes modifies the module, and if so, return true.
399 bool runOnModule(Module &M);
400
403
404 /// Pass Manager itself does not invalidate any analysis info.
405 void getAnalysisUsage(AnalysisUsage &Info) const override {
406 Info.setPreservesAll();
407 }
408
409 /// Add RequiredPass into list of lower level passes required by pass P.
410 /// RequiredPass is run on the fly by Pass Manager when P requests it
411 /// through getAnalysis interface.
412 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
413
414 /// Return function pass corresponding to PassInfo PI, that is
415 /// required by module pass MP. Instantiate analysis pass, by using
416 /// its runOnFunction() for function F.
417 std::tuple<Pass *, bool> getOnTheFlyPass(Pass *MP, AnalysisID PI,
418 Function &F) override;
419
420 StringRef getPassName() const override { return "Module Pass Manager"; }
421
422 PMDataManager *getAsPMDataManager() override { return this; }
423 Pass *getAsPass() override { return this; }
424
425 // Print passes managed by this manager
426 void dumpPassStructure(unsigned Offset) override {
427 dbgs().indent(Offset*2) << "ModulePass Manager\n";
428 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
429 ModulePass *MP = getContainedPass(Index);
430 MP->dumpPassStructure(Offset + 1);
432 OnTheFlyManagers.find(MP);
433 if (I != OnTheFlyManagers.end())
434 I->second->dumpPassStructure(Offset + 2);
435 dumpLastUses(MP, Offset+1);
436 }
437 }
438
439 ModulePass *getContainedPass(unsigned N) {
440 assert(N < PassVector.size() && "Pass number out of range!");
441 return static_cast<ModulePass *>(PassVector[N]);
442 }
443
444 PassManagerType getPassManagerType() const override {
446 }
447
448 private:
449 /// Collection of on the fly FPPassManagers. These managers manage
450 /// function passes that are required by module passes.
451 MapVector<Pass *, legacy::FunctionPassManagerImpl *> OnTheFlyManagers;
452};
453
454char MPPassManager::ID = 0;
455} // End anonymous namespace
456
457namespace llvm {
458namespace legacy {
459//===----------------------------------------------------------------------===//
460// PassManagerImpl
461//
462
463/// PassManagerImpl manages MPPassManagers
464class PassManagerImpl : public Pass,
465 public PMDataManager,
466 public PMTopLevelManager {
467 virtual void anchor();
468
469public:
470 static char ID;
472 : Pass(PT_PassManager, ID), PMTopLevelManager(new MPPassManager()) {}
473
474 /// \copydoc PassManager::add()
475 void add(Pass *P) {
477 }
478
479 /// createPrinterPass - Get a module printer pass.
481 const std::string &Banner) const override {
482 return createPrintModulePass(O, Banner);
483 }
484
485 /// run - Execute all of the passes scheduled for execution. Keep track of
486 /// whether any of the passes modifies the module, and if so, return true.
487 bool run(Module &M);
488
491
492 /// Pass Manager itself does not invalidate any analysis info.
493 void getAnalysisUsage(AnalysisUsage &Info) const override {
494 Info.setPreservesAll();
495 }
496
497 PMDataManager *getAsPMDataManager() override { return this; }
498 Pass *getAsPass() override { return this; }
502
503 MPPassManager *getContainedManager(unsigned N) {
504 assert(N < PassManagers.size() && "Pass number out of range!");
505 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
506 return MP;
507 }
508};
509
510void PassManagerImpl::anchor() {}
511
512char PassManagerImpl::ID = 0;
513
514//===----------------------------------------------------------------------===//
515// PassManagerImpl implementation
516
517//
518/// run - Execute all of the passes scheduled for execution. Keep track of
519/// whether any of the passes modifies the module, and if so, return true.
521 bool Changed = false;
522
524 dumpPasses();
525
526 for (ImmutablePass *ImPass : getImmutablePasses())
527 Changed |= ImPass->doInitialization(M);
528
530 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
531 Changed |= getContainedManager(Index)->runOnModule(M);
532 M.getContext().yield();
533 }
534
535 for (ImmutablePass *ImPass : getImmutablePasses())
536 Changed |= ImPass->doFinalization(M);
537
538 return Changed;
539}
540} // namespace legacy
541} // namespace llvm
542
543//===----------------------------------------------------------------------===//
544// PMTopLevelManager implementation
545
546/// Initialize top level manager. Create first pass manager.
552
553/// Set pass P as the last user of the given analysis passes.
554void
556 unsigned PDepth = 0;
557 if (P->getResolver())
558 PDepth = P->getResolver()->getPMDataManager().getDepth();
559
560 for (Pass *AP : AnalysisPasses) {
561 // Record P as the new last user of AP.
562 auto &LastUserOfAP = LastUser[AP];
563 if (LastUserOfAP)
564 InversedLastUser[LastUserOfAP].erase(AP);
565 LastUserOfAP = P;
566 InversedLastUser[P].insert(AP);
567
568 if (P == AP)
569 continue;
570
571 // Update the last users of passes that are required transitive by AP.
572 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
575 SmallVector<Pass *, 12> LastPMUses;
576 for (AnalysisID ID : IDs) {
577 Pass *AnalysisPass = findAnalysisPass(ID);
578 assert(AnalysisPass && "Expected analysis pass to exist.");
579 AnalysisResolver *AR = AnalysisPass->getResolver();
580 assert(AR && "Expected analysis resolver to exist.");
581 unsigned APDepth = AR->getPMDataManager().getDepth();
582
583 if (PDepth == APDepth)
584 LastUses.push_back(AnalysisPass);
585 else if (PDepth > APDepth)
586 LastPMUses.push_back(AnalysisPass);
587 }
588
589 setLastUser(LastUses, P);
590
591 // If this pass has a corresponding pass manager, push higher level
592 // analysis to this pass manager.
593 if (P->getResolver())
594 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
595
596 // If AP is the last user of other passes then make P last user of
597 // such passes.
598 auto &LastUsedByAP = InversedLastUser[AP];
599 for (Pass *L : LastUsedByAP)
600 LastUser[L] = P;
601 InversedLastUser[P].insert_range(LastUsedByAP);
602 LastUsedByAP.clear();
603 }
604}
605
606/// Collect passes whose last user is P
608 Pass *P) {
609 auto DMI = InversedLastUser.find(P);
610 if (DMI == InversedLastUser.end())
611 return;
612
613 auto &LU = DMI->second;
614 LastUses.append(LU.begin(), LU.end());
615}
616
618 AnalysisUsage *AnUsage = nullptr;
619 auto DMI = AnUsageMap.find(P);
620 if (DMI != AnUsageMap.end())
621 AnUsage = DMI->second;
622 else {
623 // Look up the analysis usage from the pass instance (different instances
624 // of the same pass can produce different results), but unique the
625 // resulting object to reduce memory usage. This helps to greatly reduce
626 // memory usage when we have many instances of only a few pass types
627 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
628 // of dependencies.
629 AnalysisUsage AU;
630 P->getAnalysisUsage(AU);
631
632 AUFoldingSetNode* Node = nullptr;
634 AUFoldingSetNode::Profile(ID, AU);
635 void *IP = nullptr;
636 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
637 Node = N;
638 else {
639 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
640 UniqueAnalysisUsages.InsertNode(Node, IP);
641 }
642 assert(Node && "cached analysis usage must be non null");
643
644 AnUsageMap[P] = &Node->AU;
645 AnUsage = &Node->AU;
646 }
647 return AnUsage;
648}
649
650/// Schedule pass P for execution. Make sure that passes required by
651/// P are run before P is run. Update analysis info maintained by
652/// the manager. Remove dead passes. This is a recursive function.
654
655 // TODO : Allocate function manager for this pass, other wise required set
656 // may be inserted into previous function manager
657
658 // Give pass a chance to prepare the stage.
659 P->preparePassManager(activeStack);
660
661 // If P is an analysis pass and it is available then do not
662 // generate the analysis again. Stale analysis info should not be
663 // available at this point.
664 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
665 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
666 // Remove any cached AnalysisUsage information.
667 AnUsageMap.erase(P);
668 delete P;
669 return;
670 }
671
673
674 bool checkAnalysis = true;
675 while (checkAnalysis) {
676 checkAnalysis = false;
677
678 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
679 for (const AnalysisID ID : RequiredSet) {
680
681 Pass *AnalysisPass = findAnalysisPass(ID);
682 if (!AnalysisPass) {
683 const PassInfo *PI = findAnalysisPassInfo(ID);
684
685 if (!PI) {
686 // Pass P is not in the global PassRegistry
687 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
688 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
689 dbgs() << "Required Passes:" << "\n";
690 for (const AnalysisID ID2 : RequiredSet) {
691 if (ID == ID2)
692 break;
693 Pass *AnalysisPass2 = findAnalysisPass(ID2);
694 if (AnalysisPass2) {
695 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
696 } else {
697 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
698 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
699 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
700 }
701 }
702 }
703
704 assert(PI && "Expected required passes to be initialized");
705 AnalysisPass = PI->createPass();
706 if (P->getPotentialPassManagerType () ==
707 AnalysisPass->getPotentialPassManagerType())
708 // Schedule analysis pass that is managed by the same pass manager.
709 schedulePass(AnalysisPass);
710 else if (P->getPotentialPassManagerType () >
711 AnalysisPass->getPotentialPassManagerType()) {
712 // Schedule analysis pass that is managed by a new manager.
713 schedulePass(AnalysisPass);
714 // Recheck analysis passes to ensure that required analyses that
715 // are already checked are still available.
716 checkAnalysis = true;
717 } else
718 // Do not schedule this analysis. Lower level analysis
719 // passes are run on the fly.
720 delete AnalysisPass;
721 }
722 }
723 }
724
725 // Now all required passes are available.
726 if (ImmutablePass *IP = P->getAsImmutablePass()) {
727 // P is a immutable pass and it will be managed by this
728 // top level manager. Set up analysis resolver to connect them.
729 PMDataManager *DM = getAsPMDataManager();
731 P->setResolver(AR);
732 DM->initializeAnalysisImpl(P);
734 DM->recordAvailableAnalysis(IP);
735 return;
736 }
737
738 if (PI && !PI->isAnalysis() && shouldPrintBeforePass(PI->getPassArgument())) {
739 Pass *PP =
740 P->createPrinterPass(dbgs(), ("*** IR Dump Before " + P->getPassName() +
741 " (" + PI->getPassArgument() + ") ***")
742 .str());
743 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
744 }
745
746 // Add the requested pass to the best available pass manager.
747 P->assignPassManager(activeStack, getTopLevelPassManagerType());
748
749 if (PI && !PI->isAnalysis() && shouldPrintAfterPass(PI->getPassArgument())) {
750 Pass *PP =
751 P->createPrinterPass(dbgs(), ("*** IR Dump After " + P->getPassName() +
752 " (" + PI->getPassArgument() + ") ***")
753 .str());
754 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
755 }
756}
757
758/// Find the pass that implements Analysis AID. Search immutable
759/// passes and all pass managers. If desired pass is not found
760/// then return NULL.
762 // For immutable passes we have a direct mapping from ID to pass, so check
763 // that first.
764 if (Pass *P = ImmutablePassMap.lookup(AID))
765 return P;
766
767 // Check pass managers
769 if (Pass *P = PassManager->findAnalysisPass(AID, false))
770 return P;
771
772 // Check other pass managers
773 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
774 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
775 return P;
776
777 return nullptr;
778}
779
781 const PassInfo *&PI = AnalysisPassInfos[AID];
782 if (!PI)
784 else
786 "The pass info pointer changed for an analysis ID!");
787
788 return PI;
789}
790
792 P->initializePass();
793 ImmutablePasses.push_back(P);
794
795 // Add this pass to the map from its analysis ID. We clobber any prior runs
796 // of the pass in the map so that the last one added is the one found when
797 // doing lookups.
798 AnalysisID AID = P->getPassID();
799 ImmutablePassMap[AID] = P;
800}
801
802// Print passes managed by this top level manager.
804
805 if (PassDebugging < Structure)
806 return;
807
808 // Print out the immutable passes
809 for (ImmutablePass *Pass : ImmutablePasses)
811
812 // Every class that derives from PMDataManager also derives from Pass
813 // (sometimes indirectly), but there's no inheritance relationship
814 // between PMDataManager and Pass, so we have to getAsPass to get
815 // from a PMDataManager* to a Pass*.
816 for (PMDataManager *Manager : PassManagers)
817 Manager->getAsPass()->dumpPassStructure(1);
818}
819
821
823 return;
824
825 dbgs() << "Pass Arguments: ";
826 for (ImmutablePass *P : ImmutablePasses)
827 if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
828 assert(PI && "Expected all immutable passes to be initialized");
829 dbgs() << " -" << PI->getPassArgument();
830 }
831 for (PMDataManager *PM : PassManagers)
832 PM->dumpPassArguments();
833 dbgs() << "\n";
834}
835
837 for (PMDataManager *PM : PassManagers)
838 PM->initializeAnalysisInfo();
839
840 // Initailize other pass managers
841 for (PMDataManager *IPM : IndirectPassManagers)
842 IPM->initializeAnalysisInfo();
843}
844
845/// Destructor
847 for (PMDataManager *PM : PassManagers)
848 delete PM;
849
850 for (ImmutablePass *P : ImmutablePasses)
851 delete P;
852}
853
854//===----------------------------------------------------------------------===//
855// PMDataManager implementation
856
857/// Augement AvailableAnalysis by adding analysis made available by pass P.
859 AnalysisID PI = P->getPassID();
860
861 AvailableAnalysis[PI] = P;
862}
863
864// Return true if P preserves high level analysis used by other
865// passes managed by this manager
867 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
868 if (AnUsage->getPreservesAll())
869 return true;
870
871 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
872 for (Pass *P1 : HigherLevelAnalysis) {
873 if (P1->getAsImmutablePass() == nullptr &&
874 !is_contained(PreservedSet, P1->getPassID()))
875 return false;
876 }
877
878 return true;
879}
880
881/// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
883 // Don't do this unless assertions are enabled.
884#ifdef NDEBUG
885 return;
886#endif
887 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
888 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
889
890 // Verify preserved analysis
891 for (AnalysisID AID : PreservedSet) {
892 if (Pass *AP = findAnalysisPass(AID, true)) {
893 TimeRegion PassTimer(getPassTimer(AP));
894 AP->verifyAnalysis();
895 }
896 }
897}
898
899/// Remove Analysis not preserved by Pass P
901 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
902 if (AnUsage->getPreservesAll())
903 return;
904
905 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
906 for (auto I = AvailableAnalysis.begin(), E = AvailableAnalysis.end();
907 I != E;) {
908 auto Info = I++;
909 if (Info->second->getAsImmutablePass() == nullptr &&
910 !is_contained(PreservedSet, Info->first)) {
911 // Remove this analysis
912 if (PassDebugging >= Details) {
913 Pass *S = Info->second;
914 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
915 dbgs() << S->getPassName() << "'\n";
916 }
917 AvailableAnalysis.erase(Info);
918 }
919 }
920
921 // Check inherited analysis also. If P is not preserving analysis
922 // provided by parent manager then remove it here.
924 if (!IA)
925 continue;
926
927 for (auto I = IA->begin(), E = IA->end(); I != E;) {
928 auto Info = I++;
929 if (Info->second->getAsImmutablePass() == nullptr &&
930 !is_contained(PreservedSet, Info->first)) {
931 // Remove this analysis
932 if (PassDebugging >= Details) {
933 Pass *S = Info->second;
934 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
935 dbgs() << S->getPassName() << "'\n";
936 }
937 IA->erase(Info);
938 }
939 }
940 }
941}
942
943/// Remove analysis passes that are not used any longer
945 enum PassDebuggingString DBG_STR) {
946
947 SmallVector<Pass *, 12> DeadPasses;
948
949 // If this is a on the fly manager then it does not have TPM.
950 if (!TPM)
951 return;
952
953 TPM->collectLastUses(DeadPasses, P);
954
955 if (PassDebugging >= Details && !DeadPasses.empty()) {
956 dbgs() << " -*- '" << P->getPassName();
957 dbgs() << "' is the last user of following pass instances.";
958 dbgs() << " Free these instances\n";
959 }
960
961 for (Pass *P : DeadPasses)
962 freePass(P, Msg, DBG_STR);
963}
964
966 enum PassDebuggingString DBG_STR) {
967 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
968
969 {
970 // If the pass crashes releasing memory, remember this.
972 TimeRegion PassTimer(getPassTimer(P));
973
974 P->releaseMemory();
975 }
976
977 // Remove the pass itself (if it is not already removed).
978 AvailableAnalysis.erase(P->getPassID());
979}
980
981/// Add pass P into the PassVector. Update
982/// AvailableAnalysis appropriately if ProcessAnalysis is true.
983void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
984 // This manager is going to manage pass P. Set up analysis resolver
985 // to connect them.
986 AnalysisResolver *AR = new AnalysisResolver(*this);
987 P->setResolver(AR);
988
989 // If a FunctionPass F is the last user of ModulePass info M
990 // then the F's manager, not F, records itself as a last user of M.
991 SmallVector<Pass *, 12> TransferLastUses;
992
993 if (!ProcessAnalysis) {
994 // Add pass
995 PassVector.push_back(P);
996 return;
997 }
998
999 // At the moment, this pass is the last user of all required passes.
1000 SmallVector<Pass *, 12> LastUses;
1001 SmallVector<Pass *, 8> UsedPasses;
1002 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1003
1004 unsigned PDepth = this->getDepth();
1005
1006 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
1007 for (Pass *PUsed : UsedPasses) {
1008 unsigned RDepth = 0;
1009
1010 assert(PUsed->getResolver() && "Analysis Resolver is not set");
1011 PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
1012 RDepth = DM.getDepth();
1013
1014 if (PDepth == RDepth)
1015 LastUses.push_back(PUsed);
1016 else if (PDepth > RDepth) {
1017 // Let the parent claim responsibility of last use
1018 TransferLastUses.push_back(PUsed);
1019 // Keep track of higher level analysis used by this manager.
1020 HigherLevelAnalysis.push_back(PUsed);
1021 } else
1022 llvm_unreachable("Unable to accommodate Used Pass");
1023 }
1024
1025 // Set P as P's last user until someone starts using P.
1026 // However, if P is a Pass Manager then it does not need
1027 // to record its last user.
1028 if (!P->getAsPMDataManager())
1029 LastUses.push_back(P);
1030 TPM->setLastUser(LastUses, P);
1031
1032 if (!TransferLastUses.empty()) {
1033 Pass *My_PM = getAsPass();
1034 TPM->setLastUser(TransferLastUses, My_PM);
1035 TransferLastUses.clear();
1036 }
1037
1038 // Now, take care of required analyses that are not available.
1039 for (AnalysisID ID : ReqAnalysisNotAvailable) {
1040 const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1041 Pass *AnalysisPass = PI->createPass();
1042 this->addLowerLevelRequiredPass(P, AnalysisPass);
1043 }
1044
1045 // Take a note of analysis required and made available by this pass.
1046 // Remove the analysis not preserved by this pass
1049
1050 // Add pass
1051 PassVector.push_back(P);
1052}
1053
1054
1055/// Populate UP with analysis pass that are used or required by
1056/// pass P and are available. Populate RP_NotAvail with analysis
1057/// pass that are required by pass P but are not available.
1060 Pass *P) {
1061 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1062
1063 for (const auto &UsedID : AnUsage->getUsedSet())
1064 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1065 UP.push_back(AnalysisPass);
1066
1067 for (const auto &RequiredID : AnUsage->getRequiredSet())
1068 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1069 UP.push_back(AnalysisPass);
1070 else
1071 RP_NotAvail.push_back(RequiredID);
1072}
1073
1074// All Required analyses should be available to the pass as it runs! Here
1075// we fill in the AnalysisImpls member of the pass so that it can
1076// successfully use the getAnalysis() method to retrieve the
1077// implementations it needs.
1078//
1080 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1081
1082 for (const AnalysisID ID : AnUsage->getRequiredSet()) {
1083 Pass *Impl = findAnalysisPass(ID, true);
1084 if (!Impl)
1085 // This may be analysis pass that is initialized on the fly.
1086 // If that is not the case then it will raise an assert when it is used.
1087 continue;
1088 AnalysisResolver *AR = P->getResolver();
1089 assert(AR && "Analysis Resolver is not set");
1090 AR->addAnalysisImplsPair(ID, Impl);
1091 }
1092}
1093
1094/// Find the pass that implements Analysis AID. If desired pass is not found
1095/// then return NULL.
1097
1098 // Check if AvailableAnalysis map has one entry.
1099 auto I = AvailableAnalysis.find(AID);
1100
1101 if (I != AvailableAnalysis.end())
1102 return I->second;
1103
1104 // Search Parents through TopLevelManager
1105 if (SearchParent)
1106 return TPM->findAnalysisPass(AID);
1107
1108 return nullptr;
1109}
1110
1111// Print list of passes that are last used by P.
1113 if (PassDebugging < Details)
1114 return;
1115
1117
1118 // If this is a on the fly manager then it does not have TPM.
1119 if (!TPM)
1120 return;
1121
1122 TPM->collectLastUses(LUses, P);
1123
1124 for (Pass *P : LUses) {
1125 dbgs() << "--" << std::string(Offset*2, ' ');
1126 P->dumpPassStructure(0);
1127 }
1128}
1129
1131 for (Pass *P : PassVector) {
1132 if (PMDataManager *PMD = P->getAsPMDataManager())
1133 PMD->dumpPassArguments();
1134 else if (const PassInfo *PI = TPM->findAnalysisPassInfo(P->getPassID()))
1135 dbgs() << " -" << PI->getPassArgument();
1136 }
1137}
1138
1140 enum PassDebuggingString S2,
1141 StringRef Msg) {
1142 if (PassDebugging < Executions)
1143 return;
1144 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1145 << std::string(getDepth() * 2 + 1, ' ');
1146 switch (S1) {
1147 case EXECUTION_MSG:
1148 dbgs() << "Executing Pass '" << P->getPassName();
1149 break;
1150 case MODIFICATION_MSG:
1151 dbgs() << "Made Modification '" << P->getPassName();
1152 break;
1153 case FREEING_MSG:
1154 dbgs() << " Freeing Pass '" << P->getPassName();
1155 break;
1156 default:
1157 break;
1158 }
1159 switch (S2) {
1160 case ON_FUNCTION_MSG:
1161 dbgs() << "' on Function '" << Msg << "'...\n";
1162 break;
1163 case ON_MODULE_MSG:
1164 dbgs() << "' on Module '" << Msg << "'...\n";
1165 break;
1166 case ON_REGION_MSG:
1167 dbgs() << "' on Region '" << Msg << "'...\n";
1168 break;
1169 case ON_LOOP_MSG:
1170 dbgs() << "' on Loop '" << Msg << "'...\n";
1171 break;
1172 case ON_CG_MSG:
1173 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1174 break;
1175 default:
1176 break;
1177 }
1178}
1179
1181 if (PassDebugging < Details)
1182 return;
1183
1184 AnalysisUsage analysisUsage;
1185 P->getAnalysisUsage(analysisUsage);
1186 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1187}
1188
1190 if (PassDebugging < Details)
1191 return;
1192
1193 AnalysisUsage analysisUsage;
1194 P->getAnalysisUsage(analysisUsage);
1195 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1196}
1197
1199 if (PassDebugging < Details)
1200 return;
1201
1202 AnalysisUsage analysisUsage;
1203 P->getAnalysisUsage(analysisUsage);
1204 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1205}
1206
1207void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1208 const AnalysisUsage::VectorType &Set) const {
1209 assert(PassDebugging >= Details);
1210 if (Set.empty())
1211 return;
1212 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1213 for (unsigned i = 0; i != Set.size(); ++i) {
1214 if (i) dbgs() << ',';
1215 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1216 if (!PInf) {
1217 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1218 // all drivers.
1219 dbgs() << " Uninitialized Pass";
1220 continue;
1221 }
1222 dbgs() << ' ' << PInf->getPassName();
1223 }
1224 dbgs() << '\n';
1225}
1226
1227/// Add RequiredPass into list of lower level passes required by pass P.
1228/// RequiredPass is run on the fly by Pass Manager when P requests it
1229/// through getAnalysis interface.
1230/// This should be handled by specific pass manager.
1232 if (TPM) {
1233 TPM->dumpArguments();
1234 TPM->dumpPasses();
1235 }
1236
1237 // Module Level pass may required Function Level analysis info
1238 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1239 // to provide this on demand. In that case, in Pass manager terminology,
1240 // module level pass is requiring lower level analysis info managed by
1241 // lower level pass manager.
1242
1243 // When Pass manager is not able to order required analysis info, Pass manager
1244 // checks whether any lower level manager will be able to provide this
1245 // analysis info on demand or not.
1246#ifndef NDEBUG
1247 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1248 dbgs() << "' required by '" << P->getPassName() << "'\n";
1249#endif
1250 llvm_unreachable("Unable to schedule pass");
1251}
1252
1253std::tuple<Pass *, bool> PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI,
1254 Function &F) {
1255 llvm_unreachable("Unable to find on the fly pass");
1256}
1257
1258// Destructor
1260 for (Pass *P : PassVector)
1261 delete P;
1262}
1263
1264//===----------------------------------------------------------------------===//
1265// NOTE: Is this the right place to define this method ?
1266// getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1268 return PM.findAnalysisPass(ID, true);
1269}
1270
1271std::tuple<Pass *, bool>
1273 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1274}
1275
1276namespace llvm {
1277namespace legacy {
1278
1279//===----------------------------------------------------------------------===//
1280// FunctionPassManager implementation
1281
1282/// Create new Function pass manager
1283FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1285 // FPM is the top level manager.
1286 FPM->setTopLevelManager(FPM);
1287
1288 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1289 FPM->setResolver(AR);
1290}
1291
1292FunctionPassManager::~FunctionPassManager() {
1293 delete FPM;
1294}
1295
1296void FunctionPassManager::add(Pass *P) {
1297 FPM->add(P);
1298}
1299
1300/// run - Execute all of the passes scheduled for execution. Keep
1301/// track of whether any of the passes modifies the function, and if
1302/// so, return true.
1303///
1305 handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1306 report_fatal_error(Twine("Error reading bitcode file: ") + EIB.message());
1307 });
1308 return FPM->run(F);
1309}
1310
1311
1312/// doInitialization - Run all of the initializers for the function passes.
1313///
1314bool FunctionPassManager::doInitialization() {
1315 return FPM->doInitialization(*M);
1316}
1317
1318/// doFinalization - Run all of the finalizers for the function passes.
1319///
1320bool FunctionPassManager::doFinalization() {
1321 return FPM->doFinalization(*M);
1322}
1323} // namespace legacy
1324} // namespace llvm
1325
1326/// cleanup - After running all passes, clean up pass manager cache.
1328 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1330 AnalysisResolver *AR = FP->getResolver();
1331 assert(AR && "Analysis Resolver is not set");
1332 AR->clearAnalysisImpls();
1333 }
1334}
1335
1336
1337//===----------------------------------------------------------------------===//
1338// FPPassManager implementation
1339
1340char FPPassManager::ID = 0;
1341/// Print passes managed by this manager
1343 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1344 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1346 FP->dumpPassStructure(Offset + 1);
1348 }
1349}
1350
1351/// Execute all of the passes scheduled for execution by invoking
1352/// runOnFunction method. Keep track of whether any of the passes modifies
1353/// the function, and if so, return true.
1355 if (F.isDeclaration())
1356 return false;
1357
1358 bool Changed = false;
1359 Module &M = *F.getParent();
1360 // Collect inherited analysis from Module level pass manager.
1361 populateInheritedAnalysis(TPM->activeStack);
1362
1363 unsigned InstrCount, FunctionSize = 0;
1364 StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1365 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1366 // Collect the initial size of the module.
1367 if (EmitICRemark) {
1368 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1369 FunctionSize = F.getInstructionCount();
1370 }
1371
1372 // Store name outside of loop to avoid redundant calls.
1373 const StringRef Name = F.getName();
1374 llvm::TimeTraceScope FunctionScope("OptFunction", Name);
1375
1376 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1378 bool LocalChanged = false;
1379
1380 // Call getPassName only when required. The call itself is fairly cheap, but
1381 // still virtual and repeated calling adds unnecessary overhead.
1382 llvm::TimeTraceScope PassScope(
1383 "RunPass", [FP]() { return std::string(FP->getPassName()); });
1384
1387
1389
1390 {
1392 TimeRegion PassTimer(getPassTimer(FP));
1393#ifdef EXPENSIVE_CHECKS
1394 uint64_t RefHash = FP->structuralHash(F);
1395#endif
1396 LocalChanged |= FP->runOnFunction(F);
1397
1398#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
1399 if (!LocalChanged && (RefHash != FP->structuralHash(F))) {
1400 llvm::errs() << "Pass modifies its input and doesn't report it: "
1401 << FP->getPassName() << "\n";
1402 llvm_unreachable("Pass modifies its input and doesn't report it");
1403 }
1404#endif
1405
1406 if (EmitICRemark) {
1407 unsigned NewSize = F.getInstructionCount();
1408
1409 // Update the size of the function, emit a remark, and update the size
1410 // of the module.
1411 if (NewSize != FunctionSize) {
1412 int64_t Delta = static_cast<int64_t>(NewSize) -
1413 static_cast<int64_t>(FunctionSize);
1415 FunctionToInstrCount, &F);
1416 InstrCount = static_cast<int64_t>(InstrCount) + Delta;
1417 FunctionSize = NewSize;
1418 }
1419 }
1420 }
1421
1422 Changed |= LocalChanged;
1423 if (LocalChanged)
1426 dumpUsedSet(FP);
1427
1429 if (LocalChanged)
1433 }
1434
1435 return Changed;
1436}
1437
1439 bool Changed = false;
1440
1441 for (Function &F : M)
1443
1444 return Changed;
1445}
1446
1448 bool Changed = false;
1449
1450 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1452
1453 return Changed;
1454}
1455
1457 bool Changed = false;
1458
1459 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1461
1462 return Changed;
1463}
1464
1465//===----------------------------------------------------------------------===//
1466// MPPassManager implementation
1467
1468/// Execute all of the passes scheduled for execution by invoking
1469/// runOnModule method. Keep track of whether any of the passes modifies
1470/// the module, and if so, return true.
1471bool
1472MPPassManager::runOnModule(Module &M) {
1473 llvm::TimeTraceScope TimeScope("OptModule", M.getName());
1474
1475 bool Changed = false;
1476
1477 // Initialize on-the-fly passes
1478 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1479 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1480 Changed |= FPP->doInitialization(M);
1481 }
1482
1483 // Initialize module passes
1484 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1485 Changed |= getContainedPass(Index)->doInitialization(M);
1486
1487 unsigned InstrCount;
1488 StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1489 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1490 // Collect the initial size of the module.
1491 if (EmitICRemark)
1492 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1493
1494 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1495 ModulePass *MP = getContainedPass(Index);
1496 bool LocalChanged = false;
1497
1498 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1499 dumpRequiredSet(MP);
1500
1501 initializeAnalysisImpl(MP);
1502
1503 {
1505 TimeRegion PassTimer(getPassTimer(MP));
1506
1507#ifdef EXPENSIVE_CHECKS
1508 uint64_t RefHash = MP->structuralHash(M);
1509#endif
1510
1511 LocalChanged |= MP->runOnModule(M);
1512
1513#ifdef EXPENSIVE_CHECKS
1514 assert((LocalChanged || (RefHash == MP->structuralHash(M))) &&
1515 "Pass modifies its input and doesn't report it.");
1516#endif
1517
1518 if (EmitICRemark) {
1519 // Update the size of the module.
1520 unsigned ModuleCount = M.getInstructionCount();
1521 if (ModuleCount != InstrCount) {
1522 int64_t Delta = static_cast<int64_t>(ModuleCount) -
1523 static_cast<int64_t>(InstrCount);
1524 emitInstrCountChangedRemark(MP, M, Delta, InstrCount,
1525 FunctionToInstrCount);
1526 InstrCount = ModuleCount;
1527 }
1528 }
1529 }
1530
1531 Changed |= LocalChanged;
1532 if (LocalChanged)
1533 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1534 M.getModuleIdentifier());
1535 dumpPreservedSet(MP);
1536 dumpUsedSet(MP);
1537
1538 verifyPreservedAnalysis(MP);
1539 if (LocalChanged)
1540 removeNotPreservedAnalysis(MP);
1541 recordAvailableAnalysis(MP);
1542 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1543 }
1544
1545 // Finalize module passes
1546 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1547 Changed |= getContainedPass(Index)->doFinalization(M);
1548
1549 // Finalize on-the-fly passes
1550 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1551 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1552 // We don't know when is the last time an on-the-fly pass is run,
1553 // so we need to releaseMemory / finalize here
1554 FPP->releaseMemoryOnTheFly();
1555 Changed |= FPP->doFinalization(M);
1556 }
1557
1558 return Changed;
1559}
1560
1561/// Add RequiredPass into list of lower level passes required by pass P.
1562/// RequiredPass is run on the fly by Pass Manager when P requests it
1563/// through getAnalysis interface.
1564void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1565 assert(RequiredPass && "No required pass?");
1566 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1567 "Unable to handle Pass that requires lower level Analysis pass");
1568 assert((P->getPotentialPassManagerType() <
1569 RequiredPass->getPotentialPassManagerType()) &&
1570 "Unable to handle Pass that requires lower level Analysis pass");
1571
1572 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1573 if (!FPP) {
1575 // FPP is the top level manager.
1576 FPP->setTopLevelManager(FPP);
1577
1578 OnTheFlyManagers[P] = FPP;
1579 }
1580 const PassInfo *RequiredPassPI =
1581 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1582
1583 Pass *FoundPass = nullptr;
1584 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1585 FoundPass =
1586 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1587 }
1588 if (!FoundPass) {
1589 FoundPass = RequiredPass;
1590 // This should be guaranteed to add RequiredPass to the passmanager given
1591 // that we checked for an available analysis above.
1592 FPP->add(RequiredPass);
1593 }
1594 // Register P as the last user of FoundPass or RequiredPass.
1596 LU.push_back(FoundPass);
1597 FPP->setLastUser(LU, P);
1598}
1599
1600/// Return function pass corresponding to PassInfo PI, that is
1601/// required by module pass MP. Instantiate analysis pass, by using
1602/// its runOnFunction() for function F.
1603std::tuple<Pass *, bool> MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI,
1604 Function &F) {
1605 legacy::FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1606 assert(FPP && "Unable to find on the fly pass");
1607
1608 FPP->releaseMemoryOnTheFly();
1609 bool Changed = FPP->run(F);
1610 return std::make_tuple(((PMTopLevelManager *)FPP)->findAnalysisPass(PI),
1611 Changed);
1612}
1613
1614namespace llvm {
1615namespace legacy {
1616
1617//===----------------------------------------------------------------------===//
1618// PassManager implementation
1619
1620/// Create new pass manager
1622 PM = new PassManagerImpl();
1623 // PM is the top level manager
1624 PM->setTopLevelManager(PM);
1625}
1626
1628 delete PM;
1629}
1630
1632 PM->add(P);
1633}
1634
1635/// run - Execute all of the passes scheduled for execution. Keep track of
1636/// whether any of the passes modifies the module, and if so, return true.
1638 return PM->run(M);
1639}
1640} // namespace legacy
1641} // namespace llvm
1642
1643//===----------------------------------------------------------------------===//
1644// PMStack implementation
1645//
1646
1647// Pop Pass Manager from the stack and clear its analysis info.
1649
1650 PMDataManager *Top = this->top();
1652
1653 S.pop_back();
1654}
1655
1656// Push PM on the stack and set its top level manager.
1658 assert(PM && "Unable to push. Pass Manager expected");
1659 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1660
1661 if (!this->empty()) {
1662 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1663 && "pushing bad pass manager to PMStack");
1664 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1665
1666 assert(TPM && "Unable to find top level manager");
1667 TPM->addIndirectPassManager(PM);
1668 PM->setTopLevelManager(TPM);
1669 PM->setDepth(this->top()->getDepth()+1);
1670 } else {
1673 && "pushing bad pass manager to PMStack");
1674 PM->setDepth(1);
1675 }
1676
1677 S.push_back(PM);
1678}
1679
1680// Dump content of the pass manager stack.
1682 for (PMDataManager *Manager : S)
1683 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1684
1685 if (!S.empty())
1686 dbgs() << '\n';
1687}
1688
1689/// Find appropriate Module Pass Manager in the PM Stack and
1690/// add self into that manager.
1692 PassManagerType PreferredType) {
1693 // Find Module Pass Manager
1695 while ((T = PMS.top()->getPassManagerType()) > PMT_ModulePassManager &&
1696 T != PreferredType)
1697 PMS.pop();
1698 PMS.top()->add(this);
1699}
1700
1701/// Find appropriate Function Pass Manager or Call Graph Pass Manager
1702/// in the PM Stack and add self into that manager.
1704 PassManagerType /*PreferredType*/) {
1705 // Find Function Pass Manager
1706 PMDataManager *PM;
1707 while (PM = PMS.top(), PM->getPassManagerType() > PMT_FunctionPassManager)
1708 PMS.pop();
1709
1710 // Create new Function Pass Manager if needed.
1712 // [1] Create new Function Pass Manager
1713 auto *FPP = new FPPassManager;
1714 FPP->populateInheritedAnalysis(PMS);
1715
1716 // [2] Set up new manager's top level manager
1718
1719 // [3] Assign manager to manage this new manager. This may create
1720 // and push new managers into PMS
1721 FPP->assignPassManager(PMS, PM->getPassManagerType());
1722
1723 // [4] Push new manager into PMS
1724 PMS.push(FPP);
1725 PM = FPP;
1726 }
1727
1728 // Assign FPP as the manager of this pass.
1729 PM->add(this);
1730}
1731
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
AMDGPU Lower Kernel Arguments
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
#define clEnumVal(ENUMVAL, DESC)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
static unsigned InstrCount
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
This file contains an interface for creating legacy passes to print out IR in various granularities.
Module.h This file contains the declarations for the Module class.
static cl::opt< enum PassDebugLevel > PassDebugging("debug-pass", cl::Hidden, cl::desc("Print legacy PassManager debugging information"), cl::values(clEnumVal(Disabled, "disable debug output"), clEnumVal(Arguments, "print pass arguments to pass to 'opt'"), clEnumVal(Structure, "print pass structure before run()"), clEnumVal(Executions, "print pass name before it is executed"), clEnumVal(Details, "print pass details when it is executed")))
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:598
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
#define T
#define P(N)
This header defines classes/functions to handle pass execution timing information with interfaces for...
static const PassInfo * getPassInfo(StringRef PassName)
static const char PassName[]
AnalysisResolver - Simple interface used by Pass objects to pull all analysis information out of pass...
void addAnalysisImplsPair(AnalysisID PI, Pass *P)
Pass * findImplPass(AnalysisID PI)
Find pass that is implementing PI.
PMDataManager & getPMDataManager()
void clearAnalysisImpls()
Clear cache that is used to connect a pass to the analysis (PassInfo).
LLVM_ABI Pass * getAnalysisIfAvailable(AnalysisID ID) const
Return analysis result or null if it doesn't exist.
Represent the analysis usage information of a pass.
const VectorType & getRequiredSet() const
const VectorType & getRequiredTransitiveSet() const
SmallVectorImpl< AnalysisID > VectorType
const VectorType & getUsedSet() const
bool getPreservesAll() const
Determine whether a pass said it does not transform its input at all.
const VectorType & getPreservedSet() const
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for error info classes.
Definition Error.h:44
FPPassManager manages BBPassManagers and FunctionPasses.
bool runOnFunction(Function &F)
run - Execute all of the passes scheduled for execution.
bool doInitialization(Module &M) override
doInitialization - Run all of the initializers for the function passes.
bool doFinalization(Module &M) override
doFinalization - Run all of the finalizers for the function passes.
FunctionPass * getContainedPass(unsigned N)
void dumpPassStructure(unsigned Offset) override
Print passes managed by this manager.
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
void cleanup()
cleanup - After running all passes, clean up pass manager cache.
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:208
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
void assignPassManager(PMStack &PMS, PassManagerType T) override
Find appropriate Function Pass Manager or Call Graph Pass Manager in the PM Stack and add self into t...
bool empty() const
Definition Function.h:859
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition Pass.h:285
typename VectorType::const_iterator const_iterator
Definition MapVector.h:45
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
void assignPassManager(PMStack &PMS, PassManagerType T) override
Find appropriate Module Pass Manager in the PM Stack and add self into that manager.
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Diagnostic information for optimization analysis remarks.
PMDataManager provides the common place to manage the analysis data used by pass managers.
void removeDeadPasses(Pass *P, StringRef Msg, enum PassDebuggingString)
Remove dead passes used by P.
void dumpLastUses(Pass *P, unsigned Offset) const
virtual Pass * getAsPass()=0
virtual std::tuple< Pass *, bool > getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F)
void setDepth(unsigned newDepth)
void recordAvailableAnalysis(Pass *P)
Augment AvailableAnalysis by adding analysis made available by pass P.
Pass * findAnalysisPass(AnalysisID AID, bool Direction)
Find the pass that implements Analysis AID.
bool isPassDebuggingExecutionsOrMore() const
isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions or higher is specified.
unsigned getDepth() const
SmallVector< Pass *, 16 > PassVector
DenseMap< AnalysisID, Pass * > * InheritedAnalysis[PMT_Last]
virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass)
Add RequiredPass into list of lower level passes required by pass P.
PMTopLevelManager * getTopLevelManager()
unsigned initSizeRemarkInfo(Module &M, StringMap< std::pair< unsigned, unsigned > > &FunctionToInstrCount)
Set the initial size of the module if the user has specified that they want remarks for size.
void setTopLevelManager(PMTopLevelManager *T)
void dumpRequiredSet(const Pass *P) const
void initializeAnalysisImpl(Pass *P)
All Required analyses should be available to the pass as it runs!
void verifyPreservedAnalysis(Pass *P)
verifyPreservedAnalysis – Verify analysis presreved by pass P.
void initializeAnalysisInfo()
Initialize available analysis information.
void freePass(Pass *P, StringRef Msg, enum PassDebuggingString)
Remove P.
bool preserveHigherLevelAnalysis(Pass *P)
unsigned getNumContainedPasses() const
virtual PassManagerType getPassManagerType() const
PMTopLevelManager * TPM
void emitInstrCountChangedRemark(Pass *P, Module &M, int64_t Delta, unsigned CountBefore, StringMap< std::pair< unsigned, unsigned > > &FunctionToInstrCount, Function *F=nullptr)
Emit a remark signifying that the number of IR instructions in the module changed.
void add(Pass *P, bool ProcessAnalysis=true)
Add pass P into the PassVector.
void collectRequiredAndUsedAnalyses(SmallVectorImpl< Pass * > &UsedPasses, SmallVectorImpl< AnalysisID > &ReqPassNotAvailable, Pass *P)
Populate UsedPasses with analysis pass that are used or required by pass P and are available.
void populateInheritedAnalysis(PMStack &PMS)
void dumpPreservedSet(const Pass *P) const
void dumpUsedSet(const Pass *P) const
void removeNotPreservedAnalysis(Pass *P)
Remove Analysis that is not preserved by the pass.
void dumpPassInfo(Pass *P, enum PassDebuggingString S1, enum PassDebuggingString S2, StringRef Msg)
PMStack - This class implements a stack data structure of PMDataManager pointers.
LLVM_ABI void pop()
PMDataManager * top() const
LLVM_ABI void dump() const
LLVM_ABI void push(PMDataManager *PM)
PMTopLevelManager manages LastUser info and collects common APIs used by top level pass managers.
void addIndirectPassManager(PMDataManager *Manager)
void addImmutablePass(ImmutablePass *P)
Add immutable pass and initialize it.
const PassInfo * findAnalysisPassInfo(AnalysisID AID) const
Retrieve the PassInfo for an analysis.
void setLastUser(ArrayRef< Pass * > AnalysisPasses, Pass *P)
Set pass P as the last user of the given analysis passes.
virtual ~PMTopLevelManager()
Destructor.
void schedulePass(Pass *P)
Schedule pass P for execution.
SmallVector< PMDataManager *, 8 > PassManagers
Collection of pass managers.
Pass * findAnalysisPass(AnalysisID AID)
Find the pass that implements Analysis AID.
AnalysisUsage * findAnalysisUsage(Pass *P)
Find analysis usage information for the pass P.
void addPassManager(PMDataManager *Manager)
unsigned getNumContainedManagers() const
SmallVectorImpl< ImmutablePass * > & getImmutablePasses()
PMTopLevelManager(PMDataManager *PMDM)
Initialize top level manager. Create first pass manager.
void collectLastUses(SmallVectorImpl< Pass * > &LastUses, Pass *P)
Collect passes whose last user is P.
PassInfo class - An instance of this class exists for every pass known by the system,...
Definition PassInfo.h:29
bool isAnalysis() const
Definition PassInfo.h:67
StringRef getPassArgument() const
getPassArgument - Return the command line option that may be passed to 'opt' that will cause this pas...
Definition PassInfo.h:58
StringRef getPassName() const
getPassName - Return the friendly name for the pass, never returns null
Definition PassInfo.h:53
Pass * createPass() const
createPass() - Use this method to create an instance of this pass.
Definition PassInfo.h:84
PassManagerPrettyStackEntry - This is used to print informative information about what pass is runnin...
void print(raw_ostream &OS) const override
print - Emit information about this stack frame to OS.
Manages a sequence of passes over a particular unit of IR.
PreservedAnalyses run(Function &IR, AnalysisManager< Function > &AM, ExtraArgTs... ExtraArgs)
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVM_ABI const PassInfo * getPassInfo(const void *TI) const
getPassInfo - Look up a pass' corresponding PassInfo, indexed by the pass' type identifier (&MyPass::...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
virtual PassManagerType getPotentialPassManagerType() const
Return what kind of Pass Manager can manage this pass.
Definition Pass.cpp:107
Pass(PassKind K, char &pid)
Definition Pass.h:105
AnalysisID getPassID() const
getPassID - Return the PassID number that corresponds to this pass.
Definition Pass.h:122
virtual void assignPassManager(PMStack &, PassManagerType)
Each pass is responsible for assigning a pass manager to itself.
Definition Pass.h:151
AnalysisResolver * getResolver() const
Definition Pass.h:162
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Definition Pass.h:128
virtual bool doFinalization(Module &)
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
Definition Pass.h:132
virtual void dumpPassStructure(unsigned Offset=0)
Definition Pass.cpp:78
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition Pass.cpp:85
virtual void releaseMemory()
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition Pass.cpp:116
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The TimeRegion class is used as a helper class to call the startTimer() and stopTimer() methods of th...
Definition Timer.h:155
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
FunctionPassManagerImpl manages FPPassManagers.
Pass * createPrinterPass(raw_ostream &O, const std::string &Banner) const override
createPrinterPass - Get a function printer pass.
FPPassManager * getContainedManager(unsigned N)
bool doInitialization(Module &M) override
doInitialization - Run all of the initializers for the function passes.
PMDataManager * getAsPMDataManager() override
void dumpPassStructure(unsigned Offset) override
bool run(Function &F)
run - Execute all of the passes scheduled for execution.
bool doFinalization(Module &M) override
doFinalization - Run all of the finalizers for the function passes.
PassManagerType getTopLevelPassManagerType() override
void getAnalysisUsage(AnalysisUsage &Info) const override
Pass Manager itself does not invalidate any analysis info.
PassManagerImpl manages MPPassManagers.
PassManagerType getTopLevelPassManagerType() override
void getAnalysisUsage(AnalysisUsage &Info) const override
Pass Manager itself does not invalidate any analysis info.
void add(Pass *P)
Add a pass to the queue of passes to run.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
PMDataManager * getAsPMDataManager() override
MPPassManager * getContainedManager(unsigned N)
Pass * createPrinterPass(raw_ostream &O, const std::string &Banner) const override
createPrinterPass - Get a module printer pass.
void add(Pass *P) override
Add a pass to the queue of passes to run.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
PassManager()
Create new pass manager.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
LLVM_ABI bool debugPassSpecified()
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:557
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1731
@ PT_PassManager
Definition Pass.h:73
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
PassManagerType
Different types of internal pass managers.
Definition Pass.h:56
@ PMT_ModulePassManager
MPPassManager.
Definition Pass.h:58
@ PMT_FunctionPassManager
FPPassManager.
Definition Pass.h:60
LLVM_ABI Timer * getPassTimer(Pass *)
Request the timer for this legacy-pass-manager's pass instance.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI ModulePass * createPrintModulePass(raw_ostream &OS, const std::string &Banner="", bool ShouldPreserveUseListOrder=false)
Create and return a pass that writes the module to the specified raw_ostream.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1771
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
bool shouldPrintBeforePass(StringRef PassID)
bool shouldPrintAfterPass(StringRef PassID)
@ Disabled
Don't do any conversion of .debug_str_offsets tables.
Definition DWP.h:31
LLVM_ABI FunctionPass * createPrintFunctionPass(raw_ostream &OS, const std::string &Banner="")
Create and return a pass that prints functions to the specified raw_ostream as they are processed.
const void * AnalysisID
Definition Pass.h:51
#define N
Used in the streaming interface as the general argument type.