LoopPass.cpp 14 KB

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