LegacyPassManager.cpp 62 KB

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