LoopUnrollAndJam.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. //===-- LoopUnrollAndJam.cpp - Loop unrolling utilities -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements loop unroll and jam as a routine, much like
  11. // LoopUnroll.cpp implements loop unroll.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/SmallPtrSet.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/Analysis/AssumptionCache.h"
  17. #include "llvm/Analysis/DependenceAnalysis.h"
  18. #include "llvm/Analysis/InstructionSimplify.h"
  19. #include "llvm/Analysis/LoopAnalysisManager.h"
  20. #include "llvm/Analysis/LoopIterator.h"
  21. #include "llvm/Analysis/LoopPass.h"
  22. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  23. #include "llvm/Analysis/ScalarEvolution.h"
  24. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  25. #include "llvm/Analysis/Utils/Local.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/DebugInfoMetadata.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/IntrinsicInst.h"
  31. #include "llvm/IR/LLVMContext.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  35. #include "llvm/Transforms/Utils/Cloning.h"
  36. #include "llvm/Transforms/Utils/LoopSimplify.h"
  37. #include "llvm/Transforms/Utils/LoopUtils.h"
  38. #include "llvm/Transforms/Utils/SimplifyIndVar.h"
  39. #include "llvm/Transforms/Utils/UnrollLoop.h"
  40. using namespace llvm;
  41. #define DEBUG_TYPE "loop-unroll-and-jam"
  42. STATISTIC(NumUnrolledAndJammed, "Number of loops unroll and jammed");
  43. STATISTIC(NumCompletelyUnrolledAndJammed, "Number of loops unroll and jammed");
  44. typedef SmallPtrSet<BasicBlock *, 4> BasicBlockSet;
  45. // Partition blocks in an outer/inner loop pair into blocks before and after
  46. // the loop
  47. static bool partitionOuterLoopBlocks(Loop *L, Loop *SubLoop,
  48. BasicBlockSet &ForeBlocks,
  49. BasicBlockSet &SubLoopBlocks,
  50. BasicBlockSet &AftBlocks,
  51. DominatorTree *DT) {
  52. BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
  53. SubLoopBlocks.insert(SubLoop->block_begin(), SubLoop->block_end());
  54. for (BasicBlock *BB : L->blocks()) {
  55. if (!SubLoop->contains(BB)) {
  56. if (DT->dominates(SubLoopLatch, BB))
  57. AftBlocks.insert(BB);
  58. else
  59. ForeBlocks.insert(BB);
  60. }
  61. }
  62. // Check that all blocks in ForeBlocks together dominate the subloop
  63. // TODO: This might ideally be done better with a dominator/postdominators.
  64. BasicBlock *SubLoopPreHeader = SubLoop->getLoopPreheader();
  65. for (BasicBlock *BB : ForeBlocks) {
  66. if (BB == SubLoopPreHeader)
  67. continue;
  68. Instruction *TI = BB->getTerminator();
  69. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  70. if (!ForeBlocks.count(TI->getSuccessor(i)))
  71. return false;
  72. }
  73. return true;
  74. }
  75. // Looks at the phi nodes in Header for values coming from Latch. For these
  76. // instructions and all their operands calls Visit on them, keeping going for
  77. // all the operands in AftBlocks. Returns false if Visit returns false,
  78. // otherwise returns true. This is used to process the instructions in the
  79. // Aft blocks that need to be moved before the subloop. It is used in two
  80. // places. One to check that the required set of instructions can be moved
  81. // before the loop. Then to collect the instructions to actually move in
  82. // moveHeaderPhiOperandsToForeBlocks.
  83. template <typename T>
  84. static bool processHeaderPhiOperands(BasicBlock *Header, BasicBlock *Latch,
  85. BasicBlockSet &AftBlocks, T Visit) {
  86. SmallVector<Instruction *, 8> Worklist;
  87. for (auto &Phi : Header->phis()) {
  88. Value *V = Phi.getIncomingValueForBlock(Latch);
  89. if (Instruction *I = dyn_cast<Instruction>(V))
  90. Worklist.push_back(I);
  91. }
  92. while (!Worklist.empty()) {
  93. Instruction *I = Worklist.back();
  94. Worklist.pop_back();
  95. if (!Visit(I))
  96. return false;
  97. if (AftBlocks.count(I->getParent()))
  98. for (auto &U : I->operands())
  99. if (Instruction *II = dyn_cast<Instruction>(U))
  100. Worklist.push_back(II);
  101. }
  102. return true;
  103. }
  104. // Move the phi operands of Header from Latch out of AftBlocks to InsertLoc.
  105. static void moveHeaderPhiOperandsToForeBlocks(BasicBlock *Header,
  106. BasicBlock *Latch,
  107. Instruction *InsertLoc,
  108. BasicBlockSet &AftBlocks) {
  109. // We need to ensure we move the instructions in the correct order,
  110. // starting with the earliest required instruction and moving forward.
  111. std::vector<Instruction *> Visited;
  112. processHeaderPhiOperands(Header, Latch, AftBlocks,
  113. [&Visited, &AftBlocks](Instruction *I) {
  114. if (AftBlocks.count(I->getParent()))
  115. Visited.push_back(I);
  116. return true;
  117. });
  118. // Move all instructions in program order to before the InsertLoc
  119. BasicBlock *InsertLocBB = InsertLoc->getParent();
  120. for (Instruction *I : reverse(Visited)) {
  121. if (I->getParent() != InsertLocBB)
  122. I->moveBefore(InsertLoc);
  123. }
  124. }
  125. /*
  126. This method performs Unroll and Jam. For a simple loop like:
  127. for (i = ..)
  128. Fore(i)
  129. for (j = ..)
  130. SubLoop(i, j)
  131. Aft(i)
  132. Instead of doing normal inner or outer unrolling, we do:
  133. for (i = .., i+=2)
  134. Fore(i)
  135. Fore(i+1)
  136. for (j = ..)
  137. SubLoop(i, j)
  138. SubLoop(i+1, j)
  139. Aft(i)
  140. Aft(i+1)
  141. So the outer loop is essetially unrolled and then the inner loops are fused
  142. ("jammed") together into a single loop. This can increase speed when there
  143. are loads in SubLoop that are invariant to i, as they become shared between
  144. the now jammed inner loops.
  145. We do this by spliting the blocks in the loop into Fore, Subloop and Aft.
  146. Fore blocks are those before the inner loop, Aft are those after. Normal
  147. Unroll code is used to copy each of these sets of blocks and the results are
  148. combined together into the final form above.
  149. isSafeToUnrollAndJam should be used prior to calling this to make sure the
  150. unrolling will be valid. Checking profitablility is also advisable.
  151. If EpilogueLoop is non-null, it receives the epilogue loop (if it was
  152. necessary to create one and not fully unrolled).
  153. */
  154. LoopUnrollResult llvm::UnrollAndJamLoop(
  155. Loop *L, unsigned Count, unsigned TripCount, unsigned TripMultiple,
  156. bool UnrollRemainder, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
  157. AssumptionCache *AC, OptimizationRemarkEmitter *ORE, Loop **EpilogueLoop) {
  158. // When we enter here we should have already checked that it is safe
  159. BasicBlock *Header = L->getHeader();
  160. assert(L->getSubLoops().size() == 1);
  161. Loop *SubLoop = *L->begin();
  162. // Don't enter the unroll code if there is nothing to do.
  163. if (TripCount == 0 && Count < 2) {
  164. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; almost nothing to do\n");
  165. return LoopUnrollResult::Unmodified;
  166. }
  167. assert(Count > 0);
  168. assert(TripMultiple > 0);
  169. assert(TripCount == 0 || TripCount % TripMultiple == 0);
  170. // Are we eliminating the loop control altogether?
  171. bool CompletelyUnroll = (Count == TripCount);
  172. // We use the runtime remainder in cases where we don't know trip multiple
  173. if (TripMultiple == 1 || TripMultiple % Count != 0) {
  174. if (!UnrollRuntimeLoopRemainder(L, Count, /*AllowExpensiveTripCount*/ false,
  175. /*UseEpilogRemainder*/ true,
  176. UnrollRemainder, LI, SE, DT, AC, true,
  177. EpilogueLoop)) {
  178. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; remainder loop could not be "
  179. "generated when assuming runtime trip count\n");
  180. return LoopUnrollResult::Unmodified;
  181. }
  182. }
  183. // Notify ScalarEvolution that the loop will be substantially changed,
  184. // if not outright eliminated.
  185. if (SE) {
  186. SE->forgetLoop(L);
  187. SE->forgetLoop(SubLoop);
  188. }
  189. using namespace ore;
  190. // Report the unrolling decision.
  191. if (CompletelyUnroll) {
  192. LLVM_DEBUG(dbgs() << "COMPLETELY UNROLL AND JAMMING loop %"
  193. << Header->getName() << " with trip count " << TripCount
  194. << "!\n");
  195. ORE->emit(OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
  196. L->getHeader())
  197. << "completely unroll and jammed loop with "
  198. << NV("UnrollCount", TripCount) << " iterations");
  199. } else {
  200. auto DiagBuilder = [&]() {
  201. OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
  202. L->getHeader());
  203. return Diag << "unroll and jammed loop by a factor of "
  204. << NV("UnrollCount", Count);
  205. };
  206. LLVM_DEBUG(dbgs() << "UNROLL AND JAMMING loop %" << Header->getName()
  207. << " by " << Count);
  208. if (TripMultiple != 1) {
  209. LLVM_DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
  210. ORE->emit([&]() {
  211. return DiagBuilder() << " with " << NV("TripMultiple", TripMultiple)
  212. << " trips per branch";
  213. });
  214. } else {
  215. LLVM_DEBUG(dbgs() << " with run-time trip count");
  216. ORE->emit([&]() { return DiagBuilder() << " with run-time trip count"; });
  217. }
  218. LLVM_DEBUG(dbgs() << "!\n");
  219. }
  220. BasicBlock *Preheader = L->getLoopPreheader();
  221. BasicBlock *LatchBlock = L->getLoopLatch();
  222. BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
  223. assert(Preheader && LatchBlock && Header);
  224. assert(BI && !BI->isUnconditional());
  225. bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
  226. BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
  227. bool SubLoopContinueOnTrue = SubLoop->contains(
  228. SubLoop->getLoopLatch()->getTerminator()->getSuccessor(0));
  229. // Partition blocks in an outer/inner loop pair into blocks before and after
  230. // the loop
  231. BasicBlockSet SubLoopBlocks;
  232. BasicBlockSet ForeBlocks;
  233. BasicBlockSet AftBlocks;
  234. partitionOuterLoopBlocks(L, SubLoop, ForeBlocks, SubLoopBlocks, AftBlocks,
  235. DT);
  236. // We keep track of the entering/first and exiting/last block of each of
  237. // Fore/SubLoop/Aft in each iteration. This helps make the stapling up of
  238. // blocks easier.
  239. std::vector<BasicBlock *> ForeBlocksFirst;
  240. std::vector<BasicBlock *> ForeBlocksLast;
  241. std::vector<BasicBlock *> SubLoopBlocksFirst;
  242. std::vector<BasicBlock *> SubLoopBlocksLast;
  243. std::vector<BasicBlock *> AftBlocksFirst;
  244. std::vector<BasicBlock *> AftBlocksLast;
  245. ForeBlocksFirst.push_back(Header);
  246. ForeBlocksLast.push_back(SubLoop->getLoopPreheader());
  247. SubLoopBlocksFirst.push_back(SubLoop->getHeader());
  248. SubLoopBlocksLast.push_back(SubLoop->getExitingBlock());
  249. AftBlocksFirst.push_back(SubLoop->getExitBlock());
  250. AftBlocksLast.push_back(L->getExitingBlock());
  251. // Maps Blocks[0] -> Blocks[It]
  252. ValueToValueMapTy LastValueMap;
  253. // Move any instructions from fore phi operands from AftBlocks into Fore.
  254. moveHeaderPhiOperandsToForeBlocks(
  255. Header, LatchBlock, SubLoop->getLoopPreheader()->getTerminator(),
  256. AftBlocks);
  257. // The current on-the-fly SSA update requires blocks to be processed in
  258. // reverse postorder so that LastValueMap contains the correct value at each
  259. // exit.
  260. LoopBlocksDFS DFS(L);
  261. DFS.perform(LI);
  262. // Stash the DFS iterators before adding blocks to the loop.
  263. LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
  264. LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
  265. if (Header->getParent()->isDebugInfoForProfiling())
  266. for (BasicBlock *BB : L->getBlocks())
  267. for (Instruction &I : *BB)
  268. if (!isa<DbgInfoIntrinsic>(&I))
  269. if (const DILocation *DIL = I.getDebugLoc())
  270. I.setDebugLoc(DIL->cloneWithDuplicationFactor(Count));
  271. // Copy all blocks
  272. for (unsigned It = 1; It != Count; ++It) {
  273. std::vector<BasicBlock *> NewBlocks;
  274. // Maps Blocks[It] -> Blocks[It-1]
  275. DenseMap<Value *, Value *> PrevItValueMap;
  276. for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
  277. ValueToValueMapTy VMap;
  278. BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
  279. Header->getParent()->getBasicBlockList().push_back(New);
  280. if (ForeBlocks.count(*BB)) {
  281. L->addBasicBlockToLoop(New, *LI);
  282. if (*BB == ForeBlocksFirst[0])
  283. ForeBlocksFirst.push_back(New);
  284. if (*BB == ForeBlocksLast[0])
  285. ForeBlocksLast.push_back(New);
  286. } else if (SubLoopBlocks.count(*BB)) {
  287. SubLoop->addBasicBlockToLoop(New, *LI);
  288. if (*BB == SubLoopBlocksFirst[0])
  289. SubLoopBlocksFirst.push_back(New);
  290. if (*BB == SubLoopBlocksLast[0])
  291. SubLoopBlocksLast.push_back(New);
  292. } else if (AftBlocks.count(*BB)) {
  293. L->addBasicBlockToLoop(New, *LI);
  294. if (*BB == AftBlocksFirst[0])
  295. AftBlocksFirst.push_back(New);
  296. if (*BB == AftBlocksLast[0])
  297. AftBlocksLast.push_back(New);
  298. } else {
  299. llvm_unreachable("BB being cloned should be in Fore/Sub/Aft");
  300. }
  301. // Update our running maps of newest clones
  302. PrevItValueMap[New] = (It == 1 ? *BB : LastValueMap[*BB]);
  303. LastValueMap[*BB] = New;
  304. for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
  305. VI != VE; ++VI) {
  306. PrevItValueMap[VI->second] =
  307. const_cast<Value *>(It == 1 ? VI->first : LastValueMap[VI->first]);
  308. LastValueMap[VI->first] = VI->second;
  309. }
  310. NewBlocks.push_back(New);
  311. // Update DomTree:
  312. if (*BB == ForeBlocksFirst[0])
  313. DT->addNewBlock(New, ForeBlocksLast[It - 1]);
  314. else if (*BB == SubLoopBlocksFirst[0])
  315. DT->addNewBlock(New, SubLoopBlocksLast[It - 1]);
  316. else if (*BB == AftBlocksFirst[0])
  317. DT->addNewBlock(New, AftBlocksLast[It - 1]);
  318. else {
  319. // Each set of blocks (Fore/Sub/Aft) will have the same internal domtree
  320. // structure.
  321. auto BBDomNode = DT->getNode(*BB);
  322. auto BBIDom = BBDomNode->getIDom();
  323. BasicBlock *OriginalBBIDom = BBIDom->getBlock();
  324. assert(OriginalBBIDom);
  325. assert(LastValueMap[cast<Value>(OriginalBBIDom)]);
  326. DT->addNewBlock(
  327. New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
  328. }
  329. }
  330. // Remap all instructions in the most recent iteration
  331. for (BasicBlock *NewBlock : NewBlocks) {
  332. for (Instruction &I : *NewBlock) {
  333. ::remapInstruction(&I, LastValueMap);
  334. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  335. if (II->getIntrinsicID() == Intrinsic::assume)
  336. AC->registerAssumption(II);
  337. }
  338. }
  339. // Alter the ForeBlocks phi's, pointing them at the latest version of the
  340. // value from the previous iteration's phis
  341. for (PHINode &Phi : ForeBlocksFirst[It]->phis()) {
  342. Value *OldValue = Phi.getIncomingValueForBlock(AftBlocksLast[It]);
  343. assert(OldValue && "should have incoming edge from Aft[It]");
  344. Value *NewValue = OldValue;
  345. if (Value *PrevValue = PrevItValueMap[OldValue])
  346. NewValue = PrevValue;
  347. assert(Phi.getNumOperands() == 2);
  348. Phi.setIncomingBlock(0, ForeBlocksLast[It - 1]);
  349. Phi.setIncomingValue(0, NewValue);
  350. Phi.removeIncomingValue(1);
  351. }
  352. }
  353. // Now that all the basic blocks for the unrolled iterations are in place,
  354. // finish up connecting the blocks and phi nodes. At this point LastValueMap
  355. // is the last unrolled iterations values.
  356. // Update Phis in BB from OldBB to point to NewBB
  357. auto updatePHIBlocks = [](BasicBlock *BB, BasicBlock *OldBB,
  358. BasicBlock *NewBB) {
  359. for (PHINode &Phi : BB->phis()) {
  360. int I = Phi.getBasicBlockIndex(OldBB);
  361. Phi.setIncomingBlock(I, NewBB);
  362. }
  363. };
  364. // Update Phis in BB from OldBB to point to NewBB and use the latest value
  365. // from LastValueMap
  366. auto updatePHIBlocksAndValues = [](BasicBlock *BB, BasicBlock *OldBB,
  367. BasicBlock *NewBB,
  368. ValueToValueMapTy &LastValueMap) {
  369. for (PHINode &Phi : BB->phis()) {
  370. for (unsigned b = 0; b < Phi.getNumIncomingValues(); ++b) {
  371. if (Phi.getIncomingBlock(b) == OldBB) {
  372. Value *OldValue = Phi.getIncomingValue(b);
  373. if (Value *LastValue = LastValueMap[OldValue])
  374. Phi.setIncomingValue(b, LastValue);
  375. Phi.setIncomingBlock(b, NewBB);
  376. break;
  377. }
  378. }
  379. }
  380. };
  381. // Move all the phis from Src into Dest
  382. auto movePHIs = [](BasicBlock *Src, BasicBlock *Dest) {
  383. Instruction *insertPoint = Dest->getFirstNonPHI();
  384. while (PHINode *Phi = dyn_cast<PHINode>(Src->begin()))
  385. Phi->moveBefore(insertPoint);
  386. };
  387. // Update the PHI values outside the loop to point to the last block
  388. updatePHIBlocksAndValues(LoopExit, AftBlocksLast[0], AftBlocksLast.back(),
  389. LastValueMap);
  390. // Update ForeBlocks successors and phi nodes
  391. BranchInst *ForeTerm =
  392. cast<BranchInst>(ForeBlocksLast.back()->getTerminator());
  393. BasicBlock *Dest = SubLoopBlocksFirst[0];
  394. ForeTerm->setSuccessor(0, Dest);
  395. if (CompletelyUnroll) {
  396. while (PHINode *Phi = dyn_cast<PHINode>(ForeBlocksFirst[0]->begin())) {
  397. Phi->replaceAllUsesWith(Phi->getIncomingValueForBlock(Preheader));
  398. Phi->getParent()->getInstList().erase(Phi);
  399. }
  400. } else {
  401. // Update the PHI values to point to the last aft block
  402. updatePHIBlocksAndValues(ForeBlocksFirst[0], AftBlocksLast[0],
  403. AftBlocksLast.back(), LastValueMap);
  404. }
  405. for (unsigned It = 1; It != Count; It++) {
  406. // Remap ForeBlock successors from previous iteration to this
  407. BranchInst *ForeTerm =
  408. cast<BranchInst>(ForeBlocksLast[It - 1]->getTerminator());
  409. BasicBlock *Dest = ForeBlocksFirst[It];
  410. ForeTerm->setSuccessor(0, Dest);
  411. }
  412. // Subloop successors and phis
  413. BranchInst *SubTerm =
  414. cast<BranchInst>(SubLoopBlocksLast.back()->getTerminator());
  415. SubTerm->setSuccessor(!SubLoopContinueOnTrue, SubLoopBlocksFirst[0]);
  416. SubTerm->setSuccessor(SubLoopContinueOnTrue, AftBlocksFirst[0]);
  417. updatePHIBlocks(SubLoopBlocksFirst[0], ForeBlocksLast[0],
  418. ForeBlocksLast.back());
  419. updatePHIBlocks(SubLoopBlocksFirst[0], SubLoopBlocksLast[0],
  420. SubLoopBlocksLast.back());
  421. for (unsigned It = 1; It != Count; It++) {
  422. // Replace the conditional branch of the previous iteration subloop with an
  423. // unconditional one to this one
  424. BranchInst *SubTerm =
  425. cast<BranchInst>(SubLoopBlocksLast[It - 1]->getTerminator());
  426. BranchInst::Create(SubLoopBlocksFirst[It], SubTerm);
  427. SubTerm->eraseFromParent();
  428. updatePHIBlocks(SubLoopBlocksFirst[It], ForeBlocksLast[It],
  429. ForeBlocksLast.back());
  430. updatePHIBlocks(SubLoopBlocksFirst[It], SubLoopBlocksLast[It],
  431. SubLoopBlocksLast.back());
  432. movePHIs(SubLoopBlocksFirst[It], SubLoopBlocksFirst[0]);
  433. }
  434. // Aft blocks successors and phis
  435. BranchInst *Term = cast<BranchInst>(AftBlocksLast.back()->getTerminator());
  436. if (CompletelyUnroll) {
  437. BranchInst::Create(LoopExit, Term);
  438. Term->eraseFromParent();
  439. } else {
  440. Term->setSuccessor(!ContinueOnTrue, ForeBlocksFirst[0]);
  441. }
  442. updatePHIBlocks(AftBlocksFirst[0], SubLoopBlocksLast[0],
  443. SubLoopBlocksLast.back());
  444. for (unsigned It = 1; It != Count; It++) {
  445. // Replace the conditional branch of the previous iteration subloop with an
  446. // unconditional one to this one
  447. BranchInst *AftTerm =
  448. cast<BranchInst>(AftBlocksLast[It - 1]->getTerminator());
  449. BranchInst::Create(AftBlocksFirst[It], AftTerm);
  450. AftTerm->eraseFromParent();
  451. updatePHIBlocks(AftBlocksFirst[It], SubLoopBlocksLast[It],
  452. SubLoopBlocksLast.back());
  453. movePHIs(AftBlocksFirst[It], AftBlocksFirst[0]);
  454. }
  455. // Dominator Tree. Remove the old links between Fore, Sub and Aft, adding the
  456. // new ones required.
  457. if (Count != 1) {
  458. SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
  459. DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete, ForeBlocksLast[0],
  460. SubLoopBlocksFirst[0]);
  461. DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete,
  462. SubLoopBlocksLast[0], AftBlocksFirst[0]);
  463. DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert,
  464. ForeBlocksLast.back(), SubLoopBlocksFirst[0]);
  465. DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert,
  466. SubLoopBlocksLast.back(), AftBlocksFirst[0]);
  467. DT->applyUpdates(DTUpdates);
  468. }
  469. // Merge adjacent basic blocks, if possible.
  470. SmallPtrSet<BasicBlock *, 16> MergeBlocks;
  471. MergeBlocks.insert(ForeBlocksLast.begin(), ForeBlocksLast.end());
  472. MergeBlocks.insert(SubLoopBlocksLast.begin(), SubLoopBlocksLast.end());
  473. MergeBlocks.insert(AftBlocksLast.begin(), AftBlocksLast.end());
  474. while (!MergeBlocks.empty()) {
  475. BasicBlock *BB = *MergeBlocks.begin();
  476. BranchInst *Term = dyn_cast<BranchInst>(BB->getTerminator());
  477. if (Term && Term->isUnconditional() && L->contains(Term->getSuccessor(0))) {
  478. BasicBlock *Dest = Term->getSuccessor(0);
  479. if (BasicBlock *Fold = foldBlockIntoPredecessor(Dest, LI, SE, DT)) {
  480. // Don't remove BB and add Fold as they are the same BB
  481. assert(Fold == BB);
  482. (void)Fold;
  483. MergeBlocks.erase(Dest);
  484. } else
  485. MergeBlocks.erase(BB);
  486. } else
  487. MergeBlocks.erase(BB);
  488. }
  489. // At this point, the code is well formed. We now do a quick sweep over the
  490. // inserted code, doing constant propagation and dead code elimination as we
  491. // go.
  492. simplifyLoopAfterUnroll(SubLoop, true, LI, SE, DT, AC);
  493. simplifyLoopAfterUnroll(L, !CompletelyUnroll && Count > 1, LI, SE, DT, AC);
  494. NumCompletelyUnrolledAndJammed += CompletelyUnroll;
  495. ++NumUnrolledAndJammed;
  496. #ifndef NDEBUG
  497. // We shouldn't have done anything to break loop simplify form or LCSSA.
  498. Loop *OuterL = L->getParentLoop();
  499. Loop *OutestLoop = OuterL ? OuterL : (!CompletelyUnroll ? L : SubLoop);
  500. assert(OutestLoop->isRecursivelyLCSSAForm(*DT, *LI));
  501. if (!CompletelyUnroll)
  502. assert(L->isLoopSimplifyForm());
  503. assert(SubLoop->isLoopSimplifyForm());
  504. assert(DT->verify());
  505. #endif
  506. // Update LoopInfo if the loop is completely removed.
  507. if (CompletelyUnroll)
  508. LI->erase(L);
  509. return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
  510. : LoopUnrollResult::PartiallyUnrolled;
  511. }
  512. static bool getLoadsAndStores(BasicBlockSet &Blocks,
  513. SmallVector<Value *, 4> &MemInstr) {
  514. // Scan the BBs and collect legal loads and stores.
  515. // Returns false if non-simple loads/stores are found.
  516. for (BasicBlock *BB : Blocks) {
  517. for (Instruction &I : *BB) {
  518. if (auto *Ld = dyn_cast<LoadInst>(&I)) {
  519. if (!Ld->isSimple())
  520. return false;
  521. MemInstr.push_back(&I);
  522. } else if (auto *St = dyn_cast<StoreInst>(&I)) {
  523. if (!St->isSimple())
  524. return false;
  525. MemInstr.push_back(&I);
  526. } else if (I.mayReadOrWriteMemory()) {
  527. return false;
  528. }
  529. }
  530. }
  531. return true;
  532. }
  533. static bool checkDependencies(SmallVector<Value *, 4> &Earlier,
  534. SmallVector<Value *, 4> &Later,
  535. unsigned LoopDepth, bool InnerLoop,
  536. DependenceInfo &DI) {
  537. // Use DA to check for dependencies between loads and stores that make unroll
  538. // and jam invalid
  539. for (Value *I : Earlier) {
  540. for (Value *J : Later) {
  541. Instruction *Src = cast<Instruction>(I);
  542. Instruction *Dst = cast<Instruction>(J);
  543. if (Src == Dst)
  544. continue;
  545. // Ignore Input dependencies.
  546. if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
  547. continue;
  548. // Track dependencies, and if we find them take a conservative approach
  549. // by allowing only = or < (not >), altough some > would be safe
  550. // (depending upon unroll width).
  551. // For the inner loop, we need to disallow any (> <) dependencies
  552. // FIXME: Allow > so long as distance is less than unroll width
  553. if (auto D = DI.depends(Src, Dst, true)) {
  554. assert(D->isOrdered() && "Expected an output, flow or anti dep.");
  555. if (D->isConfused()) {
  556. LLVM_DEBUG(dbgs() << " Confused dependency between:\n"
  557. << " " << *Src << "\n"
  558. << " " << *Dst << "\n");
  559. return false;
  560. }
  561. if (!InnerLoop) {
  562. if (D->getDirection(LoopDepth) & Dependence::DVEntry::GT) {
  563. LLVM_DEBUG(dbgs() << " > dependency between:\n"
  564. << " " << *Src << "\n"
  565. << " " << *Dst << "\n");
  566. return false;
  567. }
  568. } else {
  569. assert(LoopDepth + 1 <= D->getLevels());
  570. if (D->getDirection(LoopDepth) & Dependence::DVEntry::GT &&
  571. D->getDirection(LoopDepth + 1) & Dependence::DVEntry::LT) {
  572. LLVM_DEBUG(dbgs() << " < > dependency between:\n"
  573. << " " << *Src << "\n"
  574. << " " << *Dst << "\n");
  575. return false;
  576. }
  577. }
  578. }
  579. }
  580. }
  581. return true;
  582. }
  583. static bool checkDependencies(Loop *L, BasicBlockSet &ForeBlocks,
  584. BasicBlockSet &SubLoopBlocks,
  585. BasicBlockSet &AftBlocks, DependenceInfo &DI) {
  586. // Get all loads/store pairs for each blocks
  587. SmallVector<Value *, 4> ForeMemInstr;
  588. SmallVector<Value *, 4> SubLoopMemInstr;
  589. SmallVector<Value *, 4> AftMemInstr;
  590. if (!getLoadsAndStores(ForeBlocks, ForeMemInstr) ||
  591. !getLoadsAndStores(SubLoopBlocks, SubLoopMemInstr) ||
  592. !getLoadsAndStores(AftBlocks, AftMemInstr))
  593. return false;
  594. // Check for dependencies between any blocks that may change order
  595. unsigned LoopDepth = L->getLoopDepth();
  596. return checkDependencies(ForeMemInstr, SubLoopMemInstr, LoopDepth, false,
  597. DI) &&
  598. checkDependencies(ForeMemInstr, AftMemInstr, LoopDepth, false, DI) &&
  599. checkDependencies(SubLoopMemInstr, AftMemInstr, LoopDepth, false,
  600. DI) &&
  601. checkDependencies(SubLoopMemInstr, SubLoopMemInstr, LoopDepth, true,
  602. DI);
  603. }
  604. bool llvm::isSafeToUnrollAndJam(Loop *L, ScalarEvolution &SE, DominatorTree &DT,
  605. DependenceInfo &DI) {
  606. /* We currently handle outer loops like this:
  607. |
  608. ForeFirst <----\ }
  609. Blocks | } ForeBlocks
  610. ForeLast | }
  611. | |
  612. SubLoopFirst <\ | }
  613. Blocks | | } SubLoopBlocks
  614. SubLoopLast -/ | }
  615. | |
  616. AftFirst | }
  617. Blocks | } AftBlocks
  618. AftLast ------/ }
  619. |
  620. There are (theoretically) any number of blocks in ForeBlocks, SubLoopBlocks
  621. and AftBlocks, providing that there is one edge from Fores to SubLoops,
  622. one edge from SubLoops to Afts and a single outer loop exit (from Afts).
  623. In practice we currently limit Aft blocks to a single block, and limit
  624. things further in the profitablility checks of the unroll and jam pass.
  625. Because of the way we rearrange basic blocks, we also require that
  626. the Fore blocks on all unrolled iterations are safe to move before the
  627. SubLoop blocks of all iterations. So we require that the phi node looping
  628. operands of ForeHeader can be moved to at least the end of ForeEnd, so that
  629. we can arrange cloned Fore Blocks before the subloop and match up Phi's
  630. correctly.
  631. i.e. The old order of blocks used to be F1 S1_1 S1_2 A1 F2 S2_1 S2_2 A2.
  632. It needs to be safe to tranform this to F1 F2 S1_1 S2_1 S1_2 S2_2 A1 A2.
  633. There are then a number of checks along the lines of no calls, no
  634. exceptions, inner loop IV is consistent, etc. Note that for loops requiring
  635. runtime unrolling, UnrollRuntimeLoopRemainder can also fail in
  636. UnrollAndJamLoop if the trip count cannot be easily calculated.
  637. */
  638. if (!L->isLoopSimplifyForm() || L->getSubLoops().size() != 1)
  639. return false;
  640. Loop *SubLoop = L->getSubLoops()[0];
  641. if (!SubLoop->isLoopSimplifyForm())
  642. return false;
  643. BasicBlock *Header = L->getHeader();
  644. BasicBlock *Latch = L->getLoopLatch();
  645. BasicBlock *Exit = L->getExitingBlock();
  646. BasicBlock *SubLoopHeader = SubLoop->getHeader();
  647. BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
  648. BasicBlock *SubLoopExit = SubLoop->getExitingBlock();
  649. if (Latch != Exit)
  650. return false;
  651. if (SubLoopLatch != SubLoopExit)
  652. return false;
  653. if (Header->hasAddressTaken() || SubLoopHeader->hasAddressTaken()) {
  654. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Address taken\n");
  655. return false;
  656. }
  657. // Split blocks into Fore/SubLoop/Aft based on dominators
  658. BasicBlockSet SubLoopBlocks;
  659. BasicBlockSet ForeBlocks;
  660. BasicBlockSet AftBlocks;
  661. if (!partitionOuterLoopBlocks(L, SubLoop, ForeBlocks, SubLoopBlocks,
  662. AftBlocks, &DT)) {
  663. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Incompatible loop layout\n");
  664. return false;
  665. }
  666. // Aft blocks may need to move instructions to fore blocks, which becomes more
  667. // difficult if there are multiple (potentially conditionally executed)
  668. // blocks. For now we just exclude loops with multiple aft blocks.
  669. if (AftBlocks.size() != 1) {
  670. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Can't currently handle "
  671. "multiple blocks after the loop\n");
  672. return false;
  673. }
  674. // Check inner loop backedge count is consistent on all iterations of the
  675. // outer loop
  676. if (!hasIterationCountInvariantInParent(SubLoop, SE)) {
  677. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Inner loop iteration count is "
  678. "not consistent on each iteration\n");
  679. return false;
  680. }
  681. // Check the loop safety info for exceptions.
  682. SimpleLoopSafetyInfo LSI;
  683. LSI.computeLoopSafetyInfo(L);
  684. if (LSI.anyBlockMayThrow()) {
  685. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Something may throw\n");
  686. return false;
  687. }
  688. // We've ruled out the easy stuff and now need to check that there are no
  689. // interdependencies which may prevent us from moving the:
  690. // ForeBlocks before Subloop and AftBlocks.
  691. // Subloop before AftBlocks.
  692. // ForeBlock phi operands before the subloop
  693. // Make sure we can move all instructions we need to before the subloop
  694. if (!processHeaderPhiOperands(
  695. Header, Latch, AftBlocks, [&AftBlocks, &SubLoop](Instruction *I) {
  696. if (SubLoop->contains(I->getParent()))
  697. return false;
  698. if (AftBlocks.count(I->getParent())) {
  699. // If we hit a phi node in afts we know we are done (probably
  700. // LCSSA)
  701. if (isa<PHINode>(I))
  702. return false;
  703. // Can't move instructions with side effects or memory
  704. // reads/writes
  705. if (I->mayHaveSideEffects() || I->mayReadOrWriteMemory())
  706. return false;
  707. }
  708. // Keep going
  709. return true;
  710. })) {
  711. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; can't move required "
  712. "instructions after subloop to before it\n");
  713. return false;
  714. }
  715. // Check for memory dependencies which prohibit the unrolling we are doing.
  716. // Because of the way we are unrolling Fore/Sub/Aft blocks, we need to check
  717. // there are no dependencies between Fore-Sub, Fore-Aft, Sub-Aft and Sub-Sub.
  718. if (!checkDependencies(L, ForeBlocks, SubLoopBlocks, AftBlocks, DI)) {
  719. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; failed dependency check\n");
  720. return false;
  721. }
  722. return true;
  723. }