LegacyPassManager.cpp 66 KB

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