LoopPass.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. //===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===//
  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 LoopPass and LPPassManager. All loop optimization
  10. // and transformation passes are derived from LoopPass. LPPassManager is
  11. // responsible for managing LoopPasses.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/LoopPass.h"
  15. #include "llvm/Analysis/LoopAnalysisManager.h"
  16. #include "llvm/IR/Dominators.h"
  17. #include "llvm/IR/LLVMContext.h"
  18. #include "llvm/IR/OptBisect.h"
  19. #include "llvm/IR/PassManager.h"
  20. #include "llvm/IR/PassTimingInfo.h"
  21. #include "llvm/IR/PrintPasses.h"
  22. #include "llvm/IR/StructuralHash.h"
  23. #include "llvm/InitializePasses.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Support/TimeProfiler.h"
  26. #include "llvm/Support/Timer.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. using namespace llvm;
  29. #define DEBUG_TYPE "loop-pass-manager"
  30. namespace {
  31. /// PrintLoopPass - Print a Function corresponding to a Loop.
  32. ///
  33. class PrintLoopPassWrapper : public LoopPass {
  34. raw_ostream &OS;
  35. std::string Banner;
  36. public:
  37. static char ID;
  38. PrintLoopPassWrapper() : LoopPass(ID), OS(dbgs()) {}
  39. PrintLoopPassWrapper(raw_ostream &OS, const std::string &Banner)
  40. : LoopPass(ID), OS(OS), Banner(Banner) {}
  41. void getAnalysisUsage(AnalysisUsage &AU) const override {
  42. AU.setPreservesAll();
  43. }
  44. bool runOnLoop(Loop *L, LPPassManager &) override {
  45. auto BBI = llvm::find_if(L->blocks(), [](BasicBlock *BB) { return BB; });
  46. if (BBI != L->blocks().end() &&
  47. isFunctionInPrintList((*BBI)->getParent()->getName())) {
  48. printLoop(*L, OS, Banner);
  49. }
  50. return false;
  51. }
  52. StringRef getPassName() const override { return "Print Loop IR"; }
  53. };
  54. char PrintLoopPassWrapper::ID = 0;
  55. }
  56. //===----------------------------------------------------------------------===//
  57. // LPPassManager
  58. //
  59. char LPPassManager::ID = 0;
  60. LPPassManager::LPPassManager() : FunctionPass(ID) {
  61. LI = nullptr;
  62. CurrentLoop = nullptr;
  63. }
  64. // Insert loop into loop nest (LoopInfo) and loop queue (LQ).
  65. void LPPassManager::addLoop(Loop &L) {
  66. if (L.isOutermost()) {
  67. // This is the top level loop.
  68. LQ.push_front(&L);
  69. return;
  70. }
  71. // Insert L into the loop queue after the parent loop.
  72. for (auto I = LQ.begin(), E = LQ.end(); I != E; ++I) {
  73. if (*I == L.getParentLoop()) {
  74. // deque does not support insert after.
  75. ++I;
  76. LQ.insert(I, 1, &L);
  77. return;
  78. }
  79. }
  80. }
  81. // Recurse through all subloops and all loops into LQ.
  82. static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
  83. LQ.push_back(L);
  84. for (Loop *I : reverse(*L))
  85. addLoopIntoQueue(I, LQ);
  86. }
  87. /// Pass Manager itself does not invalidate any analysis info.
  88. void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
  89. // LPPassManager needs LoopInfo. In the long term LoopInfo class will
  90. // become part of LPPassManager.
  91. Info.addRequired<LoopInfoWrapperPass>();
  92. Info.addRequired<DominatorTreeWrapperPass>();
  93. Info.setPreservesAll();
  94. }
  95. void LPPassManager::markLoopAsDeleted(Loop &L) {
  96. assert((&L == CurrentLoop || CurrentLoop->contains(&L)) &&
  97. "Must not delete loop outside the current loop tree!");
  98. // If this loop appears elsewhere within the queue, we also need to remove it
  99. // there. However, we have to be careful to not remove the back of the queue
  100. // as that is assumed to match the current loop.
  101. assert(LQ.back() == CurrentLoop && "Loop queue back isn't the current loop!");
  102. llvm::erase_value(LQ, &L);
  103. if (&L == CurrentLoop) {
  104. CurrentLoopDeleted = true;
  105. // Add this loop back onto the back of the queue to preserve our invariants.
  106. LQ.push_back(&L);
  107. }
  108. }
  109. /// run - Execute all of the passes scheduled for execution. Keep track of
  110. /// whether any of the passes modifies the function, and if so, return true.
  111. bool LPPassManager::runOnFunction(Function &F) {
  112. auto &LIWP = getAnalysis<LoopInfoWrapperPass>();
  113. LI = &LIWP.getLoopInfo();
  114. Module &M = *F.getParent();
  115. #if 0
  116. DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  117. #endif
  118. bool Changed = false;
  119. // Collect inherited analysis from Module level pass manager.
  120. populateInheritedAnalysis(TPM->activeStack);
  121. // Populate the loop queue in reverse program order. There is no clear need to
  122. // process sibling loops in either forward or reverse order. There may be some
  123. // advantage in deleting uses in a later loop before optimizing the
  124. // definitions in an earlier loop. If we find a clear reason to process in
  125. // forward order, then a forward variant of LoopPassManager should be created.
  126. //
  127. // Note that LoopInfo::iterator visits loops in reverse program
  128. // order. Here, reverse_iterator gives us a forward order, and the LoopQueue
  129. // reverses the order a third time by popping from the back.
  130. for (Loop *L : reverse(*LI))
  131. addLoopIntoQueue(L, LQ);
  132. if (LQ.empty()) // No loops, skip calling finalizers
  133. return false;
  134. // Initialization
  135. for (Loop *L : LQ) {
  136. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  137. LoopPass *P = getContainedPass(Index);
  138. Changed |= P->doInitialization(L, *this);
  139. }
  140. }
  141. // Walk Loops
  142. unsigned InstrCount, FunctionSize = 0;
  143. StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
  144. bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
  145. // Collect the initial size of the module and the function we're looking at.
  146. if (EmitICRemark) {
  147. InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
  148. FunctionSize = F.getInstructionCount();
  149. }
  150. while (!LQ.empty()) {
  151. CurrentLoopDeleted = false;
  152. CurrentLoop = LQ.back();
  153. // Run all passes on the current Loop.
  154. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  155. LoopPass *P = getContainedPass(Index);
  156. llvm::TimeTraceScope LoopPassScope("RunLoopPass", P->getPassName());
  157. dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
  158. CurrentLoop->getHeader()->getName());
  159. dumpRequiredSet(P);
  160. initializeAnalysisImpl(P);
  161. bool LocalChanged = false;
  162. {
  163. PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
  164. TimeRegion PassTimer(getPassTimer(P));
  165. #ifdef EXPENSIVE_CHECKS
  166. uint64_t RefHash = StructuralHash(F);
  167. #endif
  168. LocalChanged = P->runOnLoop(CurrentLoop, *this);
  169. #ifdef EXPENSIVE_CHECKS
  170. if (!LocalChanged && (RefHash != StructuralHash(F))) {
  171. llvm::errs() << "Pass modifies its input and doesn't report it: "
  172. << P->getPassName() << "\n";
  173. llvm_unreachable("Pass modifies its input and doesn't report it");
  174. }
  175. #endif
  176. Changed |= LocalChanged;
  177. if (EmitICRemark) {
  178. unsigned NewSize = F.getInstructionCount();
  179. // Update the size of the function, emit a remark, and update the
  180. // size of the module.
  181. if (NewSize != FunctionSize) {
  182. int64_t Delta = static_cast<int64_t>(NewSize) -
  183. static_cast<int64_t>(FunctionSize);
  184. emitInstrCountChangedRemark(P, M, Delta, InstrCount,
  185. FunctionToInstrCount, &F);
  186. InstrCount = static_cast<int64_t>(InstrCount) + Delta;
  187. FunctionSize = NewSize;
  188. }
  189. }
  190. }
  191. if (LocalChanged)
  192. dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
  193. CurrentLoopDeleted ? "<deleted loop>"
  194. : CurrentLoop->getName());
  195. dumpPreservedSet(P);
  196. if (!CurrentLoopDeleted) {
  197. // Manually check that this loop is still healthy. This is done
  198. // instead of relying on LoopInfo::verifyLoop since LoopInfo
  199. // is a function pass and it's really expensive to verify every
  200. // loop in the function every time. That level of checking can be
  201. // enabled with the -verify-loop-info option.
  202. {
  203. TimeRegion PassTimer(getPassTimer(&LIWP));
  204. CurrentLoop->verifyLoop();
  205. }
  206. // Here we apply same reasoning as in the above case. Only difference
  207. // is that LPPassManager might run passes which do not require LCSSA
  208. // form (LoopPassPrinter for example). We should skip verification for
  209. // such passes.
  210. // FIXME: Loop-sink currently break LCSSA. Fix it and reenable the
  211. // verification!
  212. #if 0
  213. if (mustPreserveAnalysisID(LCSSAVerificationPass::ID))
  214. assert(CurrentLoop->isRecursivelyLCSSAForm(*DT, *LI));
  215. #endif
  216. // Then call the regular verifyAnalysis functions.
  217. verifyPreservedAnalysis(P);
  218. F.getContext().yield();
  219. }
  220. if (LocalChanged)
  221. removeNotPreservedAnalysis(P);
  222. recordAvailableAnalysis(P);
  223. removeDeadPasses(P,
  224. CurrentLoopDeleted ? "<deleted>"
  225. : CurrentLoop->getHeader()->getName(),
  226. ON_LOOP_MSG);
  227. if (CurrentLoopDeleted)
  228. // Do not run other passes on this loop.
  229. break;
  230. }
  231. // If the loop was deleted, release all the loop passes. This frees up
  232. // some memory, and avoids trouble with the pass manager trying to call
  233. // verifyAnalysis on them.
  234. if (CurrentLoopDeleted) {
  235. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  236. Pass *P = getContainedPass(Index);
  237. freePass(P, "<deleted>", ON_LOOP_MSG);
  238. }
  239. }
  240. // Pop the loop from queue after running all passes.
  241. LQ.pop_back();
  242. }
  243. // Finalization
  244. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  245. LoopPass *P = getContainedPass(Index);
  246. Changed |= P->doFinalization();
  247. }
  248. return Changed;
  249. }
  250. /// Print passes managed by this manager
  251. void LPPassManager::dumpPassStructure(unsigned Offset) {
  252. errs().indent(Offset*2) << "Loop Pass Manager\n";
  253. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
  254. Pass *P = getContainedPass(Index);
  255. P->dumpPassStructure(Offset + 1);
  256. dumpLastUses(P, Offset+1);
  257. }
  258. }
  259. //===----------------------------------------------------------------------===//
  260. // LoopPass
  261. Pass *LoopPass::createPrinterPass(raw_ostream &O,
  262. const std::string &Banner) const {
  263. return new PrintLoopPassWrapper(O, Banner);
  264. }
  265. // Check if this pass is suitable for the current LPPassManager, if
  266. // available. This pass P is not suitable for a LPPassManager if P
  267. // is not preserving higher level analysis info used by other
  268. // LPPassManager passes. In such case, pop LPPassManager from the
  269. // stack. This will force assignPassManager() to create new
  270. // LPPassManger as expected.
  271. void LoopPass::preparePassManager(PMStack &PMS) {
  272. // Find LPPassManager
  273. while (!PMS.empty() &&
  274. PMS.top()->getPassManagerType() > PMT_LoopPassManager)
  275. PMS.pop();
  276. // If this pass is destroying high level information that is used
  277. // by other passes that are managed by LPM then do not insert
  278. // this pass in current LPM. Use new LPPassManager.
  279. if (PMS.top()->getPassManagerType() == PMT_LoopPassManager &&
  280. !PMS.top()->preserveHigherLevelAnalysis(this))
  281. PMS.pop();
  282. }
  283. /// Assign pass manager to manage this pass.
  284. void LoopPass::assignPassManager(PMStack &PMS,
  285. PassManagerType PreferredType) {
  286. // Find LPPassManager
  287. while (!PMS.empty() &&
  288. PMS.top()->getPassManagerType() > PMT_LoopPassManager)
  289. PMS.pop();
  290. LPPassManager *LPPM;
  291. if (PMS.top()->getPassManagerType() == PMT_LoopPassManager)
  292. LPPM = (LPPassManager*)PMS.top();
  293. else {
  294. // Create new Loop Pass Manager if it does not exist.
  295. assert (!PMS.empty() && "Unable to create Loop Pass Manager");
  296. PMDataManager *PMD = PMS.top();
  297. // [1] Create new Loop Pass Manager
  298. LPPM = new LPPassManager();
  299. LPPM->populateInheritedAnalysis(PMS);
  300. // [2] Set up new manager's top level manager
  301. PMTopLevelManager *TPM = PMD->getTopLevelManager();
  302. TPM->addIndirectPassManager(LPPM);
  303. // [3] Assign manager to manage this new manager. This may create
  304. // and push new managers into PMS
  305. Pass *P = LPPM->getAsPass();
  306. TPM->schedulePass(P);
  307. // [4] Push new manager into PMS
  308. PMS.push(LPPM);
  309. }
  310. LPPM->add(this);
  311. }
  312. static std::string getDescription(const Loop &L) {
  313. return "loop";
  314. }
  315. bool LoopPass::skipLoop(const Loop *L) const {
  316. const Function *F = L->getHeader()->getParent();
  317. if (!F)
  318. return false;
  319. // Check the opt bisect limit.
  320. OptPassGate &Gate = F->getContext().getOptPassGate();
  321. if (Gate.isEnabled() && !Gate.shouldRunPass(this, getDescription(*L)))
  322. return true;
  323. // Check for the OptimizeNone attribute.
  324. if (F->hasOptNone()) {
  325. // FIXME: Report this to dbgs() only once per function.
  326. LLVM_DEBUG(dbgs() << "Skipping pass '" << getPassName() << "' in function "
  327. << F->getName() << "\n");
  328. // FIXME: Delete loop from pass manager's queue?
  329. return true;
  330. }
  331. return false;
  332. }
  333. LCSSAVerificationPass::LCSSAVerificationPass() : FunctionPass(ID) {
  334. initializeLCSSAVerificationPassPass(*PassRegistry::getPassRegistry());
  335. }
  336. char LCSSAVerificationPass::ID = 0;
  337. INITIALIZE_PASS(LCSSAVerificationPass, "lcssa-verification", "LCSSA Verifier",
  338. false, false)