LegacyPassManager.cpp 63 KB

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