LoopPass.cpp 13 KB

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