LoopNestAnalysis.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. //===- LoopNestAnalysis.cpp - Loop Nest Analysis --------------------------==//
  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. /// \file
  10. /// The implementation for the loop nest analysis.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/LoopNestAnalysis.h"
  14. #include "llvm/ADT/BreadthFirstIterator.h"
  15. #include "llvm/ADT/DepthFirstIterator.h"
  16. #include "llvm/Analysis/ValueTracking.h"
  17. using namespace llvm;
  18. #define DEBUG_TYPE "loopnest"
  19. #ifndef NDEBUG
  20. static const char *VerboseDebug = DEBUG_TYPE "-verbose";
  21. #endif
  22. /// Determine whether the loops structure violates basic requirements for
  23. /// perfect nesting:
  24. /// - the inner loop should be the outer loop's only child
  25. /// - the outer loop header should 'flow' into the inner loop preheader
  26. /// or jump around the inner loop to the outer loop latch
  27. /// - if the inner loop latch exits the inner loop, it should 'flow' into
  28. /// the outer loop latch.
  29. /// Returns true if the loop structure satisfies the basic requirements and
  30. /// false otherwise.
  31. static bool checkLoopsStructure(const Loop &OuterLoop, const Loop &InnerLoop,
  32. ScalarEvolution &SE);
  33. //===----------------------------------------------------------------------===//
  34. // LoopNest implementation
  35. //
  36. LoopNest::LoopNest(Loop &Root, ScalarEvolution &SE)
  37. : MaxPerfectDepth(getMaxPerfectDepth(Root, SE)) {
  38. append_range(Loops, breadth_first(&Root));
  39. }
  40. std::unique_ptr<LoopNest> LoopNest::getLoopNest(Loop &Root,
  41. ScalarEvolution &SE) {
  42. return std::make_unique<LoopNest>(Root, SE);
  43. }
  44. static CmpInst *getOuterLoopLatchCmp(const Loop &OuterLoop) {
  45. const BasicBlock *Latch = OuterLoop.getLoopLatch();
  46. assert(Latch && "Expecting a valid loop latch");
  47. const BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
  48. assert(BI && BI->isConditional() &&
  49. "Expecting loop latch terminator to be a branch instruction");
  50. CmpInst *OuterLoopLatchCmp = dyn_cast<CmpInst>(BI->getCondition());
  51. DEBUG_WITH_TYPE(
  52. VerboseDebug, if (OuterLoopLatchCmp) {
  53. dbgs() << "Outer loop latch compare instruction: " << *OuterLoopLatchCmp
  54. << "\n";
  55. });
  56. return OuterLoopLatchCmp;
  57. }
  58. static CmpInst *getInnerLoopGuardCmp(const Loop &InnerLoop) {
  59. BranchInst *InnerGuard = InnerLoop.getLoopGuardBranch();
  60. CmpInst *InnerLoopGuardCmp =
  61. (InnerGuard) ? dyn_cast<CmpInst>(InnerGuard->getCondition()) : nullptr;
  62. DEBUG_WITH_TYPE(
  63. VerboseDebug, if (InnerLoopGuardCmp) {
  64. dbgs() << "Inner loop guard compare instruction: " << *InnerLoopGuardCmp
  65. << "\n";
  66. });
  67. return InnerLoopGuardCmp;
  68. }
  69. static bool checkSafeInstruction(const Instruction &I,
  70. const CmpInst *InnerLoopGuardCmp,
  71. const CmpInst *OuterLoopLatchCmp,
  72. std::optional<Loop::LoopBounds> OuterLoopLB) {
  73. bool IsAllowed =
  74. isSafeToSpeculativelyExecute(&I) || isa<PHINode>(I) || isa<BranchInst>(I);
  75. if (!IsAllowed)
  76. return false;
  77. // The only binary instruction allowed is the outer loop step instruction,
  78. // the only comparison instructions allowed are the inner loop guard
  79. // compare instruction and the outer loop latch compare instruction.
  80. if ((isa<BinaryOperator>(I) && &I != &OuterLoopLB->getStepInst()) ||
  81. (isa<CmpInst>(I) && &I != OuterLoopLatchCmp && &I != InnerLoopGuardCmp)) {
  82. return false;
  83. }
  84. return true;
  85. }
  86. bool LoopNest::arePerfectlyNested(const Loop &OuterLoop, const Loop &InnerLoop,
  87. ScalarEvolution &SE) {
  88. return (analyzeLoopNestForPerfectNest(OuterLoop, InnerLoop, SE) ==
  89. PerfectLoopNest);
  90. }
  91. LoopNest::LoopNestEnum LoopNest::analyzeLoopNestForPerfectNest(
  92. const Loop &OuterLoop, const Loop &InnerLoop, ScalarEvolution &SE) {
  93. assert(!OuterLoop.isInnermost() && "Outer loop should have subloops");
  94. assert(!InnerLoop.isOutermost() && "Inner loop should have a parent");
  95. LLVM_DEBUG(dbgs() << "Checking whether loop '" << OuterLoop.getName()
  96. << "' and '" << InnerLoop.getName()
  97. << "' are perfectly nested.\n");
  98. // Determine whether the loops structure satisfies the following requirements:
  99. // - the inner loop should be the outer loop's only child
  100. // - the outer loop header should 'flow' into the inner loop preheader
  101. // or jump around the inner loop to the outer loop latch
  102. // - if the inner loop latch exits the inner loop, it should 'flow' into
  103. // the outer loop latch.
  104. if (!checkLoopsStructure(OuterLoop, InnerLoop, SE)) {
  105. LLVM_DEBUG(dbgs() << "Not perfectly nested: invalid loop structure.\n");
  106. return InvalidLoopStructure;
  107. }
  108. // Bail out if we cannot retrieve the outer loop bounds.
  109. auto OuterLoopLB = OuterLoop.getBounds(SE);
  110. if (OuterLoopLB == std::nullopt) {
  111. LLVM_DEBUG(dbgs() << "Cannot compute loop bounds of OuterLoop: "
  112. << OuterLoop << "\n";);
  113. return OuterLoopLowerBoundUnknown;
  114. }
  115. CmpInst *OuterLoopLatchCmp = getOuterLoopLatchCmp(OuterLoop);
  116. CmpInst *InnerLoopGuardCmp = getInnerLoopGuardCmp(InnerLoop);
  117. // Determine whether instructions in a basic block are one of:
  118. // - the inner loop guard comparison
  119. // - the outer loop latch comparison
  120. // - the outer loop induction variable increment
  121. // - a phi node, a cast or a branch
  122. auto containsOnlySafeInstructions = [&](const BasicBlock &BB) {
  123. return llvm::all_of(BB, [&](const Instruction &I) {
  124. bool IsSafeInstr = checkSafeInstruction(I, InnerLoopGuardCmp,
  125. OuterLoopLatchCmp, OuterLoopLB);
  126. if (IsSafeInstr) {
  127. DEBUG_WITH_TYPE(VerboseDebug, {
  128. dbgs() << "Instruction: " << I << "\nin basic block:" << BB
  129. << "is unsafe.\n";
  130. });
  131. }
  132. return IsSafeInstr;
  133. });
  134. };
  135. // Check the code surrounding the inner loop for instructions that are deemed
  136. // unsafe.
  137. const BasicBlock *OuterLoopHeader = OuterLoop.getHeader();
  138. const BasicBlock *OuterLoopLatch = OuterLoop.getLoopLatch();
  139. const BasicBlock *InnerLoopPreHeader = InnerLoop.getLoopPreheader();
  140. if (!containsOnlySafeInstructions(*OuterLoopHeader) ||
  141. !containsOnlySafeInstructions(*OuterLoopLatch) ||
  142. (InnerLoopPreHeader != OuterLoopHeader &&
  143. !containsOnlySafeInstructions(*InnerLoopPreHeader)) ||
  144. !containsOnlySafeInstructions(*InnerLoop.getExitBlock())) {
  145. LLVM_DEBUG(dbgs() << "Not perfectly nested: code surrounding inner loop is "
  146. "unsafe\n";);
  147. return ImperfectLoopNest;
  148. }
  149. LLVM_DEBUG(dbgs() << "Loop '" << OuterLoop.getName() << "' and '"
  150. << InnerLoop.getName() << "' are perfectly nested.\n");
  151. return PerfectLoopNest;
  152. }
  153. LoopNest::InstrVectorTy LoopNest::getInterveningInstructions(
  154. const Loop &OuterLoop, const Loop &InnerLoop, ScalarEvolution &SE) {
  155. InstrVectorTy Instr;
  156. switch (analyzeLoopNestForPerfectNest(OuterLoop, InnerLoop, SE)) {
  157. case PerfectLoopNest:
  158. LLVM_DEBUG(dbgs() << "The loop Nest is Perfect, returning empty "
  159. "instruction vector. \n";);
  160. return Instr;
  161. case InvalidLoopStructure:
  162. LLVM_DEBUG(dbgs() << "Not perfectly nested: invalid loop structure. "
  163. "Instruction vector is empty.\n";);
  164. return Instr;
  165. case OuterLoopLowerBoundUnknown:
  166. LLVM_DEBUG(dbgs() << "Cannot compute loop bounds of OuterLoop: "
  167. << OuterLoop << "\nInstruction vector is empty.\n";);
  168. return Instr;
  169. case ImperfectLoopNest:
  170. break;
  171. }
  172. // Identify the outer loop latch comparison instruction.
  173. auto OuterLoopLB = OuterLoop.getBounds(SE);
  174. CmpInst *OuterLoopLatchCmp = getOuterLoopLatchCmp(OuterLoop);
  175. CmpInst *InnerLoopGuardCmp = getInnerLoopGuardCmp(InnerLoop);
  176. auto GetUnsafeInstructions = [&](const BasicBlock &BB) {
  177. for (const Instruction &I : BB) {
  178. if (!checkSafeInstruction(I, InnerLoopGuardCmp, OuterLoopLatchCmp,
  179. OuterLoopLB)) {
  180. Instr.push_back(&I);
  181. DEBUG_WITH_TYPE(VerboseDebug, {
  182. dbgs() << "Instruction: " << I << "\nin basic block:" << BB
  183. << "is unsafe.\n";
  184. });
  185. }
  186. }
  187. };
  188. // Check the code surrounding the inner loop for instructions that are deemed
  189. // unsafe.
  190. const BasicBlock *OuterLoopHeader = OuterLoop.getHeader();
  191. const BasicBlock *OuterLoopLatch = OuterLoop.getLoopLatch();
  192. const BasicBlock *InnerLoopPreHeader = InnerLoop.getLoopPreheader();
  193. const BasicBlock *InnerLoopExitBlock = InnerLoop.getExitBlock();
  194. GetUnsafeInstructions(*OuterLoopHeader);
  195. GetUnsafeInstructions(*OuterLoopLatch);
  196. GetUnsafeInstructions(*InnerLoopExitBlock);
  197. if (InnerLoopPreHeader != OuterLoopHeader) {
  198. GetUnsafeInstructions(*InnerLoopPreHeader);
  199. }
  200. return Instr;
  201. }
  202. SmallVector<LoopVectorTy, 4>
  203. LoopNest::getPerfectLoops(ScalarEvolution &SE) const {
  204. SmallVector<LoopVectorTy, 4> LV;
  205. LoopVectorTy PerfectNest;
  206. for (Loop *L : depth_first(const_cast<Loop *>(Loops.front()))) {
  207. if (PerfectNest.empty())
  208. PerfectNest.push_back(L);
  209. auto &SubLoops = L->getSubLoops();
  210. if (SubLoops.size() == 1 && arePerfectlyNested(*L, *SubLoops.front(), SE)) {
  211. PerfectNest.push_back(SubLoops.front());
  212. } else {
  213. LV.push_back(PerfectNest);
  214. PerfectNest.clear();
  215. }
  216. }
  217. return LV;
  218. }
  219. unsigned LoopNest::getMaxPerfectDepth(const Loop &Root, ScalarEvolution &SE) {
  220. LLVM_DEBUG(dbgs() << "Get maximum perfect depth of loop nest rooted by loop '"
  221. << Root.getName() << "'\n");
  222. const Loop *CurrentLoop = &Root;
  223. const auto *SubLoops = &CurrentLoop->getSubLoops();
  224. unsigned CurrentDepth = 1;
  225. while (SubLoops->size() == 1) {
  226. const Loop *InnerLoop = SubLoops->front();
  227. if (!arePerfectlyNested(*CurrentLoop, *InnerLoop, SE)) {
  228. LLVM_DEBUG({
  229. dbgs() << "Not a perfect nest: loop '" << CurrentLoop->getName()
  230. << "' is not perfectly nested with loop '"
  231. << InnerLoop->getName() << "'\n";
  232. });
  233. break;
  234. }
  235. CurrentLoop = InnerLoop;
  236. SubLoops = &CurrentLoop->getSubLoops();
  237. ++CurrentDepth;
  238. }
  239. return CurrentDepth;
  240. }
  241. const BasicBlock &LoopNest::skipEmptyBlockUntil(const BasicBlock *From,
  242. const BasicBlock *End,
  243. bool CheckUniquePred) {
  244. assert(From && "Expecting valid From");
  245. assert(End && "Expecting valid End");
  246. if (From == End || !From->getUniqueSuccessor())
  247. return *From;
  248. auto IsEmpty = [](const BasicBlock *BB) {
  249. return (BB->size() == 1);
  250. };
  251. // Visited is used to avoid running into an infinite loop.
  252. SmallPtrSet<const BasicBlock *, 4> Visited;
  253. const BasicBlock *BB = From->getUniqueSuccessor();
  254. const BasicBlock *PredBB = From;
  255. while (BB && BB != End && IsEmpty(BB) && !Visited.count(BB) &&
  256. (!CheckUniquePred || BB->getUniquePredecessor())) {
  257. Visited.insert(BB);
  258. PredBB = BB;
  259. BB = BB->getUniqueSuccessor();
  260. }
  261. return (BB == End) ? *End : *PredBB;
  262. }
  263. static bool checkLoopsStructure(const Loop &OuterLoop, const Loop &InnerLoop,
  264. ScalarEvolution &SE) {
  265. // The inner loop must be the only outer loop's child.
  266. if ((OuterLoop.getSubLoops().size() != 1) ||
  267. (InnerLoop.getParentLoop() != &OuterLoop))
  268. return false;
  269. // We expect loops in normal form which have a preheader, header, latch...
  270. if (!OuterLoop.isLoopSimplifyForm() || !InnerLoop.isLoopSimplifyForm())
  271. return false;
  272. const BasicBlock *OuterLoopHeader = OuterLoop.getHeader();
  273. const BasicBlock *OuterLoopLatch = OuterLoop.getLoopLatch();
  274. const BasicBlock *InnerLoopPreHeader = InnerLoop.getLoopPreheader();
  275. const BasicBlock *InnerLoopLatch = InnerLoop.getLoopLatch();
  276. const BasicBlock *InnerLoopExit = InnerLoop.getExitBlock();
  277. // We expect rotated loops. The inner loop should have a single exit block.
  278. if (OuterLoop.getExitingBlock() != OuterLoopLatch ||
  279. InnerLoop.getExitingBlock() != InnerLoopLatch || !InnerLoopExit)
  280. return false;
  281. // Returns whether the block `ExitBlock` contains at least one LCSSA Phi node.
  282. auto ContainsLCSSAPhi = [](const BasicBlock &ExitBlock) {
  283. return any_of(ExitBlock.phis(), [](const PHINode &PN) {
  284. return PN.getNumIncomingValues() == 1;
  285. });
  286. };
  287. // Returns whether the block `BB` qualifies for being an extra Phi block. The
  288. // extra Phi block is the additional block inserted after the exit block of an
  289. // "guarded" inner loop which contains "only" Phi nodes corresponding to the
  290. // LCSSA Phi nodes in the exit block.
  291. auto IsExtraPhiBlock = [&](const BasicBlock &BB) {
  292. return BB.getFirstNonPHI() == BB.getTerminator() &&
  293. all_of(BB.phis(), [&](const PHINode &PN) {
  294. return all_of(PN.blocks(), [&](const BasicBlock *IncomingBlock) {
  295. return IncomingBlock == InnerLoopExit ||
  296. IncomingBlock == OuterLoopHeader;
  297. });
  298. });
  299. };
  300. const BasicBlock *ExtraPhiBlock = nullptr;
  301. // Ensure the only branch that may exist between the loops is the inner loop
  302. // guard.
  303. if (OuterLoopHeader != InnerLoopPreHeader) {
  304. const BasicBlock &SingleSucc =
  305. LoopNest::skipEmptyBlockUntil(OuterLoopHeader, InnerLoopPreHeader);
  306. // no conditional branch present
  307. if (&SingleSucc != InnerLoopPreHeader) {
  308. const BranchInst *BI = dyn_cast<BranchInst>(SingleSucc.getTerminator());
  309. if (!BI || BI != InnerLoop.getLoopGuardBranch())
  310. return false;
  311. bool InnerLoopExitContainsLCSSA = ContainsLCSSAPhi(*InnerLoopExit);
  312. // The successors of the inner loop guard should be the inner loop
  313. // preheader or the outer loop latch possibly through empty blocks.
  314. for (const BasicBlock *Succ : BI->successors()) {
  315. const BasicBlock *PotentialInnerPreHeader = Succ;
  316. const BasicBlock *PotentialOuterLatch = Succ;
  317. // Ensure the inner loop guard successor is empty before skipping
  318. // blocks.
  319. if (Succ->size() == 1) {
  320. PotentialInnerPreHeader =
  321. &LoopNest::skipEmptyBlockUntil(Succ, InnerLoopPreHeader);
  322. PotentialOuterLatch =
  323. &LoopNest::skipEmptyBlockUntil(Succ, OuterLoopLatch);
  324. }
  325. if (PotentialInnerPreHeader == InnerLoopPreHeader)
  326. continue;
  327. if (PotentialOuterLatch == OuterLoopLatch)
  328. continue;
  329. // If `InnerLoopExit` contains LCSSA Phi instructions, additional block
  330. // may be inserted before the `OuterLoopLatch` to which `BI` jumps. The
  331. // loops are still considered perfectly nested if the extra block only
  332. // contains Phi instructions from InnerLoopExit and OuterLoopHeader.
  333. if (InnerLoopExitContainsLCSSA && IsExtraPhiBlock(*Succ) &&
  334. Succ->getSingleSuccessor() == OuterLoopLatch) {
  335. // Points to the extra block so that we can reference it later in the
  336. // final check. We can also conclude that the inner loop is
  337. // guarded and there exists LCSSA Phi node in the exit block later if
  338. // we see a non-null `ExtraPhiBlock`.
  339. ExtraPhiBlock = Succ;
  340. continue;
  341. }
  342. DEBUG_WITH_TYPE(VerboseDebug, {
  343. dbgs() << "Inner loop guard successor " << Succ->getName()
  344. << " doesn't lead to inner loop preheader or "
  345. "outer loop latch.\n";
  346. });
  347. return false;
  348. }
  349. }
  350. }
  351. // Ensure the inner loop exit block lead to the outer loop latch possibly
  352. // through empty blocks.
  353. if ((!ExtraPhiBlock ||
  354. &LoopNest::skipEmptyBlockUntil(InnerLoop.getExitBlock(),
  355. ExtraPhiBlock) != ExtraPhiBlock) &&
  356. (&LoopNest::skipEmptyBlockUntil(InnerLoop.getExitBlock(),
  357. OuterLoopLatch) != OuterLoopLatch)) {
  358. DEBUG_WITH_TYPE(
  359. VerboseDebug,
  360. dbgs() << "Inner loop exit block " << *InnerLoopExit
  361. << " does not directly lead to the outer loop latch.\n";);
  362. return false;
  363. }
  364. return true;
  365. }
  366. AnalysisKey LoopNestAnalysis::Key;
  367. raw_ostream &llvm::operator<<(raw_ostream &OS, const LoopNest &LN) {
  368. OS << "IsPerfect=";
  369. if (LN.getMaxPerfectDepth() == LN.getNestDepth())
  370. OS << "true";
  371. else
  372. OS << "false";
  373. OS << ", Depth=" << LN.getNestDepth();
  374. OS << ", OutermostLoop: " << LN.getOutermostLoop().getName();
  375. OS << ", Loops: ( ";
  376. for (const Loop *L : LN.getLoops())
  377. OS << L->getName() << " ";
  378. OS << ")";
  379. return OS;
  380. }
  381. //===----------------------------------------------------------------------===//
  382. // LoopNestPrinterPass implementation
  383. //
  384. PreservedAnalyses LoopNestPrinterPass::run(Loop &L, LoopAnalysisManager &AM,
  385. LoopStandardAnalysisResults &AR,
  386. LPMUpdater &U) {
  387. if (auto LN = LoopNest::getLoopNest(L, AR.SE))
  388. OS << *LN << "\n";
  389. return PreservedAnalyses::all();
  390. }