1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the legacy LLVM Pass Manager infrastructure.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/LegacyPassManager.h"
15 #include "llvm/ADT/MapVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/IR/DiagnosticInfo.h"
18 #include "llvm/IR/IRPrintingPasses.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/LegacyPassManagers.h"
21 #include "llvm/IR/LegacyPassNameParser.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/PassTimingInfo.h"
24 #include "llvm/Support/Chrono.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/Mutex.h"
31 #include "llvm/Support/Timer.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 #include <unordered_set>
35 using namespace llvm;
36 using namespace llvm::legacy;
37 
38 // See PassManagers.h for Pass Manager infrastructure overview.
39 
40 //===----------------------------------------------------------------------===//
41 // Pass debugging information.  Often it is useful to find out what pass is
42 // running when a crash occurs in a utility.  When this library is compiled with
43 // debugging on, a command line option (--debug-pass) is enabled that causes the
44 // pass name to be printed before it executes.
45 //
46 
47 namespace {
48 // Different debug levels that can be enabled...
49 enum PassDebugLevel {
50   Disabled, Arguments, Structure, Executions, Details
51 };
52 }
53 
54 static cl::opt<enum PassDebugLevel>
55 PassDebugging("debug-pass", cl::Hidden,
56                   cl::desc("Print PassManager debugging information"),
57                   cl::values(
58   clEnumVal(Disabled  , "disable debug output"),
59   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
60   clEnumVal(Structure , "print pass structure before run()"),
61   clEnumVal(Executions, "print pass name before it is executed"),
62   clEnumVal(Details   , "print pass details when it is executed")));
63 
64 namespace {
65 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
66 PassOptionList;
67 }
68 
69 // Print IR out before/after specified passes.
70 static PassOptionList
71 PrintBefore("print-before",
72             llvm::cl::desc("Print IR before specified passes"),
73             cl::Hidden);
74 
75 static PassOptionList
76 PrintAfter("print-after",
77            llvm::cl::desc("Print IR after specified passes"),
78            cl::Hidden);
79 
80 static cl::opt<bool> PrintBeforeAll("print-before-all",
81                                     llvm::cl::desc("Print IR before each pass"),
82                                     cl::init(false), cl::Hidden);
83 static cl::opt<bool> PrintAfterAll("print-after-all",
84                                    llvm::cl::desc("Print IR after each pass"),
85                                    cl::init(false), cl::Hidden);
86 
87 static cl::opt<bool>
88     PrintModuleScope("print-module-scope",
89                      cl::desc("When printing IR for print-[before|after]{-all} "
90                               "always print a module IR"),
91                      cl::init(false), cl::Hidden);
92 
93 static cl::list<std::string>
94     PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
95                    cl::desc("Only print IR for functions whose name "
96                             "match this for all print-[before|after][-all] "
97                             "options"),
98                    cl::CommaSeparated, cl::Hidden);
99 
100 /// This is a helper to determine whether to print IR before or
101 /// after a pass.
102 
103 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
104                                          PassOptionList &PassesToPrint) {
105   for (auto *PassInf : PassesToPrint) {
106     if (PassInf)
107       if (PassInf->getPassArgument() == PI->getPassArgument()) {
108         return true;
109       }
110   }
111   return false;
112 }
113 
114 /// This is a utility to check whether a pass should have IR dumped
115 /// before it.
116 static bool ShouldPrintBeforePass(const PassInfo *PI) {
117   return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
118 }
119 
120 /// This is a utility to check whether a pass should have IR dumped
121 /// after it.
122 static bool ShouldPrintAfterPass(const PassInfo *PI) {
123   return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
124 }
125 
126 bool llvm::forcePrintModuleIR() { return PrintModuleScope; }
127 
128 bool llvm::isFunctionInPrintList(StringRef FunctionName) {
129   static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
130                                                         PrintFuncsList.end());
131   return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName);
132 }
133 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
134 /// or higher is specified.
135 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
136   return PassDebugging >= Executions;
137 }
138 
139 unsigned PMDataManager::initSizeRemarkInfo(Module &M) {
140   // Only calculate getInstructionCount if the size-info remark is requested.
141   return M.getInstructionCount();
142 }
143 
144 void PMDataManager::emitInstrCountChangedRemark(Pass *P, Module &M,
145                                                 unsigned CountBefore) {
146   // We need a function containing at least one basic block in order to output
147   // remarks. Since it's possible that the first function in the module doesn't
148   // actually contain a basic block, we have to go and find one that's suitable
149   // for emitting remarks.
150   auto It = std::find_if(M.begin(), M.end(),
151                          [](const Function &Fn) { return !Fn.empty(); });
152 
153   // Didn't find a function. Quit.
154   if (It == M.end())
155     return;
156 
157   // We found a function containing at least one basic block.
158   Function *F = &*It;
159 
160   // How many instructions are in the module now?
161   unsigned CountAfter = M.getInstructionCount();
162 
163   // If there was no change, don't emit a remark.
164   if (CountBefore == CountAfter)
165     return;
166 
167   // If it's a pass manager, don't emit a remark. (This hinges on the assumption
168   // that the only passes that return non-null with getAsPMDataManager are pass
169   // managers.) The reason we have to do this is to avoid emitting remarks for
170   // CGSCC passes.
171   if (P->getAsPMDataManager())
172     return;
173 
174   // Compute a possibly negative delta between the instruction count before
175   // running P, and after running P.
176   int64_t Delta =
177       static_cast<int64_t>(CountAfter) - static_cast<int64_t>(CountBefore);
178 
179   BasicBlock &BB = *F->begin();
180   OptimizationRemarkAnalysis R("size-info", "IRSizeChange",
181                                DiagnosticLocation(), &BB);
182   // FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This
183   // would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.
184   R << DiagnosticInfoOptimizationBase::Argument("Pass", P->getPassName())
185     << ": IR instruction count changed from "
186     << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore)
187     << " to "
188     << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter)
189     << "; Delta: "
190     << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta);
191   F->getContext().diagnose(R); // Not using ORE for layering reasons.
192 }
193 
194 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
195   if (!V && !M)
196     OS << "Releasing pass '";
197   else
198     OS << "Running pass '";
199 
200   OS << P->getPassName() << "'";
201 
202   if (M) {
203     OS << " on module '" << M->getModuleIdentifier() << "'.\n";
204     return;
205   }
206   if (!V) {
207     OS << '\n';
208     return;
209   }
210 
211   OS << " on ";
212   if (isa<Function>(V))
213     OS << "function";
214   else if (isa<BasicBlock>(V))
215     OS << "basic block";
216   else
217     OS << "value";
218 
219   OS << " '";
220   V->printAsOperand(OS, /*PrintTy=*/false, M);
221   OS << "'\n";
222 }
223 
224 
225 namespace {
226 //===----------------------------------------------------------------------===//
227 // BBPassManager
228 //
229 /// BBPassManager manages BasicBlockPass. It batches all the
230 /// pass together and sequence them to process one basic block before
231 /// processing next basic block.
232 class BBPassManager : public PMDataManager, public FunctionPass {
233 
234 public:
235   static char ID;
236   explicit BBPassManager()
237     : PMDataManager(), FunctionPass(ID) {}
238 
239   /// Execute all of the passes scheduled for execution.  Keep track of
240   /// whether any of the passes modifies the function, and if so, return true.
241   bool runOnFunction(Function &F) override;
242 
243   /// Pass Manager itself does not invalidate any analysis info.
244   void getAnalysisUsage(AnalysisUsage &Info) const override {
245     Info.setPreservesAll();
246   }
247 
248   bool doInitialization(Module &M) override;
249   bool doInitialization(Function &F);
250   bool doFinalization(Module &M) override;
251   bool doFinalization(Function &F);
252 
253   PMDataManager *getAsPMDataManager() override { return this; }
254   Pass *getAsPass() override { return this; }
255 
256   StringRef getPassName() const override { return "BasicBlock Pass Manager"; }
257 
258   // Print passes managed by this manager
259   void dumpPassStructure(unsigned Offset) override {
260     dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
261     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
262       BasicBlockPass *BP = getContainedPass(Index);
263       BP->dumpPassStructure(Offset + 1);
264       dumpLastUses(BP, Offset+1);
265     }
266   }
267 
268   BasicBlockPass *getContainedPass(unsigned N) {
269     assert(N < PassVector.size() && "Pass number out of range!");
270     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
271     return BP;
272   }
273 
274   PassManagerType getPassManagerType() const override {
275     return PMT_BasicBlockPassManager;
276   }
277 };
278 
279 char BBPassManager::ID = 0;
280 } // End anonymous namespace
281 
282 namespace llvm {
283 namespace legacy {
284 //===----------------------------------------------------------------------===//
285 // FunctionPassManagerImpl
286 //
287 /// FunctionPassManagerImpl manages FPPassManagers
288 class FunctionPassManagerImpl : public Pass,
289                                 public PMDataManager,
290                                 public PMTopLevelManager {
291   virtual void anchor();
292 private:
293   bool wasRun;
294 public:
295   static char ID;
296   explicit FunctionPassManagerImpl() :
297     Pass(PT_PassManager, ID), PMDataManager(),
298     PMTopLevelManager(new FPPassManager()), wasRun(false) {}
299 
300   /// \copydoc FunctionPassManager::add()
301   void add(Pass *P) {
302     schedulePass(P);
303   }
304 
305   /// createPrinterPass - Get a function printer pass.
306   Pass *createPrinterPass(raw_ostream &O,
307                           const std::string &Banner) const override {
308     return createPrintFunctionPass(O, Banner);
309   }
310 
311   // Prepare for running an on the fly pass, freeing memory if needed
312   // from a previous run.
313   void releaseMemoryOnTheFly();
314 
315   /// run - Execute all of the passes scheduled for execution.  Keep track of
316   /// whether any of the passes modifies the module, and if so, return true.
317   bool run(Function &F);
318 
319   /// doInitialization - Run all of the initializers for the function passes.
320   ///
321   bool doInitialization(Module &M) override;
322 
323   /// doFinalization - Run all of the finalizers for the function passes.
324   ///
325   bool doFinalization(Module &M) override;
326 
327 
328   PMDataManager *getAsPMDataManager() override { return this; }
329   Pass *getAsPass() override { return this; }
330   PassManagerType getTopLevelPassManagerType() override {
331     return PMT_FunctionPassManager;
332   }
333 
334   /// Pass Manager itself does not invalidate any analysis info.
335   void getAnalysisUsage(AnalysisUsage &Info) const override {
336     Info.setPreservesAll();
337   }
338 
339   FPPassManager *getContainedManager(unsigned N) {
340     assert(N < PassManagers.size() && "Pass number out of range!");
341     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
342     return FP;
343   }
344 };
345 
346 void FunctionPassManagerImpl::anchor() {}
347 
348 char FunctionPassManagerImpl::ID = 0;
349 } // End of legacy namespace
350 } // End of llvm namespace
351 
352 namespace {
353 //===----------------------------------------------------------------------===//
354 // MPPassManager
355 //
356 /// MPPassManager manages ModulePasses and function pass managers.
357 /// It batches all Module passes and function pass managers together and
358 /// sequences them to process one module.
359 class MPPassManager : public Pass, public PMDataManager {
360 public:
361   static char ID;
362   explicit MPPassManager() :
363     Pass(PT_PassManager, ID), PMDataManager() { }
364 
365   // Delete on the fly managers.
366   ~MPPassManager() override {
367     for (auto &OnTheFlyManager : OnTheFlyManagers) {
368       FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
369       delete FPP;
370     }
371   }
372 
373   /// createPrinterPass - Get a module printer pass.
374   Pass *createPrinterPass(raw_ostream &O,
375                           const std::string &Banner) const override {
376     return createPrintModulePass(O, Banner);
377   }
378 
379   /// run - Execute all of the passes scheduled for execution.  Keep track of
380   /// whether any of the passes modifies the module, and if so, return true.
381   bool runOnModule(Module &M);
382 
383   using llvm::Pass::doInitialization;
384   using llvm::Pass::doFinalization;
385 
386   /// Pass Manager itself does not invalidate any analysis info.
387   void getAnalysisUsage(AnalysisUsage &Info) const override {
388     Info.setPreservesAll();
389   }
390 
391   /// Add RequiredPass into list of lower level passes required by pass P.
392   /// RequiredPass is run on the fly by Pass Manager when P requests it
393   /// through getAnalysis interface.
394   void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
395 
396   /// Return function pass corresponding to PassInfo PI, that is
397   /// required by module pass MP. Instantiate analysis pass, by using
398   /// its runOnFunction() for function F.
399   Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
400 
401   StringRef getPassName() const override { return "Module Pass Manager"; }
402 
403   PMDataManager *getAsPMDataManager() override { return this; }
404   Pass *getAsPass() override { return this; }
405 
406   // Print passes managed by this manager
407   void dumpPassStructure(unsigned Offset) override {
408     dbgs().indent(Offset*2) << "ModulePass Manager\n";
409     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
410       ModulePass *MP = getContainedPass(Index);
411       MP->dumpPassStructure(Offset + 1);
412       MapVector<Pass *, FunctionPassManagerImpl *>::const_iterator I =
413           OnTheFlyManagers.find(MP);
414       if (I != OnTheFlyManagers.end())
415         I->second->dumpPassStructure(Offset + 2);
416       dumpLastUses(MP, Offset+1);
417     }
418   }
419 
420   ModulePass *getContainedPass(unsigned N) {
421     assert(N < PassVector.size() && "Pass number out of range!");
422     return static_cast<ModulePass *>(PassVector[N]);
423   }
424 
425   PassManagerType getPassManagerType() const override {
426     return PMT_ModulePassManager;
427   }
428 
429  private:
430   /// Collection of on the fly FPPassManagers. These managers manage
431   /// function passes that are required by module passes.
432    MapVector<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
433 };
434 
435 char MPPassManager::ID = 0;
436 } // End anonymous namespace
437 
438 namespace llvm {
439 namespace legacy {
440 //===----------------------------------------------------------------------===//
441 // PassManagerImpl
442 //
443 
444 /// PassManagerImpl manages MPPassManagers
445 class PassManagerImpl : public Pass,
446                         public PMDataManager,
447                         public PMTopLevelManager {
448   virtual void anchor();
449 
450 public:
451   static char ID;
452   explicit PassManagerImpl() :
453     Pass(PT_PassManager, ID), PMDataManager(),
454                               PMTopLevelManager(new MPPassManager()) {}
455 
456   /// \copydoc PassManager::add()
457   void add(Pass *P) {
458     schedulePass(P);
459   }
460 
461   /// createPrinterPass - Get a module printer pass.
462   Pass *createPrinterPass(raw_ostream &O,
463                           const std::string &Banner) const override {
464     return createPrintModulePass(O, Banner);
465   }
466 
467   /// run - Execute all of the passes scheduled for execution.  Keep track of
468   /// whether any of the passes modifies the module, and if so, return true.
469   bool run(Module &M);
470 
471   using llvm::Pass::doInitialization;
472   using llvm::Pass::doFinalization;
473 
474   /// Pass Manager itself does not invalidate any analysis info.
475   void getAnalysisUsage(AnalysisUsage &Info) const override {
476     Info.setPreservesAll();
477   }
478 
479   PMDataManager *getAsPMDataManager() override { return this; }
480   Pass *getAsPass() override { return this; }
481   PassManagerType getTopLevelPassManagerType() override {
482     return PMT_ModulePassManager;
483   }
484 
485   MPPassManager *getContainedManager(unsigned N) {
486     assert(N < PassManagers.size() && "Pass number out of range!");
487     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
488     return MP;
489   }
490 };
491 
492 void PassManagerImpl::anchor() {}
493 
494 char PassManagerImpl::ID = 0;
495 } // End of legacy namespace
496 } // End of llvm namespace
497 
498 //===----------------------------------------------------------------------===//
499 // PMTopLevelManager implementation
500 
501 /// Initialize top level manager. Create first pass manager.
502 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
503   PMDM->setTopLevelManager(this);
504   addPassManager(PMDM);
505   activeStack.push(PMDM);
506 }
507 
508 /// Set pass P as the last user of the given analysis passes.
509 void
510 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
511   unsigned PDepth = 0;
512   if (P->getResolver())
513     PDepth = P->getResolver()->getPMDataManager().getDepth();
514 
515   for (Pass *AP : AnalysisPasses) {
516     LastUser[AP] = P;
517 
518     if (P == AP)
519       continue;
520 
521     // Update the last users of passes that are required transitive by AP.
522     AnalysisUsage *AnUsage = findAnalysisUsage(AP);
523     const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
524     SmallVector<Pass *, 12> LastUses;
525     SmallVector<Pass *, 12> LastPMUses;
526     for (AnalysisID ID : IDs) {
527       Pass *AnalysisPass = findAnalysisPass(ID);
528       assert(AnalysisPass && "Expected analysis pass to exist.");
529       AnalysisResolver *AR = AnalysisPass->getResolver();
530       assert(AR && "Expected analysis resolver to exist.");
531       unsigned APDepth = AR->getPMDataManager().getDepth();
532 
533       if (PDepth == APDepth)
534         LastUses.push_back(AnalysisPass);
535       else if (PDepth > APDepth)
536         LastPMUses.push_back(AnalysisPass);
537     }
538 
539     setLastUser(LastUses, P);
540 
541     // If this pass has a corresponding pass manager, push higher level
542     // analysis to this pass manager.
543     if (P->getResolver())
544       setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
545 
546 
547     // If AP is the last user of other passes then make P last user of
548     // such passes.
549     for (auto LU : LastUser) {
550       if (LU.second == AP)
551         // DenseMap iterator is not invalidated here because
552         // this is just updating existing entries.
553         LastUser[LU.first] = P;
554     }
555   }
556 }
557 
558 /// Collect passes whose last user is P
559 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
560                                         Pass *P) {
561   DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
562     InversedLastUser.find(P);
563   if (DMI == InversedLastUser.end())
564     return;
565 
566   SmallPtrSet<Pass *, 8> &LU = DMI->second;
567   for (Pass *LUP : LU) {
568     LastUses.push_back(LUP);
569   }
570 
571 }
572 
573 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
574   AnalysisUsage *AnUsage = nullptr;
575   auto DMI = AnUsageMap.find(P);
576   if (DMI != AnUsageMap.end())
577     AnUsage = DMI->second;
578   else {
579     // Look up the analysis usage from the pass instance (different instances
580     // of the same pass can produce different results), but unique the
581     // resulting object to reduce memory usage.  This helps to greatly reduce
582     // memory usage when we have many instances of only a few pass types
583     // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
584     // of dependencies.
585     AnalysisUsage AU;
586     P->getAnalysisUsage(AU);
587 
588     AUFoldingSetNode* Node = nullptr;
589     FoldingSetNodeID ID;
590     AUFoldingSetNode::Profile(ID, AU);
591     void *IP = nullptr;
592     if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
593       Node = N;
594     else {
595       Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
596       UniqueAnalysisUsages.InsertNode(Node, IP);
597     }
598     assert(Node && "cached analysis usage must be non null");
599 
600     AnUsageMap[P] = &Node->AU;
601     AnUsage = &Node->AU;
602   }
603   return AnUsage;
604 }
605 
606 /// Schedule pass P for execution. Make sure that passes required by
607 /// P are run before P is run. Update analysis info maintained by
608 /// the manager. Remove dead passes. This is a recursive function.
609 void PMTopLevelManager::schedulePass(Pass *P) {
610 
611   // TODO : Allocate function manager for this pass, other wise required set
612   // may be inserted into previous function manager
613 
614   // Give pass a chance to prepare the stage.
615   P->preparePassManager(activeStack);
616 
617   // If P is an analysis pass and it is available then do not
618   // generate the analysis again. Stale analysis info should not be
619   // available at this point.
620   const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
621   if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
622     // Remove any cached AnalysisUsage information.
623     AnUsageMap.erase(P);
624     delete P;
625     return;
626   }
627 
628   AnalysisUsage *AnUsage = findAnalysisUsage(P);
629 
630   bool checkAnalysis = true;
631   while (checkAnalysis) {
632     checkAnalysis = false;
633 
634     const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
635     for (const AnalysisID ID : RequiredSet) {
636 
637       Pass *AnalysisPass = findAnalysisPass(ID);
638       if (!AnalysisPass) {
639         const PassInfo *PI = findAnalysisPassInfo(ID);
640 
641         if (!PI) {
642           // Pass P is not in the global PassRegistry
643           dbgs() << "Pass '"  << P->getPassName() << "' is not initialized." << "\n";
644           dbgs() << "Verify if there is a pass dependency cycle." << "\n";
645           dbgs() << "Required Passes:" << "\n";
646           for (const AnalysisID ID2 : RequiredSet) {
647             if (ID == ID2)
648               break;
649             Pass *AnalysisPass2 = findAnalysisPass(ID2);
650             if (AnalysisPass2) {
651               dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
652             } else {
653               dbgs() << "\t"   << "Error: Required pass not found! Possible causes:"  << "\n";
654               dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)"    << "\n";
655               dbgs() << "\t\t" << "- Corruption of the global PassRegistry"           << "\n";
656             }
657           }
658         }
659 
660         assert(PI && "Expected required passes to be initialized");
661         AnalysisPass = PI->createPass();
662         if (P->getPotentialPassManagerType () ==
663             AnalysisPass->getPotentialPassManagerType())
664           // Schedule analysis pass that is managed by the same pass manager.
665           schedulePass(AnalysisPass);
666         else if (P->getPotentialPassManagerType () >
667                  AnalysisPass->getPotentialPassManagerType()) {
668           // Schedule analysis pass that is managed by a new manager.
669           schedulePass(AnalysisPass);
670           // Recheck analysis passes to ensure that required analyses that
671           // are already checked are still available.
672           checkAnalysis = true;
673         } else
674           // Do not schedule this analysis. Lower level analysis
675           // passes are run on the fly.
676           delete AnalysisPass;
677       }
678     }
679   }
680 
681   // Now all required passes are available.
682   if (ImmutablePass *IP = P->getAsImmutablePass()) {
683     // P is a immutable pass and it will be managed by this
684     // top level manager. Set up analysis resolver to connect them.
685     PMDataManager *DM = getAsPMDataManager();
686     AnalysisResolver *AR = new AnalysisResolver(*DM);
687     P->setResolver(AR);
688     DM->initializeAnalysisImpl(P);
689     addImmutablePass(IP);
690     DM->recordAvailableAnalysis(IP);
691     return;
692   }
693 
694   if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
695     Pass *PP = P->createPrinterPass(
696         dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
697     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
698   }
699 
700   // Add the requested pass to the best available pass manager.
701   P->assignPassManager(activeStack, getTopLevelPassManagerType());
702 
703   if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
704     Pass *PP = P->createPrinterPass(
705         dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
706     PP->assignPassManager(activeStack, getTopLevelPassManagerType());
707   }
708 }
709 
710 /// Find the pass that implements Analysis AID. Search immutable
711 /// passes and all pass managers. If desired pass is not found
712 /// then return NULL.
713 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
714   // For immutable passes we have a direct mapping from ID to pass, so check
715   // that first.
716   if (Pass *P = ImmutablePassMap.lookup(AID))
717     return P;
718 
719   // Check pass managers
720   for (PMDataManager *PassManager : PassManagers)
721     if (Pass *P = PassManager->findAnalysisPass(AID, false))
722       return P;
723 
724   // Check other pass managers
725   for (PMDataManager *IndirectPassManager : IndirectPassManagers)
726     if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
727       return P;
728 
729   return nullptr;
730 }
731 
732 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
733   const PassInfo *&PI = AnalysisPassInfos[AID];
734   if (!PI)
735     PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
736   else
737     assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
738            "The pass info pointer changed for an analysis ID!");
739 
740   return PI;
741 }
742 
743 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
744   P->initializePass();
745   ImmutablePasses.push_back(P);
746 
747   // Add this pass to the map from its analysis ID. We clobber any prior runs
748   // of the pass in the map so that the last one added is the one found when
749   // doing lookups.
750   AnalysisID AID = P->getPassID();
751   ImmutablePassMap[AID] = P;
752 
753   // Also add any interfaces implemented by the immutable pass to the map for
754   // fast lookup.
755   const PassInfo *PassInf = findAnalysisPassInfo(AID);
756   assert(PassInf && "Expected all immutable passes to be initialized");
757   for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
758     ImmutablePassMap[ImmPI->getTypeInfo()] = P;
759 }
760 
761 // Print passes managed by this top level manager.
762 void PMTopLevelManager::dumpPasses() const {
763 
764   if (PassDebugging < Structure)
765     return;
766 
767   // Print out the immutable passes
768   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
769     ImmutablePasses[i]->dumpPassStructure(0);
770   }
771 
772   // Every class that derives from PMDataManager also derives from Pass
773   // (sometimes indirectly), but there's no inheritance relationship
774   // between PMDataManager and Pass, so we have to getAsPass to get
775   // from a PMDataManager* to a Pass*.
776   for (PMDataManager *Manager : PassManagers)
777     Manager->getAsPass()->dumpPassStructure(1);
778 }
779 
780 void PMTopLevelManager::dumpArguments() const {
781 
782   if (PassDebugging < Arguments)
783     return;
784 
785   dbgs() << "Pass Arguments: ";
786   for (ImmutablePass *P : ImmutablePasses)
787     if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
788       assert(PI && "Expected all immutable passes to be initialized");
789       if (!PI->isAnalysisGroup())
790         dbgs() << " -" << PI->getPassArgument();
791     }
792   for (PMDataManager *PM : PassManagers)
793     PM->dumpPassArguments();
794   dbgs() << "\n";
795 }
796 
797 void PMTopLevelManager::initializeAllAnalysisInfo() {
798   for (PMDataManager *PM : PassManagers)
799     PM->initializeAnalysisInfo();
800 
801   // Initailize other pass managers
802   for (PMDataManager *IPM : IndirectPassManagers)
803     IPM->initializeAnalysisInfo();
804 
805   for (auto LU : LastUser) {
806     SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
807     L.insert(LU.first);
808   }
809 }
810 
811 /// Destructor
812 PMTopLevelManager::~PMTopLevelManager() {
813   for (PMDataManager *PM : PassManagers)
814     delete PM;
815 
816   for (ImmutablePass *P : ImmutablePasses)
817     delete P;
818 }
819 
820 //===----------------------------------------------------------------------===//
821 // PMDataManager implementation
822 
823 /// Augement AvailableAnalysis by adding analysis made available by pass P.
824 void PMDataManager::recordAvailableAnalysis(Pass *P) {
825   AnalysisID PI = P->getPassID();
826 
827   AvailableAnalysis[PI] = P;
828 
829   assert(!AvailableAnalysis.empty());
830 
831   // This pass is the current implementation of all of the interfaces it
832   // implements as well.
833   const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
834   if (!PInf) return;
835   const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
836   for (unsigned i = 0, e = II.size(); i != e; ++i)
837     AvailableAnalysis[II[i]->getTypeInfo()] = P;
838 }
839 
840 // Return true if P preserves high level analysis used by other
841 // passes managed by this manager
842 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
843   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
844   if (AnUsage->getPreservesAll())
845     return true;
846 
847   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
848   for (Pass *P1 : HigherLevelAnalysis) {
849     if (P1->getAsImmutablePass() == nullptr &&
850         !is_contained(PreservedSet, P1->getPassID()))
851       return false;
852   }
853 
854   return true;
855 }
856 
857 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
858 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
859   // Don't do this unless assertions are enabled.
860 #ifdef NDEBUG
861   return;
862 #endif
863   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
864   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
865 
866   // Verify preserved analysis
867   for (AnalysisID AID : PreservedSet) {
868     if (Pass *AP = findAnalysisPass(AID, true)) {
869       TimeRegion PassTimer(getPassTimer(AP));
870       AP->verifyAnalysis();
871     }
872   }
873 }
874 
875 /// Remove Analysis not preserved by Pass P
876 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
877   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
878   if (AnUsage->getPreservesAll())
879     return;
880 
881   const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
882   for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
883          E = AvailableAnalysis.end(); I != E; ) {
884     DenseMap<AnalysisID, Pass*>::iterator Info = I++;
885     if (Info->second->getAsImmutablePass() == nullptr &&
886         !is_contained(PreservedSet, Info->first)) {
887       // Remove this analysis
888       if (PassDebugging >= Details) {
889         Pass *S = Info->second;
890         dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
891         dbgs() << S->getPassName() << "'\n";
892       }
893       AvailableAnalysis.erase(Info);
894     }
895   }
896 
897   // Check inherited analysis also. If P is not preserving analysis
898   // provided by parent manager then remove it here.
899   for (unsigned Index = 0; Index < PMT_Last; ++Index) {
900 
901     if (!InheritedAnalysis[Index])
902       continue;
903 
904     for (DenseMap<AnalysisID, Pass*>::iterator
905            I = InheritedAnalysis[Index]->begin(),
906            E = InheritedAnalysis[Index]->end(); I != E; ) {
907       DenseMap<AnalysisID, Pass *>::iterator Info = I++;
908       if (Info->second->getAsImmutablePass() == nullptr &&
909           !is_contained(PreservedSet, Info->first)) {
910         // Remove this analysis
911         if (PassDebugging >= Details) {
912           Pass *S = Info->second;
913           dbgs() << " -- '" <<  P->getPassName() << "' is not preserving '";
914           dbgs() << S->getPassName() << "'\n";
915         }
916         InheritedAnalysis[Index]->erase(Info);
917       }
918     }
919   }
920 }
921 
922 /// Remove analysis passes that are not used any longer
923 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
924                                      enum PassDebuggingString DBG_STR) {
925 
926   SmallVector<Pass *, 12> DeadPasses;
927 
928   // If this is a on the fly manager then it does not have TPM.
929   if (!TPM)
930     return;
931 
932   TPM->collectLastUses(DeadPasses, P);
933 
934   if (PassDebugging >= Details && !DeadPasses.empty()) {
935     dbgs() << " -*- '" <<  P->getPassName();
936     dbgs() << "' is the last user of following pass instances.";
937     dbgs() << " Free these instances\n";
938   }
939 
940   for (Pass *P : DeadPasses)
941     freePass(P, Msg, DBG_STR);
942 }
943 
944 void PMDataManager::freePass(Pass *P, StringRef Msg,
945                              enum PassDebuggingString DBG_STR) {
946   dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
947 
948   {
949     // If the pass crashes releasing memory, remember this.
950     PassManagerPrettyStackEntry X(P);
951     TimeRegion PassTimer(getPassTimer(P));
952 
953     P->releaseMemory();
954   }
955 
956   AnalysisID PI = P->getPassID();
957   if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
958     // Remove the pass itself (if it is not already removed).
959     AvailableAnalysis.erase(PI);
960 
961     // Remove all interfaces this pass implements, for which it is also
962     // listed as the available implementation.
963     const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
964     for (unsigned i = 0, e = II.size(); i != e; ++i) {
965       DenseMap<AnalysisID, Pass*>::iterator Pos =
966         AvailableAnalysis.find(II[i]->getTypeInfo());
967       if (Pos != AvailableAnalysis.end() && Pos->second == P)
968         AvailableAnalysis.erase(Pos);
969     }
970   }
971 }
972 
973 /// Add pass P into the PassVector. Update
974 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
975 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
976   // This manager is going to manage pass P. Set up analysis resolver
977   // to connect them.
978   AnalysisResolver *AR = new AnalysisResolver(*this);
979   P->setResolver(AR);
980 
981   // If a FunctionPass F is the last user of ModulePass info M
982   // then the F's manager, not F, records itself as a last user of M.
983   SmallVector<Pass *, 12> TransferLastUses;
984 
985   if (!ProcessAnalysis) {
986     // Add pass
987     PassVector.push_back(P);
988     return;
989   }
990 
991   // At the moment, this pass is the last user of all required passes.
992   SmallVector<Pass *, 12> LastUses;
993   SmallVector<Pass *, 8> UsedPasses;
994   SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
995 
996   unsigned PDepth = this->getDepth();
997 
998   collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
999   for (Pass *PUsed : UsedPasses) {
1000     unsigned RDepth = 0;
1001 
1002     assert(PUsed->getResolver() && "Analysis Resolver is not set");
1003     PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
1004     RDepth = DM.getDepth();
1005 
1006     if (PDepth == RDepth)
1007       LastUses.push_back(PUsed);
1008     else if (PDepth > RDepth) {
1009       // Let the parent claim responsibility of last use
1010       TransferLastUses.push_back(PUsed);
1011       // Keep track of higher level analysis used by this manager.
1012       HigherLevelAnalysis.push_back(PUsed);
1013     } else
1014       llvm_unreachable("Unable to accommodate Used Pass");
1015   }
1016 
1017   // Set P as P's last user until someone starts using P.
1018   // However, if P is a Pass Manager then it does not need
1019   // to record its last user.
1020   if (!P->getAsPMDataManager())
1021     LastUses.push_back(P);
1022   TPM->setLastUser(LastUses, P);
1023 
1024   if (!TransferLastUses.empty()) {
1025     Pass *My_PM = getAsPass();
1026     TPM->setLastUser(TransferLastUses, My_PM);
1027     TransferLastUses.clear();
1028   }
1029 
1030   // Now, take care of required analyses that are not available.
1031   for (AnalysisID ID : ReqAnalysisNotAvailable) {
1032     const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1033     Pass *AnalysisPass = PI->createPass();
1034     this->addLowerLevelRequiredPass(P, AnalysisPass);
1035   }
1036 
1037   // Take a note of analysis required and made available by this pass.
1038   // Remove the analysis not preserved by this pass
1039   removeNotPreservedAnalysis(P);
1040   recordAvailableAnalysis(P);
1041 
1042   // Add pass
1043   PassVector.push_back(P);
1044 }
1045 
1046 
1047 /// Populate UP with analysis pass that are used or required by
1048 /// pass P and are available. Populate RP_NotAvail with analysis
1049 /// pass that are required by pass P but are not available.
1050 void PMDataManager::collectRequiredAndUsedAnalyses(
1051     SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1052     Pass *P) {
1053   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1054 
1055   for (const auto &UsedID : AnUsage->getUsedSet())
1056     if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1057       UP.push_back(AnalysisPass);
1058 
1059   for (const auto &RequiredID : AnUsage->getRequiredSet())
1060     if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1061       UP.push_back(AnalysisPass);
1062     else
1063       RP_NotAvail.push_back(RequiredID);
1064 
1065   for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1066     if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1067       UP.push_back(AnalysisPass);
1068     else
1069       RP_NotAvail.push_back(RequiredID);
1070 }
1071 
1072 // All Required analyses should be available to the pass as it runs!  Here
1073 // we fill in the AnalysisImpls member of the pass so that it can
1074 // successfully use the getAnalysis() method to retrieve the
1075 // implementations it needs.
1076 //
1077 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1078   AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1079 
1080   for (const AnalysisID ID : AnUsage->getRequiredSet()) {
1081     Pass *Impl = findAnalysisPass(ID, true);
1082     if (!Impl)
1083       // This may be analysis pass that is initialized on the fly.
1084       // If that is not the case then it will raise an assert when it is used.
1085       continue;
1086     AnalysisResolver *AR = P->getResolver();
1087     assert(AR && "Analysis Resolver is not set");
1088     AR->addAnalysisImplsPair(ID, Impl);
1089   }
1090 }
1091 
1092 /// Find the pass that implements Analysis AID. If desired pass is not found
1093 /// then return NULL.
1094 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1095 
1096   // Check if AvailableAnalysis map has one entry.
1097   DenseMap<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
1098 
1099   if (I != AvailableAnalysis.end())
1100     return I->second;
1101 
1102   // Search Parents through TopLevelManager
1103   if (SearchParent)
1104     return TPM->findAnalysisPass(AID);
1105 
1106   return nullptr;
1107 }
1108 
1109 // Print list of passes that are last used by P.
1110 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1111 
1112   SmallVector<Pass *, 12> LUses;
1113 
1114   // If this is a on the fly manager then it does not have TPM.
1115   if (!TPM)
1116     return;
1117 
1118   TPM->collectLastUses(LUses, P);
1119 
1120   for (Pass *P : LUses) {
1121     dbgs() << "--" << std::string(Offset*2, ' ');
1122     P->dumpPassStructure(0);
1123   }
1124 }
1125 
1126 void PMDataManager::dumpPassArguments() const {
1127   for (Pass *P : PassVector) {
1128     if (PMDataManager *PMD = P->getAsPMDataManager())
1129       PMD->dumpPassArguments();
1130     else
1131       if (const PassInfo *PI =
1132             TPM->findAnalysisPassInfo(P->getPassID()))
1133         if (!PI->isAnalysisGroup())
1134           dbgs() << " -" << PI->getPassArgument();
1135   }
1136 }
1137 
1138 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1139                                  enum PassDebuggingString S2,
1140                                  StringRef Msg) {
1141   if (PassDebugging < Executions)
1142     return;
1143   dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1144          << std::string(getDepth() * 2 + 1, ' ');
1145   switch (S1) {
1146   case EXECUTION_MSG:
1147     dbgs() << "Executing Pass '" << P->getPassName();
1148     break;
1149   case MODIFICATION_MSG:
1150     dbgs() << "Made Modification '" << P->getPassName();
1151     break;
1152   case FREEING_MSG:
1153     dbgs() << " Freeing Pass '" << P->getPassName();
1154     break;
1155   default:
1156     break;
1157   }
1158   switch (S2) {
1159   case ON_BASICBLOCK_MSG:
1160     dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1161     break;
1162   case ON_FUNCTION_MSG:
1163     dbgs() << "' on Function '" << Msg << "'...\n";
1164     break;
1165   case ON_MODULE_MSG:
1166     dbgs() << "' on Module '"  << Msg << "'...\n";
1167     break;
1168   case ON_REGION_MSG:
1169     dbgs() << "' on Region '"  << Msg << "'...\n";
1170     break;
1171   case ON_LOOP_MSG:
1172     dbgs() << "' on Loop '" << Msg << "'...\n";
1173     break;
1174   case ON_CG_MSG:
1175     dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1176     break;
1177   default:
1178     break;
1179   }
1180 }
1181 
1182 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1183   if (PassDebugging < Details)
1184     return;
1185 
1186   AnalysisUsage analysisUsage;
1187   P->getAnalysisUsage(analysisUsage);
1188   dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1189 }
1190 
1191 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1192   if (PassDebugging < Details)
1193     return;
1194 
1195   AnalysisUsage analysisUsage;
1196   P->getAnalysisUsage(analysisUsage);
1197   dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1198 }
1199 
1200 void PMDataManager::dumpUsedSet(const Pass *P) const {
1201   if (PassDebugging < Details)
1202     return;
1203 
1204   AnalysisUsage analysisUsage;
1205   P->getAnalysisUsage(analysisUsage);
1206   dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1207 }
1208 
1209 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1210                                    const AnalysisUsage::VectorType &Set) const {
1211   assert(PassDebugging >= Details);
1212   if (Set.empty())
1213     return;
1214   dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1215   for (unsigned i = 0; i != Set.size(); ++i) {
1216     if (i) dbgs() << ',';
1217     const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1218     if (!PInf) {
1219       // Some preserved passes, such as AliasAnalysis, may not be initialized by
1220       // all drivers.
1221       dbgs() << " Uninitialized Pass";
1222       continue;
1223     }
1224     dbgs() << ' ' << PInf->getPassName();
1225   }
1226   dbgs() << '\n';
1227 }
1228 
1229 /// Add RequiredPass into list of lower level passes required by pass P.
1230 /// RequiredPass is run on the fly by Pass Manager when P requests it
1231 /// through getAnalysis interface.
1232 /// This should be handled by specific pass manager.
1233 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1234   if (TPM) {
1235     TPM->dumpArguments();
1236     TPM->dumpPasses();
1237   }
1238 
1239   // Module Level pass may required Function Level analysis info
1240   // (e.g. dominator info). Pass manager uses on the fly function pass manager
1241   // to provide this on demand. In that case, in Pass manager terminology,
1242   // module level pass is requiring lower level analysis info managed by
1243   // lower level pass manager.
1244 
1245   // When Pass manager is not able to order required analysis info, Pass manager
1246   // checks whether any lower level manager will be able to provide this
1247   // analysis info on demand or not.
1248 #ifndef NDEBUG
1249   dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1250   dbgs() << "' required by '" << P->getPassName() << "'\n";
1251 #endif
1252   llvm_unreachable("Unable to schedule pass");
1253 }
1254 
1255 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1256   llvm_unreachable("Unable to find on the fly pass");
1257 }
1258 
1259 // Destructor
1260 PMDataManager::~PMDataManager() {
1261   for (Pass *P : PassVector)
1262     delete P;
1263 }
1264 
1265 //===----------------------------------------------------------------------===//
1266 // NOTE: Is this the right place to define this method ?
1267 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1268 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1269   return PM.findAnalysisPass(ID, dir);
1270 }
1271 
1272 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1273                                      Function &F) {
1274   return PM.getOnTheFlyPass(P, AnalysisPI, F);
1275 }
1276 
1277 //===----------------------------------------------------------------------===//
1278 // BBPassManager implementation
1279 
1280 /// Execute all of the passes scheduled for execution by invoking
1281 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies
1282 /// the function, and if so, return true.
1283 bool BBPassManager::runOnFunction(Function &F) {
1284   if (F.isDeclaration())
1285     return false;
1286 
1287   bool Changed = doInitialization(F);
1288   Module &M = *F.getParent();
1289 
1290   unsigned InstrCount = 0;
1291   bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1292   for (BasicBlock &BB : F)
1293     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1294       BasicBlockPass *BP = getContainedPass(Index);
1295       bool LocalChanged = false;
1296 
1297       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, BB.getName());
1298       dumpRequiredSet(BP);
1299 
1300       initializeAnalysisImpl(BP);
1301 
1302       {
1303         // If the pass crashes, remember this.
1304         PassManagerPrettyStackEntry X(BP, BB);
1305         TimeRegion PassTimer(getPassTimer(BP));
1306         if (EmitICRemark)
1307           InstrCount = initSizeRemarkInfo(M);
1308         LocalChanged |= BP->runOnBasicBlock(BB);
1309         if (EmitICRemark)
1310           emitInstrCountChangedRemark(BP, M, InstrCount);
1311       }
1312 
1313       Changed |= LocalChanged;
1314       if (LocalChanged)
1315         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1316                      BB.getName());
1317       dumpPreservedSet(BP);
1318       dumpUsedSet(BP);
1319 
1320       verifyPreservedAnalysis(BP);
1321       removeNotPreservedAnalysis(BP);
1322       recordAvailableAnalysis(BP);
1323       removeDeadPasses(BP, BB.getName(), ON_BASICBLOCK_MSG);
1324     }
1325 
1326   return doFinalization(F) || Changed;
1327 }
1328 
1329 // Implement doInitialization and doFinalization
1330 bool BBPassManager::doInitialization(Module &M) {
1331   bool Changed = false;
1332 
1333   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1334     Changed |= getContainedPass(Index)->doInitialization(M);
1335 
1336   return Changed;
1337 }
1338 
1339 bool BBPassManager::doFinalization(Module &M) {
1340   bool Changed = false;
1341 
1342   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1343     Changed |= getContainedPass(Index)->doFinalization(M);
1344 
1345   return Changed;
1346 }
1347 
1348 bool BBPassManager::doInitialization(Function &F) {
1349   bool Changed = false;
1350 
1351   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1352     BasicBlockPass *BP = getContainedPass(Index);
1353     Changed |= BP->doInitialization(F);
1354   }
1355 
1356   return Changed;
1357 }
1358 
1359 bool BBPassManager::doFinalization(Function &F) {
1360   bool Changed = false;
1361 
1362   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1363     BasicBlockPass *BP = getContainedPass(Index);
1364     Changed |= BP->doFinalization(F);
1365   }
1366 
1367   return Changed;
1368 }
1369 
1370 
1371 //===----------------------------------------------------------------------===//
1372 // FunctionPassManager implementation
1373 
1374 /// Create new Function pass manager
1375 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1376   FPM = new FunctionPassManagerImpl();
1377   // FPM is the top level manager.
1378   FPM->setTopLevelManager(FPM);
1379 
1380   AnalysisResolver *AR = new AnalysisResolver(*FPM);
1381   FPM->setResolver(AR);
1382 }
1383 
1384 FunctionPassManager::~FunctionPassManager() {
1385   delete FPM;
1386 }
1387 
1388 void FunctionPassManager::add(Pass *P) {
1389   FPM->add(P);
1390 }
1391 
1392 /// run - Execute all of the passes scheduled for execution.  Keep
1393 /// track of whether any of the passes modifies the function, and if
1394 /// so, return true.
1395 ///
1396 bool FunctionPassManager::run(Function &F) {
1397   handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1398     report_fatal_error("Error reading bitcode file: " + EIB.message());
1399   });
1400   return FPM->run(F);
1401 }
1402 
1403 
1404 /// doInitialization - Run all of the initializers for the function passes.
1405 ///
1406 bool FunctionPassManager::doInitialization() {
1407   return FPM->doInitialization(*M);
1408 }
1409 
1410 /// doFinalization - Run all of the finalizers for the function passes.
1411 ///
1412 bool FunctionPassManager::doFinalization() {
1413   return FPM->doFinalization(*M);
1414 }
1415 
1416 //===----------------------------------------------------------------------===//
1417 // FunctionPassManagerImpl implementation
1418 //
1419 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1420   bool Changed = false;
1421 
1422   dumpArguments();
1423   dumpPasses();
1424 
1425   for (ImmutablePass *ImPass : getImmutablePasses())
1426     Changed |= ImPass->doInitialization(M);
1427 
1428   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1429     Changed |= getContainedManager(Index)->doInitialization(M);
1430 
1431   return Changed;
1432 }
1433 
1434 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1435   bool Changed = false;
1436 
1437   for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1438     Changed |= getContainedManager(Index)->doFinalization(M);
1439 
1440   for (ImmutablePass *ImPass : getImmutablePasses())
1441     Changed |= ImPass->doFinalization(M);
1442 
1443   return Changed;
1444 }
1445 
1446 /// cleanup - After running all passes, clean up pass manager cache.
1447 void FPPassManager::cleanup() {
1448  for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1449     FunctionPass *FP = getContainedPass(Index);
1450     AnalysisResolver *AR = FP->getResolver();
1451     assert(AR && "Analysis Resolver is not set");
1452     AR->clearAnalysisImpls();
1453  }
1454 }
1455 
1456 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1457   if (!wasRun)
1458     return;
1459   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1460     FPPassManager *FPPM = getContainedManager(Index);
1461     for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1462       FPPM->getContainedPass(Index)->releaseMemory();
1463     }
1464   }
1465   wasRun = false;
1466 }
1467 
1468 // Execute all the passes managed by this top level manager.
1469 // Return true if any function is modified by a pass.
1470 bool FunctionPassManagerImpl::run(Function &F) {
1471   bool Changed = false;
1472 
1473   initializeAllAnalysisInfo();
1474   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1475     Changed |= getContainedManager(Index)->runOnFunction(F);
1476     F.getContext().yield();
1477   }
1478 
1479   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1480     getContainedManager(Index)->cleanup();
1481 
1482   wasRun = true;
1483   return Changed;
1484 }
1485 
1486 //===----------------------------------------------------------------------===//
1487 // FPPassManager implementation
1488 
1489 char FPPassManager::ID = 0;
1490 /// Print passes managed by this manager
1491 void FPPassManager::dumpPassStructure(unsigned Offset) {
1492   dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1493   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1494     FunctionPass *FP = getContainedPass(Index);
1495     FP->dumpPassStructure(Offset + 1);
1496     dumpLastUses(FP, Offset+1);
1497   }
1498 }
1499 
1500 
1501 /// Execute all of the passes scheduled for execution by invoking
1502 /// runOnFunction method.  Keep track of whether any of the passes modifies
1503 /// the function, and if so, return true.
1504 bool FPPassManager::runOnFunction(Function &F) {
1505   if (F.isDeclaration())
1506     return false;
1507 
1508   bool Changed = false;
1509   Module &M = *F.getParent();
1510   // Collect inherited analysis from Module level pass manager.
1511   populateInheritedAnalysis(TPM->activeStack);
1512 
1513   unsigned InstrCount = 0;
1514   bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1515   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1516     FunctionPass *FP = getContainedPass(Index);
1517     bool LocalChanged = false;
1518 
1519     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1520     dumpRequiredSet(FP);
1521 
1522     initializeAnalysisImpl(FP);
1523 
1524     {
1525       PassManagerPrettyStackEntry X(FP, F);
1526       TimeRegion PassTimer(getPassTimer(FP));
1527       if (EmitICRemark)
1528         InstrCount = initSizeRemarkInfo(M);
1529       LocalChanged |= FP->runOnFunction(F);
1530       if (EmitICRemark)
1531         emitInstrCountChangedRemark(FP, M, InstrCount);
1532     }
1533 
1534     Changed |= LocalChanged;
1535     if (LocalChanged)
1536       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1537     dumpPreservedSet(FP);
1538     dumpUsedSet(FP);
1539 
1540     verifyPreservedAnalysis(FP);
1541     removeNotPreservedAnalysis(FP);
1542     recordAvailableAnalysis(FP);
1543     removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1544   }
1545   return Changed;
1546 }
1547 
1548 bool FPPassManager::runOnModule(Module &M) {
1549   bool Changed = false;
1550 
1551   for (Function &F : M)
1552     Changed |= runOnFunction(F);
1553 
1554   return Changed;
1555 }
1556 
1557 bool FPPassManager::doInitialization(Module &M) {
1558   bool Changed = false;
1559 
1560   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1561     Changed |= getContainedPass(Index)->doInitialization(M);
1562 
1563   return Changed;
1564 }
1565 
1566 bool FPPassManager::doFinalization(Module &M) {
1567   bool Changed = false;
1568 
1569   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1570     Changed |= getContainedPass(Index)->doFinalization(M);
1571 
1572   return Changed;
1573 }
1574 
1575 //===----------------------------------------------------------------------===//
1576 // MPPassManager implementation
1577 
1578 /// Execute all of the passes scheduled for execution by invoking
1579 /// runOnModule method.  Keep track of whether any of the passes modifies
1580 /// the module, and if so, return true.
1581 bool
1582 MPPassManager::runOnModule(Module &M) {
1583   bool Changed = false;
1584 
1585   // Initialize on-the-fly passes
1586   for (auto &OnTheFlyManager : OnTheFlyManagers) {
1587     FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1588     Changed |= FPP->doInitialization(M);
1589   }
1590 
1591   // Initialize module passes
1592   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1593     Changed |= getContainedPass(Index)->doInitialization(M);
1594 
1595   unsigned InstrCount = 0;
1596   bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1597   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1598     ModulePass *MP = getContainedPass(Index);
1599     bool LocalChanged = false;
1600 
1601     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1602     dumpRequiredSet(MP);
1603 
1604     initializeAnalysisImpl(MP);
1605 
1606     {
1607       PassManagerPrettyStackEntry X(MP, M);
1608       TimeRegion PassTimer(getPassTimer(MP));
1609 
1610       if (EmitICRemark)
1611         InstrCount = initSizeRemarkInfo(M);
1612       LocalChanged |= MP->runOnModule(M);
1613       if (EmitICRemark)
1614         emitInstrCountChangedRemark(MP, M, InstrCount);
1615     }
1616 
1617     Changed |= LocalChanged;
1618     if (LocalChanged)
1619       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1620                    M.getModuleIdentifier());
1621     dumpPreservedSet(MP);
1622     dumpUsedSet(MP);
1623 
1624     verifyPreservedAnalysis(MP);
1625     removeNotPreservedAnalysis(MP);
1626     recordAvailableAnalysis(MP);
1627     removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1628   }
1629 
1630   // Finalize module passes
1631   for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1632     Changed |= getContainedPass(Index)->doFinalization(M);
1633 
1634   // Finalize on-the-fly passes
1635   for (auto &OnTheFlyManager : OnTheFlyManagers) {
1636     FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1637     // We don't know when is the last time an on-the-fly pass is run,
1638     // so we need to releaseMemory / finalize here
1639     FPP->releaseMemoryOnTheFly();
1640     Changed |= FPP->doFinalization(M);
1641   }
1642 
1643   return Changed;
1644 }
1645 
1646 /// Add RequiredPass into list of lower level passes required by pass P.
1647 /// RequiredPass is run on the fly by Pass Manager when P requests it
1648 /// through getAnalysis interface.
1649 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1650   assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1651          "Unable to handle Pass that requires lower level Analysis pass");
1652   assert((P->getPotentialPassManagerType() <
1653           RequiredPass->getPotentialPassManagerType()) &&
1654          "Unable to handle Pass that requires lower level Analysis pass");
1655   if (!RequiredPass)
1656     return;
1657 
1658   FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1659   if (!FPP) {
1660     FPP = new FunctionPassManagerImpl();
1661     // FPP is the top level manager.
1662     FPP->setTopLevelManager(FPP);
1663 
1664     OnTheFlyManagers[P] = FPP;
1665   }
1666   const PassInfo *RequiredPassPI =
1667       TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1668 
1669   Pass *FoundPass = nullptr;
1670   if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1671     FoundPass =
1672       ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1673   }
1674   if (!FoundPass) {
1675     FoundPass = RequiredPass;
1676     // This should be guaranteed to add RequiredPass to the passmanager given
1677     // that we checked for an available analysis above.
1678     FPP->add(RequiredPass);
1679   }
1680   // Register P as the last user of FoundPass or RequiredPass.
1681   SmallVector<Pass *, 1> LU;
1682   LU.push_back(FoundPass);
1683   FPP->setLastUser(LU,  P);
1684 }
1685 
1686 /// Return function pass corresponding to PassInfo PI, that is
1687 /// required by module pass MP. Instantiate analysis pass, by using
1688 /// its runOnFunction() for function F.
1689 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1690   FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1691   assert(FPP && "Unable to find on the fly pass");
1692 
1693   FPP->releaseMemoryOnTheFly();
1694   FPP->run(F);
1695   return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1696 }
1697 
1698 
1699 //===----------------------------------------------------------------------===//
1700 // PassManagerImpl implementation
1701 
1702 //
1703 /// run - Execute all of the passes scheduled for execution.  Keep track of
1704 /// whether any of the passes modifies the module, and if so, return true.
1705 bool PassManagerImpl::run(Module &M) {
1706   bool Changed = false;
1707 
1708   dumpArguments();
1709   dumpPasses();
1710 
1711   for (ImmutablePass *ImPass : getImmutablePasses())
1712     Changed |= ImPass->doInitialization(M);
1713 
1714   initializeAllAnalysisInfo();
1715   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1716     Changed |= getContainedManager(Index)->runOnModule(M);
1717     M.getContext().yield();
1718   }
1719 
1720   for (ImmutablePass *ImPass : getImmutablePasses())
1721     Changed |= ImPass->doFinalization(M);
1722 
1723   return Changed;
1724 }
1725 
1726 //===----------------------------------------------------------------------===//
1727 // PassManager implementation
1728 
1729 /// Create new pass manager
1730 PassManager::PassManager() {
1731   PM = new PassManagerImpl();
1732   // PM is the top level manager
1733   PM->setTopLevelManager(PM);
1734 }
1735 
1736 PassManager::~PassManager() {
1737   delete PM;
1738 }
1739 
1740 void PassManager::add(Pass *P) {
1741   PM->add(P);
1742 }
1743 
1744 /// run - Execute all of the passes scheduled for execution.  Keep track of
1745 /// whether any of the passes modifies the module, and if so, return true.
1746 bool PassManager::run(Module &M) {
1747   return PM->run(M);
1748 }
1749 
1750 //===----------------------------------------------------------------------===//
1751 // PMStack implementation
1752 //
1753 
1754 // Pop Pass Manager from the stack and clear its analysis info.
1755 void PMStack::pop() {
1756 
1757   PMDataManager *Top = this->top();
1758   Top->initializeAnalysisInfo();
1759 
1760   S.pop_back();
1761 }
1762 
1763 // Push PM on the stack and set its top level manager.
1764 void PMStack::push(PMDataManager *PM) {
1765   assert(PM && "Unable to push. Pass Manager expected");
1766   assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1767 
1768   if (!this->empty()) {
1769     assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1770            && "pushing bad pass manager to PMStack");
1771     PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1772 
1773     assert(TPM && "Unable to find top level manager");
1774     TPM->addIndirectPassManager(PM);
1775     PM->setTopLevelManager(TPM);
1776     PM->setDepth(this->top()->getDepth()+1);
1777   } else {
1778     assert((PM->getPassManagerType() == PMT_ModulePassManager
1779            || PM->getPassManagerType() == PMT_FunctionPassManager)
1780            && "pushing bad pass manager to PMStack");
1781     PM->setDepth(1);
1782   }
1783 
1784   S.push_back(PM);
1785 }
1786 
1787 // Dump content of the pass manager stack.
1788 LLVM_DUMP_METHOD void PMStack::dump() const {
1789   for (PMDataManager *Manager : S)
1790     dbgs() << Manager->getAsPass()->getPassName() << ' ';
1791 
1792   if (!S.empty())
1793     dbgs() << '\n';
1794 }
1795 
1796 /// Find appropriate Module Pass Manager in the PM Stack and
1797 /// add self into that manager.
1798 void ModulePass::assignPassManager(PMStack &PMS,
1799                                    PassManagerType PreferredType) {
1800   // Find Module Pass Manager
1801   while (!PMS.empty()) {
1802     PassManagerType TopPMType = PMS.top()->getPassManagerType();
1803     if (TopPMType == PreferredType)
1804       break; // We found desired pass manager
1805     else if (TopPMType > PMT_ModulePassManager)
1806       PMS.pop();    // Pop children pass managers
1807     else
1808       break;
1809   }
1810   assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1811   PMS.top()->add(this);
1812 }
1813 
1814 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1815 /// in the PM Stack and add self into that manager.
1816 void FunctionPass::assignPassManager(PMStack &PMS,
1817                                      PassManagerType PreferredType) {
1818 
1819   // Find Function Pass Manager
1820   while (!PMS.empty()) {
1821     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1822       PMS.pop();
1823     else
1824       break;
1825   }
1826 
1827   // Create new Function Pass Manager if needed.
1828   FPPassManager *FPP;
1829   if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1830     FPP = (FPPassManager *)PMS.top();
1831   } else {
1832     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1833     PMDataManager *PMD = PMS.top();
1834 
1835     // [1] Create new Function Pass Manager
1836     FPP = new FPPassManager();
1837     FPP->populateInheritedAnalysis(PMS);
1838 
1839     // [2] Set up new manager's top level manager
1840     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1841     TPM->addIndirectPassManager(FPP);
1842 
1843     // [3] Assign manager to manage this new manager. This may create
1844     // and push new managers into PMS
1845     FPP->assignPassManager(PMS, PMD->getPassManagerType());
1846 
1847     // [4] Push new manager into PMS
1848     PMS.push(FPP);
1849   }
1850 
1851   // Assign FPP as the manager of this pass.
1852   FPP->add(this);
1853 }
1854 
1855 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1856 /// in the PM Stack and add self into that manager.
1857 void BasicBlockPass::assignPassManager(PMStack &PMS,
1858                                        PassManagerType PreferredType) {
1859   BBPassManager *BBP;
1860 
1861   // Basic Pass Manager is a leaf pass manager. It does not handle
1862   // any other pass manager.
1863   if (!PMS.empty() &&
1864       PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1865     BBP = (BBPassManager *)PMS.top();
1866   } else {
1867     // If leaf manager is not Basic Block Pass manager then create new
1868     // basic Block Pass manager.
1869     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1870     PMDataManager *PMD = PMS.top();
1871 
1872     // [1] Create new Basic Block Manager
1873     BBP = new BBPassManager();
1874 
1875     // [2] Set up new manager's top level manager
1876     // Basic Block Pass Manager does not live by itself
1877     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1878     TPM->addIndirectPassManager(BBP);
1879 
1880     // [3] Assign manager to manage this new manager. This may create
1881     // and push new managers into PMS
1882     BBP->assignPassManager(PMS, PreferredType);
1883 
1884     // [4] Push new manager into PMS
1885     PMS.push(BBP);
1886   }
1887 
1888   // Assign BBP as the manager of this pass.
1889   BBP->add(this);
1890 }
1891 
1892 PassManagerBase::~PassManagerBase() {}
1893