LegacyPassManager.cpp 60 KB

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