StandardInstrumentations.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. //===- Standard pass instrumentations handling ----------------*- C++ -*--===//
  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. /// \file
  9. ///
  10. /// This file defines IR-printing pass instrumentation callbacks as well as
  11. /// StandardInstrumentations class that manages standard pass instrumentations.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Passes/StandardInstrumentations.h"
  15. #include "llvm/ADT/Any.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/Analysis/CallGraphSCCPass.h"
  19. #include "llvm/Analysis/LazyCallGraph.h"
  20. #include "llvm/Analysis/LoopInfo.h"
  21. #include "llvm/IR/Function.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/IR/PassInstrumentation.h"
  24. #include "llvm/IR/PrintPasses.h"
  25. #include "llvm/IR/Verifier.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/FormatVariadic.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <unordered_set>
  31. #include <vector>
  32. using namespace llvm;
  33. cl::opt<bool> PreservedCFGCheckerInstrumentation::VerifyPreservedCFG(
  34. "verify-cfg-preserved", cl::Hidden,
  35. #ifdef NDEBUG
  36. cl::init(false));
  37. #else
  38. cl::init(false));
  39. #endif
  40. // FIXME: Change `-debug-pass-manager` from boolean to enum type. Similar to
  41. // `-debug-pass` in legacy PM.
  42. static cl::opt<bool>
  43. DebugPMVerbose("debug-pass-manager-verbose", cl::Hidden, cl::init(false),
  44. cl::desc("Print all pass management debugging information. "
  45. "`-debug-pass-manager` must also be specified"));
  46. // An option that prints out the IR after passes, similar to
  47. // -print-after-all except that it only prints the IR after passes that
  48. // change the IR. Those passes that do not make changes to the IR are
  49. // reported as not making any changes. In addition, the initial IR is
  50. // also reported. Other hidden options affect the output from this
  51. // option. -filter-passes will limit the output to the named passes
  52. // that actually change the IR and other passes are reported as filtered out.
  53. // The specified passes will either be reported as making no changes (with
  54. // no IR reported) or the changed IR will be reported. Also, the
  55. // -filter-print-funcs and -print-module-scope options will do similar
  56. // filtering based on function name, reporting changed IRs as functions(or
  57. // modules if -print-module-scope is specified) for a particular function
  58. // or indicating that the IR has been filtered out. The extra options
  59. // can be combined, allowing only changed IRs for certain passes on certain
  60. // functions to be reported in different formats, with the rest being
  61. // reported as filtered out. The -print-before-changed option will print
  62. // the IR as it was before each pass that changed it. The optional
  63. // value of quiet will only report when the IR changes, suppressing
  64. // all other messages, including the initial IR.
  65. enum ChangePrinter { NoChangePrinter, PrintChangedVerbose, PrintChangedQuiet };
  66. static cl::opt<ChangePrinter> PrintChanged(
  67. "print-changed", cl::desc("Print changed IRs"), cl::Hidden,
  68. cl::ValueOptional, cl::init(NoChangePrinter),
  69. cl::values(clEnumValN(PrintChangedQuiet, "quiet", "Run in quiet mode"),
  70. // Sentinel value for unspecified option.
  71. clEnumValN(PrintChangedVerbose, "", "")));
  72. // An option that supports the -print-changed option. See
  73. // the description for -print-changed for an explanation of the use
  74. // of this option. Note that this option has no effect without -print-changed.
  75. static cl::list<std::string>
  76. PrintPassesList("filter-passes", cl::value_desc("pass names"),
  77. cl::desc("Only consider IR changes for passes whose names "
  78. "match for the print-changed option"),
  79. cl::CommaSeparated, cl::Hidden);
  80. // An option that supports the -print-changed option. See
  81. // the description for -print-changed for an explanation of the use
  82. // of this option. Note that this option has no effect without -print-changed.
  83. static cl::opt<bool>
  84. PrintChangedBefore("print-before-changed",
  85. cl::desc("Print before passes that change them"),
  86. cl::init(false), cl::Hidden);
  87. namespace {
  88. /// Extracting Module out of \p IR unit. Also fills a textual description
  89. /// of \p IR for use in header when printing.
  90. Optional<std::pair<const Module *, std::string>>
  91. unwrapModule(Any IR, bool Force = false) {
  92. if (any_isa<const Module *>(IR))
  93. return std::make_pair(any_cast<const Module *>(IR), std::string());
  94. if (any_isa<const Function *>(IR)) {
  95. const Function *F = any_cast<const Function *>(IR);
  96. if (!Force && !isFunctionInPrintList(F->getName()))
  97. return None;
  98. const Module *M = F->getParent();
  99. return std::make_pair(M, formatv(" (function: {0})", F->getName()).str());
  100. }
  101. if (any_isa<const LazyCallGraph::SCC *>(IR)) {
  102. const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
  103. for (const LazyCallGraph::Node &N : *C) {
  104. const Function &F = N.getFunction();
  105. if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) {
  106. const Module *M = F.getParent();
  107. return std::make_pair(M, formatv(" (scc: {0})", C->getName()).str());
  108. }
  109. }
  110. assert(!Force && "Expected to have made a pair when forced.");
  111. return None;
  112. }
  113. if (any_isa<const Loop *>(IR)) {
  114. const Loop *L = any_cast<const Loop *>(IR);
  115. const Function *F = L->getHeader()->getParent();
  116. if (!Force && !isFunctionInPrintList(F->getName()))
  117. return None;
  118. const Module *M = F->getParent();
  119. std::string LoopName;
  120. raw_string_ostream ss(LoopName);
  121. L->getHeader()->printAsOperand(ss, false);
  122. return std::make_pair(M, formatv(" (loop: {0})", ss.str()).str());
  123. }
  124. llvm_unreachable("Unknown IR unit");
  125. }
  126. void printIR(raw_ostream &OS, const Function *F, StringRef Banner,
  127. StringRef Extra = StringRef(), bool Brief = false) {
  128. if (Brief) {
  129. OS << F->getName() << '\n';
  130. return;
  131. }
  132. if (!isFunctionInPrintList(F->getName()))
  133. return;
  134. OS << Banner << Extra << "\n" << static_cast<const Value &>(*F);
  135. }
  136. void printIR(raw_ostream &OS, const Module *M, StringRef Banner,
  137. StringRef Extra = StringRef(), bool Brief = false,
  138. bool ShouldPreserveUseListOrder = false) {
  139. if (Brief) {
  140. OS << M->getName() << '\n';
  141. return;
  142. }
  143. if (isFunctionInPrintList("*") || forcePrintModuleIR()) {
  144. OS << Banner << Extra << "\n";
  145. M->print(OS, nullptr, ShouldPreserveUseListOrder);
  146. } else {
  147. for (const auto &F : M->functions()) {
  148. printIR(OS, &F, Banner, Extra);
  149. }
  150. }
  151. }
  152. void printIR(raw_ostream &OS, const LazyCallGraph::SCC *C, StringRef Banner,
  153. StringRef Extra = StringRef(), bool Brief = false) {
  154. if (Brief) {
  155. OS << *C << '\n';
  156. return;
  157. }
  158. bool BannerPrinted = false;
  159. for (const LazyCallGraph::Node &N : *C) {
  160. const Function &F = N.getFunction();
  161. if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
  162. if (!BannerPrinted) {
  163. OS << Banner << Extra << "\n";
  164. BannerPrinted = true;
  165. }
  166. F.print(OS);
  167. }
  168. }
  169. }
  170. void printIR(raw_ostream &OS, const Loop *L, StringRef Banner,
  171. bool Brief = false) {
  172. if (Brief) {
  173. OS << *L;
  174. return;
  175. }
  176. const Function *F = L->getHeader()->getParent();
  177. if (!isFunctionInPrintList(F->getName()))
  178. return;
  179. printLoop(const_cast<Loop &>(*L), OS, std::string(Banner));
  180. }
  181. /// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into
  182. /// llvm::Any and does actual print job.
  183. void unwrapAndPrint(raw_ostream &OS, Any IR, StringRef Banner,
  184. bool ForceModule = false, bool Brief = false,
  185. bool ShouldPreserveUseListOrder = false) {
  186. if (ForceModule) {
  187. if (auto UnwrappedModule = unwrapModule(IR))
  188. printIR(OS, UnwrappedModule->first, Banner, UnwrappedModule->second,
  189. Brief, ShouldPreserveUseListOrder);
  190. return;
  191. }
  192. if (any_isa<const Module *>(IR)) {
  193. const Module *M = any_cast<const Module *>(IR);
  194. assert(M && "module should be valid for printing");
  195. printIR(OS, M, Banner, "", Brief, ShouldPreserveUseListOrder);
  196. return;
  197. }
  198. if (any_isa<const Function *>(IR)) {
  199. const Function *F = any_cast<const Function *>(IR);
  200. assert(F && "function should be valid for printing");
  201. printIR(OS, F, Banner, "", Brief);
  202. return;
  203. }
  204. if (any_isa<const LazyCallGraph::SCC *>(IR)) {
  205. const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
  206. assert(C && "scc should be valid for printing");
  207. std::string Extra = std::string(formatv(" (scc: {0})", C->getName()));
  208. printIR(OS, C, Banner, Extra, Brief);
  209. return;
  210. }
  211. if (any_isa<const Loop *>(IR)) {
  212. const Loop *L = any_cast<const Loop *>(IR);
  213. assert(L && "Loop should be valid for printing");
  214. printIR(OS, L, Banner, Brief);
  215. return;
  216. }
  217. llvm_unreachable("Unknown wrapped IR type");
  218. }
  219. // Return true when this is a pass for which changes should be ignored
  220. bool isIgnored(StringRef PassID) {
  221. return isSpecialPass(PassID,
  222. {"PassManager", "PassAdaptor", "AnalysisManagerProxy"});
  223. }
  224. } // namespace
  225. template <typename IRUnitT>
  226. ChangeReporter<IRUnitT>::~ChangeReporter<IRUnitT>() {
  227. assert(BeforeStack.empty() && "Problem with Change Printer stack.");
  228. }
  229. template <typename IRUnitT>
  230. bool ChangeReporter<IRUnitT>::isInterestingFunction(const Function &F) {
  231. return isFunctionInPrintList(F.getName());
  232. }
  233. template <typename IRUnitT>
  234. bool ChangeReporter<IRUnitT>::isInterestingPass(StringRef PassID) {
  235. if (isIgnored(PassID))
  236. return false;
  237. static std::unordered_set<std::string> PrintPassNames(PrintPassesList.begin(),
  238. PrintPassesList.end());
  239. return PrintPassNames.empty() || PrintPassNames.count(PassID.str());
  240. }
  241. // Return true when this is a pass on IR for which printing
  242. // of changes is desired.
  243. template <typename IRUnitT>
  244. bool ChangeReporter<IRUnitT>::isInteresting(Any IR, StringRef PassID) {
  245. if (!isInterestingPass(PassID))
  246. return false;
  247. if (any_isa<const Function *>(IR))
  248. return isInterestingFunction(*any_cast<const Function *>(IR));
  249. return true;
  250. }
  251. template <typename IRUnitT>
  252. void ChangeReporter<IRUnitT>::saveIRBeforePass(Any IR, StringRef PassID) {
  253. // Always need to place something on the stack because invalidated passes
  254. // are not given the IR so it cannot be determined whether the pass was for
  255. // something that was filtered out.
  256. BeforeStack.emplace_back();
  257. if (!isInteresting(IR, PassID))
  258. return;
  259. // Is this the initial IR?
  260. if (InitialIR) {
  261. InitialIR = false;
  262. if (VerboseMode)
  263. handleInitialIR(IR);
  264. }
  265. // Save the IR representation on the stack.
  266. IRUnitT &Data = BeforeStack.back();
  267. generateIRRepresentation(IR, PassID, Data);
  268. }
  269. template <typename IRUnitT>
  270. void ChangeReporter<IRUnitT>::handleIRAfterPass(Any IR, StringRef PassID) {
  271. assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
  272. std::string Name;
  273. // unwrapModule has inconsistent handling of names for function IRs.
  274. if (any_isa<const Function *>(IR)) {
  275. const Function *F = any_cast<const Function *>(IR);
  276. Name = formatv(" (function: {0})", F->getName()).str();
  277. } else {
  278. if (auto UM = unwrapModule(IR))
  279. Name = UM->second;
  280. }
  281. if (Name == "")
  282. Name = " (module)";
  283. if (isIgnored(PassID)) {
  284. if (VerboseMode)
  285. handleIgnored(PassID, Name);
  286. } else if (!isInteresting(IR, PassID)) {
  287. if (VerboseMode)
  288. handleFiltered(PassID, Name);
  289. } else {
  290. // Get the before rep from the stack
  291. IRUnitT &Before = BeforeStack.back();
  292. // Create the after rep
  293. IRUnitT After;
  294. generateIRRepresentation(IR, PassID, After);
  295. // Was there a change in IR?
  296. if (same(Before, After)) {
  297. if (VerboseMode)
  298. omitAfter(PassID, Name);
  299. } else
  300. handleAfter(PassID, Name, Before, After, IR);
  301. }
  302. BeforeStack.pop_back();
  303. }
  304. template <typename IRUnitT>
  305. void ChangeReporter<IRUnitT>::handleInvalidatedPass(StringRef PassID) {
  306. assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
  307. // Always flag it as invalidated as we cannot determine when
  308. // a pass for a filtered function is invalidated since we do not
  309. // get the IR in the call. Also, the output is just alternate
  310. // forms of the banner anyway.
  311. if (VerboseMode)
  312. handleInvalidated(PassID);
  313. BeforeStack.pop_back();
  314. }
  315. template <typename IRUnitT>
  316. void ChangeReporter<IRUnitT>::registerRequiredCallbacks(
  317. PassInstrumentationCallbacks &PIC) {
  318. PIC.registerBeforeNonSkippedPassCallback(
  319. [this](StringRef P, Any IR) { saveIRBeforePass(IR, P); });
  320. PIC.registerAfterPassCallback(
  321. [this](StringRef P, Any IR, const PreservedAnalyses &) {
  322. handleIRAfterPass(IR, P);
  323. });
  324. PIC.registerAfterPassInvalidatedCallback(
  325. [this](StringRef P, const PreservedAnalyses &) {
  326. handleInvalidatedPass(P);
  327. });
  328. }
  329. template <typename IRUnitT>
  330. TextChangeReporter<IRUnitT>::TextChangeReporter(bool Verbose)
  331. : ChangeReporter<IRUnitT>(Verbose), Out(dbgs()) {}
  332. template <typename IRUnitT>
  333. void TextChangeReporter<IRUnitT>::handleInitialIR(Any IR) {
  334. // Always print the module.
  335. // Unwrap and print directly to avoid filtering problems in general routines.
  336. auto UnwrappedModule = unwrapModule(IR, /*Force=*/true);
  337. assert(UnwrappedModule && "Expected module to be unwrapped when forced.");
  338. Out << "*** IR Dump At Start: ***" << UnwrappedModule->second << "\n";
  339. UnwrappedModule->first->print(Out, nullptr,
  340. /*ShouldPreserveUseListOrder=*/true);
  341. }
  342. template <typename IRUnitT>
  343. void TextChangeReporter<IRUnitT>::omitAfter(StringRef PassID,
  344. std::string &Name) {
  345. Out << formatv("*** IR Dump After {0}{1} omitted because no change ***\n",
  346. PassID, Name);
  347. }
  348. template <typename IRUnitT>
  349. void TextChangeReporter<IRUnitT>::handleInvalidated(StringRef PassID) {
  350. Out << formatv("*** IR Pass {0} invalidated ***\n", PassID);
  351. }
  352. template <typename IRUnitT>
  353. void TextChangeReporter<IRUnitT>::handleFiltered(StringRef PassID,
  354. std::string &Name) {
  355. SmallString<20> Banner =
  356. formatv("*** IR Dump After {0}{1} filtered out ***\n", PassID, Name);
  357. Out << Banner;
  358. }
  359. template <typename IRUnitT>
  360. void TextChangeReporter<IRUnitT>::handleIgnored(StringRef PassID,
  361. std::string &Name) {
  362. Out << formatv("*** IR Pass {0}{1} ignored ***\n", PassID, Name);
  363. }
  364. IRChangedPrinter::~IRChangedPrinter() {}
  365. void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
  366. if (PrintChanged != NoChangePrinter)
  367. TextChangeReporter<std::string>::registerRequiredCallbacks(PIC);
  368. }
  369. void IRChangedPrinter::generateIRRepresentation(Any IR, StringRef PassID,
  370. std::string &Output) {
  371. raw_string_ostream OS(Output);
  372. // use the after banner for all cases so it will match
  373. SmallString<20> Banner = formatv("*** IR Dump After {0} ***", PassID);
  374. unwrapAndPrint(OS, IR, Banner, forcePrintModuleIR(),
  375. /*Brief=*/false, /*ShouldPreserveUseListOrder=*/true);
  376. OS.str();
  377. }
  378. void IRChangedPrinter::handleAfter(StringRef PassID, std::string &Name,
  379. const std::string &Before,
  380. const std::string &After, Any) {
  381. assert(After.find("*** IR Dump") == 0 && "Unexpected banner format.");
  382. StringRef AfterRef = After;
  383. StringRef Banner =
  384. AfterRef.take_until([](char C) -> bool { return C == '\n'; });
  385. // Report the IR before the changes when requested.
  386. if (PrintChangedBefore) {
  387. Out << "*** IR Dump Before" << Banner.substr(17);
  388. // LazyCallGraph::SCC already has "(scc:..." in banner so only add
  389. // in the name if it isn't already there.
  390. if (Name.substr(0, 6) != " (scc:" && !forcePrintModuleIR())
  391. Out << Name;
  392. StringRef BeforeRef = Before;
  393. Out << BeforeRef.substr(Banner.size());
  394. }
  395. Out << Banner;
  396. // LazyCallGraph::SCC already has "(scc:..." in banner so only add
  397. // in the name if it isn't already there.
  398. if (Name.substr(0, 6) != " (scc:" && !forcePrintModuleIR())
  399. Out << Name;
  400. Out << After.substr(Banner.size());
  401. }
  402. bool IRChangedPrinter::same(const std::string &S1, const std::string &S2) {
  403. return S1 == S2;
  404. }
  405. PrintIRInstrumentation::~PrintIRInstrumentation() {
  406. assert(ModuleDescStack.empty() && "ModuleDescStack is not empty at exit");
  407. }
  408. void PrintIRInstrumentation::pushModuleDesc(StringRef PassID, Any IR) {
  409. assert(StoreModuleDesc);
  410. const Module *M = nullptr;
  411. std::string Extra;
  412. if (auto UnwrappedModule = unwrapModule(IR))
  413. std::tie(M, Extra) = UnwrappedModule.getValue();
  414. ModuleDescStack.emplace_back(M, Extra, PassID);
  415. }
  416. PrintIRInstrumentation::PrintModuleDesc
  417. PrintIRInstrumentation::popModuleDesc(StringRef PassID) {
  418. assert(!ModuleDescStack.empty() && "empty ModuleDescStack");
  419. PrintModuleDesc ModuleDesc = ModuleDescStack.pop_back_val();
  420. assert(std::get<2>(ModuleDesc).equals(PassID) && "malformed ModuleDescStack");
  421. return ModuleDesc;
  422. }
  423. void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) {
  424. if (isIgnored(PassID))
  425. return;
  426. // Saving Module for AfterPassInvalidated operations.
  427. // Note: here we rely on a fact that we do not change modules while
  428. // traversing the pipeline, so the latest captured module is good
  429. // for all print operations that has not happen yet.
  430. if (StoreModuleDesc && shouldPrintAfterPass(PassID))
  431. pushModuleDesc(PassID, IR);
  432. if (!shouldPrintBeforePass(PassID))
  433. return;
  434. SmallString<20> Banner = formatv("*** IR Dump Before {0} ***", PassID);
  435. unwrapAndPrint(dbgs(), IR, Banner, forcePrintModuleIR());
  436. }
  437. void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) {
  438. if (isIgnored(PassID))
  439. return;
  440. if (!shouldPrintAfterPass(PassID))
  441. return;
  442. if (StoreModuleDesc)
  443. popModuleDesc(PassID);
  444. SmallString<20> Banner = formatv("*** IR Dump After {0} ***", PassID);
  445. unwrapAndPrint(dbgs(), IR, Banner, forcePrintModuleIR());
  446. }
  447. void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) {
  448. StringRef PassName = PIC->getPassNameForClassName(PassID);
  449. if (!StoreModuleDesc || !shouldPrintAfterPass(PassName))
  450. return;
  451. if (isIgnored(PassID))
  452. return;
  453. const Module *M;
  454. std::string Extra;
  455. StringRef StoredPassID;
  456. std::tie(M, Extra, StoredPassID) = popModuleDesc(PassID);
  457. // Additional filtering (e.g. -filter-print-func) can lead to module
  458. // printing being skipped.
  459. if (!M)
  460. return;
  461. SmallString<20> Banner =
  462. formatv("*** IR Dump After {0} *** invalidated: ", PassID);
  463. printIR(dbgs(), M, Banner, Extra);
  464. }
  465. bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) {
  466. if (shouldPrintBeforeAll())
  467. return true;
  468. StringRef PassName = PIC->getPassNameForClassName(PassID);
  469. for (const auto &P : printBeforePasses()) {
  470. if (PassName == P)
  471. return true;
  472. }
  473. return false;
  474. }
  475. bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) {
  476. if (shouldPrintAfterAll())
  477. return true;
  478. StringRef PassName = PIC->getPassNameForClassName(PassID);
  479. for (const auto &P : printAfterPasses()) {
  480. if (PassName == P)
  481. return true;
  482. }
  483. return false;
  484. }
  485. void PrintIRInstrumentation::registerCallbacks(
  486. PassInstrumentationCallbacks &PIC) {
  487. this->PIC = &PIC;
  488. // BeforePass callback is not just for printing, it also saves a Module
  489. // for later use in AfterPassInvalidated.
  490. StoreModuleDesc = forcePrintModuleIR() && shouldPrintAfterSomePass();
  491. if (shouldPrintBeforeSomePass() || StoreModuleDesc)
  492. PIC.registerBeforeNonSkippedPassCallback(
  493. [this](StringRef P, Any IR) { this->printBeforePass(P, IR); });
  494. if (shouldPrintAfterSomePass()) {
  495. PIC.registerAfterPassCallback(
  496. [this](StringRef P, Any IR, const PreservedAnalyses &) {
  497. this->printAfterPass(P, IR);
  498. });
  499. PIC.registerAfterPassInvalidatedCallback(
  500. [this](StringRef P, const PreservedAnalyses &) {
  501. this->printAfterPassInvalidated(P);
  502. });
  503. }
  504. }
  505. void OptNoneInstrumentation::registerCallbacks(
  506. PassInstrumentationCallbacks &PIC) {
  507. PIC.registerShouldRunOptionalPassCallback(
  508. [this](StringRef P, Any IR) { return this->shouldRun(P, IR); });
  509. }
  510. bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) {
  511. const Function *F = nullptr;
  512. if (any_isa<const Function *>(IR)) {
  513. F = any_cast<const Function *>(IR);
  514. } else if (any_isa<const Loop *>(IR)) {
  515. F = any_cast<const Loop *>(IR)->getHeader()->getParent();
  516. }
  517. bool ShouldRun = !(F && F->hasOptNone());
  518. if (!ShouldRun && DebugLogging) {
  519. errs() << "Skipping pass " << PassID << " on " << F->getName()
  520. << " due to optnone attribute\n";
  521. }
  522. return ShouldRun;
  523. }
  524. static std::string getBisectDescription(Any IR) {
  525. if (any_isa<const Module *>(IR)) {
  526. const Module *M = any_cast<const Module *>(IR);
  527. assert(M && "module should be valid for printing");
  528. return "module (" + M->getName().str() + ")";
  529. }
  530. if (any_isa<const Function *>(IR)) {
  531. const Function *F = any_cast<const Function *>(IR);
  532. assert(F && "function should be valid for printing");
  533. return "function (" + F->getName().str() + ")";
  534. }
  535. if (any_isa<const LazyCallGraph::SCC *>(IR)) {
  536. const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
  537. assert(C && "scc should be valid for printing");
  538. return "SCC " + C->getName();
  539. }
  540. if (any_isa<const Loop *>(IR)) {
  541. return "loop";
  542. }
  543. llvm_unreachable("Unknown wrapped IR type");
  544. }
  545. void OptBisectInstrumentation::registerCallbacks(
  546. PassInstrumentationCallbacks &PIC) {
  547. if (!OptBisector->isEnabled())
  548. return;
  549. PIC.registerShouldRunOptionalPassCallback([](StringRef PassID, Any IR) {
  550. return isIgnored(PassID) ||
  551. OptBisector->checkPass(PassID, getBisectDescription(IR));
  552. });
  553. }
  554. void PrintPassInstrumentation::registerCallbacks(
  555. PassInstrumentationCallbacks &PIC) {
  556. if (!DebugLogging)
  557. return;
  558. std::vector<StringRef> SpecialPasses = {"PassManager"};
  559. if (!DebugPMVerbose)
  560. SpecialPasses.emplace_back("PassAdaptor");
  561. PIC.registerBeforeSkippedPassCallback(
  562. [SpecialPasses](StringRef PassID, Any IR) {
  563. assert(!isSpecialPass(PassID, SpecialPasses) &&
  564. "Unexpectedly skipping special pass");
  565. dbgs() << "Skipping pass: " << PassID << " on ";
  566. unwrapAndPrint(dbgs(), IR, "", false, true);
  567. });
  568. PIC.registerBeforeNonSkippedPassCallback(
  569. [SpecialPasses](StringRef PassID, Any IR) {
  570. if (isSpecialPass(PassID, SpecialPasses))
  571. return;
  572. dbgs() << "Running pass: " << PassID << " on ";
  573. unwrapAndPrint(dbgs(), IR, "", false, true);
  574. });
  575. PIC.registerBeforeAnalysisCallback([](StringRef PassID, Any IR) {
  576. dbgs() << "Running analysis: " << PassID << " on ";
  577. unwrapAndPrint(dbgs(), IR, "", false, true);
  578. });
  579. }
  580. PreservedCFGCheckerInstrumentation::CFG::CFG(const Function *F,
  581. bool TrackBBLifetime) {
  582. if (TrackBBLifetime)
  583. BBGuards = DenseMap<intptr_t, BBGuard>(F->size());
  584. for (const auto &BB : *F) {
  585. if (BBGuards)
  586. BBGuards->try_emplace(intptr_t(&BB), &BB);
  587. for (auto *Succ : successors(&BB)) {
  588. Graph[&BB][Succ]++;
  589. if (BBGuards)
  590. BBGuards->try_emplace(intptr_t(Succ), Succ);
  591. }
  592. }
  593. }
  594. static void printBBName(raw_ostream &out, const BasicBlock *BB) {
  595. if (BB->hasName()) {
  596. out << BB->getName() << "<" << BB << ">";
  597. return;
  598. }
  599. if (!BB->getParent()) {
  600. out << "unnamed_removed<" << BB << ">";
  601. return;
  602. }
  603. if (BB == &BB->getParent()->getEntryBlock()) {
  604. out << "entry"
  605. << "<" << BB << ">";
  606. return;
  607. }
  608. unsigned FuncOrderBlockNum = 0;
  609. for (auto &FuncBB : *BB->getParent()) {
  610. if (&FuncBB == BB)
  611. break;
  612. FuncOrderBlockNum++;
  613. }
  614. out << "unnamed_" << FuncOrderBlockNum << "<" << BB << ">";
  615. }
  616. void PreservedCFGCheckerInstrumentation::CFG::printDiff(raw_ostream &out,
  617. const CFG &Before,
  618. const CFG &After) {
  619. assert(!After.isPoisoned());
  620. // Print function name.
  621. const CFG *FuncGraph = nullptr;
  622. if (!After.Graph.empty())
  623. FuncGraph = &After;
  624. else if (!Before.isPoisoned() && !Before.Graph.empty())
  625. FuncGraph = &Before;
  626. if (FuncGraph)
  627. out << "In function @"
  628. << FuncGraph->Graph.begin()->first->getParent()->getName() << "\n";
  629. if (Before.isPoisoned()) {
  630. out << "Some blocks were deleted\n";
  631. return;
  632. }
  633. // Find and print graph differences.
  634. if (Before.Graph.size() != After.Graph.size())
  635. out << "Different number of non-leaf basic blocks: before="
  636. << Before.Graph.size() << ", after=" << After.Graph.size() << "\n";
  637. for (auto &BB : Before.Graph) {
  638. auto BA = After.Graph.find(BB.first);
  639. if (BA == After.Graph.end()) {
  640. out << "Non-leaf block ";
  641. printBBName(out, BB.first);
  642. out << " is removed (" << BB.second.size() << " successors)\n";
  643. }
  644. }
  645. for (auto &BA : After.Graph) {
  646. auto BB = Before.Graph.find(BA.first);
  647. if (BB == Before.Graph.end()) {
  648. out << "Non-leaf block ";
  649. printBBName(out, BA.first);
  650. out << " is added (" << BA.second.size() << " successors)\n";
  651. continue;
  652. }
  653. if (BB->second == BA.second)
  654. continue;
  655. out << "Different successors of block ";
  656. printBBName(out, BA.first);
  657. out << " (unordered):\n";
  658. out << "- before (" << BB->second.size() << "): ";
  659. for (auto &SuccB : BB->second) {
  660. printBBName(out, SuccB.first);
  661. if (SuccB.second != 1)
  662. out << "(" << SuccB.second << "), ";
  663. else
  664. out << ", ";
  665. }
  666. out << "\n";
  667. out << "- after (" << BA.second.size() << "): ";
  668. for (auto &SuccA : BA.second) {
  669. printBBName(out, SuccA.first);
  670. if (SuccA.second != 1)
  671. out << "(" << SuccA.second << "), ";
  672. else
  673. out << ", ";
  674. }
  675. out << "\n";
  676. }
  677. }
  678. void PreservedCFGCheckerInstrumentation::registerCallbacks(
  679. PassInstrumentationCallbacks &PIC) {
  680. if (!VerifyPreservedCFG)
  681. return;
  682. PIC.registerBeforeNonSkippedPassCallback([this](StringRef P, Any IR) {
  683. if (any_isa<const Function *>(IR))
  684. GraphStackBefore.emplace_back(P, CFG(any_cast<const Function *>(IR)));
  685. else
  686. GraphStackBefore.emplace_back(P, None);
  687. });
  688. PIC.registerAfterPassInvalidatedCallback(
  689. [this](StringRef P, const PreservedAnalyses &PassPA) {
  690. auto Before = GraphStackBefore.pop_back_val();
  691. assert(Before.first == P &&
  692. "Before and After callbacks must correspond");
  693. (void)Before;
  694. });
  695. PIC.registerAfterPassCallback([this](StringRef P, Any IR,
  696. const PreservedAnalyses &PassPA) {
  697. auto Before = GraphStackBefore.pop_back_val();
  698. assert(Before.first == P && "Before and After callbacks must correspond");
  699. auto &GraphBefore = Before.second;
  700. if (!PassPA.allAnalysesInSetPreserved<CFGAnalyses>())
  701. return;
  702. if (any_isa<const Function *>(IR)) {
  703. assert(GraphBefore && "Must be built in BeforePassCallback");
  704. CFG GraphAfter(any_cast<const Function *>(IR), false /* NeedsGuard */);
  705. if (GraphAfter == *GraphBefore)
  706. return;
  707. dbgs() << "Error: " << P
  708. << " reported it preserved CFG, but changes detected:\n";
  709. CFG::printDiff(dbgs(), *GraphBefore, GraphAfter);
  710. report_fatal_error(Twine("Preserved CFG changed by ", P));
  711. }
  712. });
  713. }
  714. void VerifyInstrumentation::registerCallbacks(
  715. PassInstrumentationCallbacks &PIC) {
  716. PIC.registerAfterPassCallback(
  717. [this](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
  718. if (isIgnored(P) || P == "VerifierPass")
  719. return;
  720. if (any_isa<const Function *>(IR) || any_isa<const Loop *>(IR)) {
  721. const Function *F;
  722. if (any_isa<const Loop *>(IR))
  723. F = any_cast<const Loop *>(IR)->getHeader()->getParent();
  724. else
  725. F = any_cast<const Function *>(IR);
  726. if (DebugLogging)
  727. dbgs() << "Verifying function " << F->getName() << "\n";
  728. if (verifyFunction(*F))
  729. report_fatal_error("Broken function found, compilation aborted!");
  730. } else if (any_isa<const Module *>(IR) ||
  731. any_isa<const LazyCallGraph::SCC *>(IR)) {
  732. const Module *M;
  733. if (any_isa<const LazyCallGraph::SCC *>(IR))
  734. M = any_cast<const LazyCallGraph::SCC *>(IR)
  735. ->begin()
  736. ->getFunction()
  737. .getParent();
  738. else
  739. M = any_cast<const Module *>(IR);
  740. if (DebugLogging)
  741. dbgs() << "Verifying module " << M->getName() << "\n";
  742. if (verifyModule(*M))
  743. report_fatal_error("Broken module found, compilation aborted!");
  744. }
  745. });
  746. }
  747. StandardInstrumentations::StandardInstrumentations(bool DebugLogging,
  748. bool VerifyEach)
  749. : PrintPass(DebugLogging), OptNone(DebugLogging),
  750. PrintChangedIR(PrintChanged != PrintChangedQuiet), Verify(DebugLogging),
  751. VerifyEach(VerifyEach) {}
  752. void StandardInstrumentations::registerCallbacks(
  753. PassInstrumentationCallbacks &PIC) {
  754. PrintIR.registerCallbacks(PIC);
  755. PrintPass.registerCallbacks(PIC);
  756. TimePasses.registerCallbacks(PIC);
  757. OptNone.registerCallbacks(PIC);
  758. OptBisect.registerCallbacks(PIC);
  759. PreservedCFGChecker.registerCallbacks(PIC);
  760. PrintChangedIR.registerCallbacks(PIC);
  761. PseudoProbeVerification.registerCallbacks(PIC);
  762. if (VerifyEach)
  763. Verify.registerCallbacks(PIC);
  764. }
  765. namespace llvm {
  766. template class ChangeReporter<std::string>;
  767. template class TextChangeReporter<std::string>;
  768. } // namespace llvm