LoopUnrollAndJam.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. //===-- LoopUnrollAndJam.cpp - Loop unrolling utilities -------------------===//
  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 loop unroll and jam as a routine, much like
  10. // LoopUnroll.cpp implements loop unroll.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/Optional.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/Sequence.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/ADT/iterator_range.h"
  24. #include "llvm/Analysis/AssumptionCache.h"
  25. #include "llvm/Analysis/DependenceAnalysis.h"
  26. #include "llvm/Analysis/DomTreeUpdater.h"
  27. #include "llvm/Analysis/LoopInfo.h"
  28. #include "llvm/Analysis/LoopIterator.h"
  29. #include "llvm/Analysis/MustExecute.h"
  30. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  31. #include "llvm/Analysis/ScalarEvolution.h"
  32. #include "llvm/IR/BasicBlock.h"
  33. #include "llvm/IR/DebugInfoMetadata.h"
  34. #include "llvm/IR/DebugLoc.h"
  35. #include "llvm/IR/DiagnosticInfo.h"
  36. #include "llvm/IR/Dominators.h"
  37. #include "llvm/IR/Function.h"
  38. #include "llvm/IR/Instruction.h"
  39. #include "llvm/IR/Instructions.h"
  40. #include "llvm/IR/IntrinsicInst.h"
  41. #include "llvm/IR/Use.h"
  42. #include "llvm/IR/User.h"
  43. #include "llvm/IR/Value.h"
  44. #include "llvm/IR/ValueHandle.h"
  45. #include "llvm/IR/ValueMap.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/Debug.h"
  48. #include "llvm/Support/ErrorHandling.h"
  49. #include "llvm/Support/GenericDomTree.h"
  50. #include "llvm/Support/raw_ostream.h"
  51. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  52. #include "llvm/Transforms/Utils/Cloning.h"
  53. #include "llvm/Transforms/Utils/LoopUtils.h"
  54. #include "llvm/Transforms/Utils/UnrollLoop.h"
  55. #include "llvm/Transforms/Utils/ValueMapper.h"
  56. #include <assert.h>
  57. #include <memory>
  58. #include <type_traits>
  59. #include <vector>
  60. using namespace llvm;
  61. #define DEBUG_TYPE "loop-unroll-and-jam"
  62. STATISTIC(NumUnrolledAndJammed, "Number of loops unroll and jammed");
  63. STATISTIC(NumCompletelyUnrolledAndJammed, "Number of loops unroll and jammed");
  64. typedef SmallPtrSet<BasicBlock *, 4> BasicBlockSet;
  65. // Partition blocks in an outer/inner loop pair into blocks before and after
  66. // the loop
  67. static bool partitionLoopBlocks(Loop &L, BasicBlockSet &ForeBlocks,
  68. BasicBlockSet &AftBlocks, DominatorTree &DT) {
  69. Loop *SubLoop = L.getSubLoops()[0];
  70. BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
  71. for (BasicBlock *BB : L.blocks()) {
  72. if (!SubLoop->contains(BB)) {
  73. if (DT.dominates(SubLoopLatch, BB))
  74. AftBlocks.insert(BB);
  75. else
  76. ForeBlocks.insert(BB);
  77. }
  78. }
  79. // Check that all blocks in ForeBlocks together dominate the subloop
  80. // TODO: This might ideally be done better with a dominator/postdominators.
  81. BasicBlock *SubLoopPreHeader = SubLoop->getLoopPreheader();
  82. for (BasicBlock *BB : ForeBlocks) {
  83. if (BB == SubLoopPreHeader)
  84. continue;
  85. Instruction *TI = BB->getTerminator();
  86. for (BasicBlock *Succ : successors(TI))
  87. if (!ForeBlocks.count(Succ))
  88. return false;
  89. }
  90. return true;
  91. }
  92. /// Partition blocks in a loop nest into blocks before and after each inner
  93. /// loop.
  94. static bool partitionOuterLoopBlocks(
  95. Loop &Root, Loop &JamLoop, BasicBlockSet &JamLoopBlocks,
  96. DenseMap<Loop *, BasicBlockSet> &ForeBlocksMap,
  97. DenseMap<Loop *, BasicBlockSet> &AftBlocksMap, DominatorTree &DT) {
  98. JamLoopBlocks.insert(JamLoop.block_begin(), JamLoop.block_end());
  99. for (Loop *L : Root.getLoopsInPreorder()) {
  100. if (L == &JamLoop)
  101. break;
  102. if (!partitionLoopBlocks(*L, ForeBlocksMap[L], AftBlocksMap[L], DT))
  103. return false;
  104. }
  105. return true;
  106. }
  107. // TODO Remove when UnrollAndJamLoop changed to support unroll and jamming more
  108. // than 2 levels loop.
  109. static bool partitionOuterLoopBlocks(Loop *L, Loop *SubLoop,
  110. BasicBlockSet &ForeBlocks,
  111. BasicBlockSet &SubLoopBlocks,
  112. BasicBlockSet &AftBlocks,
  113. DominatorTree *DT) {
  114. SubLoopBlocks.insert(SubLoop->block_begin(), SubLoop->block_end());
  115. return partitionLoopBlocks(*L, ForeBlocks, AftBlocks, *DT);
  116. }
  117. // Looks at the phi nodes in Header for values coming from Latch. For these
  118. // instructions and all their operands calls Visit on them, keeping going for
  119. // all the operands in AftBlocks. Returns false if Visit returns false,
  120. // otherwise returns true. This is used to process the instructions in the
  121. // Aft blocks that need to be moved before the subloop. It is used in two
  122. // places. One to check that the required set of instructions can be moved
  123. // before the loop. Then to collect the instructions to actually move in
  124. // moveHeaderPhiOperandsToForeBlocks.
  125. template <typename T>
  126. static bool processHeaderPhiOperands(BasicBlock *Header, BasicBlock *Latch,
  127. BasicBlockSet &AftBlocks, T Visit) {
  128. SmallVector<Instruction *, 8> Worklist;
  129. for (auto &Phi : Header->phis()) {
  130. Value *V = Phi.getIncomingValueForBlock(Latch);
  131. if (Instruction *I = dyn_cast<Instruction>(V))
  132. Worklist.push_back(I);
  133. }
  134. while (!Worklist.empty()) {
  135. Instruction *I = Worklist.pop_back_val();
  136. if (!Visit(I))
  137. return false;
  138. if (AftBlocks.count(I->getParent()))
  139. for (auto &U : I->operands())
  140. if (Instruction *II = dyn_cast<Instruction>(U))
  141. Worklist.push_back(II);
  142. }
  143. return true;
  144. }
  145. // Move the phi operands of Header from Latch out of AftBlocks to InsertLoc.
  146. static void moveHeaderPhiOperandsToForeBlocks(BasicBlock *Header,
  147. BasicBlock *Latch,
  148. Instruction *InsertLoc,
  149. BasicBlockSet &AftBlocks) {
  150. // We need to ensure we move the instructions in the correct order,
  151. // starting with the earliest required instruction and moving forward.
  152. std::vector<Instruction *> Visited;
  153. processHeaderPhiOperands(Header, Latch, AftBlocks,
  154. [&Visited, &AftBlocks](Instruction *I) {
  155. if (AftBlocks.count(I->getParent()))
  156. Visited.push_back(I);
  157. return true;
  158. });
  159. // Move all instructions in program order to before the InsertLoc
  160. BasicBlock *InsertLocBB = InsertLoc->getParent();
  161. for (Instruction *I : reverse(Visited)) {
  162. if (I->getParent() != InsertLocBB)
  163. I->moveBefore(InsertLoc);
  164. }
  165. }
  166. /*
  167. This method performs Unroll and Jam. For a simple loop like:
  168. for (i = ..)
  169. Fore(i)
  170. for (j = ..)
  171. SubLoop(i, j)
  172. Aft(i)
  173. Instead of doing normal inner or outer unrolling, we do:
  174. for (i = .., i+=2)
  175. Fore(i)
  176. Fore(i+1)
  177. for (j = ..)
  178. SubLoop(i, j)
  179. SubLoop(i+1, j)
  180. Aft(i)
  181. Aft(i+1)
  182. So the outer loop is essetially unrolled and then the inner loops are fused
  183. ("jammed") together into a single loop. This can increase speed when there
  184. are loads in SubLoop that are invariant to i, as they become shared between
  185. the now jammed inner loops.
  186. We do this by spliting the blocks in the loop into Fore, Subloop and Aft.
  187. Fore blocks are those before the inner loop, Aft are those after. Normal
  188. Unroll code is used to copy each of these sets of blocks and the results are
  189. combined together into the final form above.
  190. isSafeToUnrollAndJam should be used prior to calling this to make sure the
  191. unrolling will be valid. Checking profitablility is also advisable.
  192. If EpilogueLoop is non-null, it receives the epilogue loop (if it was
  193. necessary to create one and not fully unrolled).
  194. */
  195. LoopUnrollResult
  196. llvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount,
  197. unsigned TripMultiple, bool UnrollRemainder,
  198. LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
  199. AssumptionCache *AC, const TargetTransformInfo *TTI,
  200. OptimizationRemarkEmitter *ORE, Loop **EpilogueLoop) {
  201. // When we enter here we should have already checked that it is safe
  202. BasicBlock *Header = L->getHeader();
  203. assert(Header && "No header.");
  204. assert(L->getSubLoops().size() == 1);
  205. Loop *SubLoop = *L->begin();
  206. // Don't enter the unroll code if there is nothing to do.
  207. if (TripCount == 0 && Count < 2) {
  208. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; almost nothing to do\n");
  209. return LoopUnrollResult::Unmodified;
  210. }
  211. assert(Count > 0);
  212. assert(TripMultiple > 0);
  213. assert(TripCount == 0 || TripCount % TripMultiple == 0);
  214. // Are we eliminating the loop control altogether?
  215. bool CompletelyUnroll = (Count == TripCount);
  216. // We use the runtime remainder in cases where we don't know trip multiple
  217. if (TripMultiple == 1 || TripMultiple % Count != 0) {
  218. if (!UnrollRuntimeLoopRemainder(L, Count, /*AllowExpensiveTripCount*/ false,
  219. /*UseEpilogRemainder*/ true,
  220. UnrollRemainder, /*ForgetAllSCEV*/ false,
  221. LI, SE, DT, AC, TTI, true, EpilogueLoop)) {
  222. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; remainder loop could not be "
  223. "generated when assuming runtime trip count\n");
  224. return LoopUnrollResult::Unmodified;
  225. }
  226. }
  227. // Notify ScalarEvolution that the loop will be substantially changed,
  228. // if not outright eliminated.
  229. if (SE) {
  230. SE->forgetLoop(L);
  231. SE->forgetLoop(SubLoop);
  232. }
  233. using namespace ore;
  234. // Report the unrolling decision.
  235. if (CompletelyUnroll) {
  236. LLVM_DEBUG(dbgs() << "COMPLETELY UNROLL AND JAMMING loop %"
  237. << Header->getName() << " with trip count " << TripCount
  238. << "!\n");
  239. ORE->emit(OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
  240. L->getHeader())
  241. << "completely unroll and jammed loop with "
  242. << NV("UnrollCount", TripCount) << " iterations");
  243. } else {
  244. auto DiagBuilder = [&]() {
  245. OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
  246. L->getHeader());
  247. return Diag << "unroll and jammed loop by a factor of "
  248. << NV("UnrollCount", Count);
  249. };
  250. LLVM_DEBUG(dbgs() << "UNROLL AND JAMMING loop %" << Header->getName()
  251. << " by " << Count);
  252. if (TripMultiple != 1) {
  253. LLVM_DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
  254. ORE->emit([&]() {
  255. return DiagBuilder() << " with " << NV("TripMultiple", TripMultiple)
  256. << " trips per branch";
  257. });
  258. } else {
  259. LLVM_DEBUG(dbgs() << " with run-time trip count");
  260. ORE->emit([&]() { return DiagBuilder() << " with run-time trip count"; });
  261. }
  262. LLVM_DEBUG(dbgs() << "!\n");
  263. }
  264. BasicBlock *Preheader = L->getLoopPreheader();
  265. BasicBlock *LatchBlock = L->getLoopLatch();
  266. assert(Preheader && "No preheader");
  267. assert(LatchBlock && "No latch block");
  268. BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
  269. assert(BI && !BI->isUnconditional());
  270. bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
  271. BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
  272. bool SubLoopContinueOnTrue = SubLoop->contains(
  273. SubLoop->getLoopLatch()->getTerminator()->getSuccessor(0));
  274. // Partition blocks in an outer/inner loop pair into blocks before and after
  275. // the loop
  276. BasicBlockSet SubLoopBlocks;
  277. BasicBlockSet ForeBlocks;
  278. BasicBlockSet AftBlocks;
  279. partitionOuterLoopBlocks(L, SubLoop, ForeBlocks, SubLoopBlocks, AftBlocks,
  280. DT);
  281. // We keep track of the entering/first and exiting/last block of each of
  282. // Fore/SubLoop/Aft in each iteration. This helps make the stapling up of
  283. // blocks easier.
  284. std::vector<BasicBlock *> ForeBlocksFirst;
  285. std::vector<BasicBlock *> ForeBlocksLast;
  286. std::vector<BasicBlock *> SubLoopBlocksFirst;
  287. std::vector<BasicBlock *> SubLoopBlocksLast;
  288. std::vector<BasicBlock *> AftBlocksFirst;
  289. std::vector<BasicBlock *> AftBlocksLast;
  290. ForeBlocksFirst.push_back(Header);
  291. ForeBlocksLast.push_back(SubLoop->getLoopPreheader());
  292. SubLoopBlocksFirst.push_back(SubLoop->getHeader());
  293. SubLoopBlocksLast.push_back(SubLoop->getExitingBlock());
  294. AftBlocksFirst.push_back(SubLoop->getExitBlock());
  295. AftBlocksLast.push_back(L->getExitingBlock());
  296. // Maps Blocks[0] -> Blocks[It]
  297. ValueToValueMapTy LastValueMap;
  298. // Move any instructions from fore phi operands from AftBlocks into Fore.
  299. moveHeaderPhiOperandsToForeBlocks(
  300. Header, LatchBlock, ForeBlocksLast[0]->getTerminator(), AftBlocks);
  301. // The current on-the-fly SSA update requires blocks to be processed in
  302. // reverse postorder so that LastValueMap contains the correct value at each
  303. // exit.
  304. LoopBlocksDFS DFS(L);
  305. DFS.perform(LI);
  306. // Stash the DFS iterators before adding blocks to the loop.
  307. LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
  308. LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
  309. if (Header->getParent()->isDebugInfoForProfiling())
  310. for (BasicBlock *BB : L->getBlocks())
  311. for (Instruction &I : *BB)
  312. if (!isa<DbgInfoIntrinsic>(&I))
  313. if (const DILocation *DIL = I.getDebugLoc()) {
  314. auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(Count);
  315. if (NewDIL)
  316. I.setDebugLoc(NewDIL.getValue());
  317. else
  318. LLVM_DEBUG(dbgs()
  319. << "Failed to create new discriminator: "
  320. << DIL->getFilename() << " Line: " << DIL->getLine());
  321. }
  322. // Copy all blocks
  323. for (unsigned It = 1; It != Count; ++It) {
  324. SmallVector<BasicBlock *, 8> NewBlocks;
  325. // Maps Blocks[It] -> Blocks[It-1]
  326. DenseMap<Value *, Value *> PrevItValueMap;
  327. SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
  328. NewLoops[L] = L;
  329. NewLoops[SubLoop] = SubLoop;
  330. for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
  331. ValueToValueMapTy VMap;
  332. BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
  333. Header->getParent()->getBasicBlockList().push_back(New);
  334. // Tell LI about New.
  335. addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
  336. if (ForeBlocks.count(*BB)) {
  337. if (*BB == ForeBlocksFirst[0])
  338. ForeBlocksFirst.push_back(New);
  339. if (*BB == ForeBlocksLast[0])
  340. ForeBlocksLast.push_back(New);
  341. } else if (SubLoopBlocks.count(*BB)) {
  342. if (*BB == SubLoopBlocksFirst[0])
  343. SubLoopBlocksFirst.push_back(New);
  344. if (*BB == SubLoopBlocksLast[0])
  345. SubLoopBlocksLast.push_back(New);
  346. } else if (AftBlocks.count(*BB)) {
  347. if (*BB == AftBlocksFirst[0])
  348. AftBlocksFirst.push_back(New);
  349. if (*BB == AftBlocksLast[0])
  350. AftBlocksLast.push_back(New);
  351. } else {
  352. llvm_unreachable("BB being cloned should be in Fore/Sub/Aft");
  353. }
  354. // Update our running maps of newest clones
  355. PrevItValueMap[New] = (It == 1 ? *BB : LastValueMap[*BB]);
  356. LastValueMap[*BB] = New;
  357. for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
  358. VI != VE; ++VI) {
  359. PrevItValueMap[VI->second] =
  360. const_cast<Value *>(It == 1 ? VI->first : LastValueMap[VI->first]);
  361. LastValueMap[VI->first] = VI->second;
  362. }
  363. NewBlocks.push_back(New);
  364. // Update DomTree:
  365. if (*BB == ForeBlocksFirst[0])
  366. DT->addNewBlock(New, ForeBlocksLast[It - 1]);
  367. else if (*BB == SubLoopBlocksFirst[0])
  368. DT->addNewBlock(New, SubLoopBlocksLast[It - 1]);
  369. else if (*BB == AftBlocksFirst[0])
  370. DT->addNewBlock(New, AftBlocksLast[It - 1]);
  371. else {
  372. // Each set of blocks (Fore/Sub/Aft) will have the same internal domtree
  373. // structure.
  374. auto BBDomNode = DT->getNode(*BB);
  375. auto BBIDom = BBDomNode->getIDom();
  376. BasicBlock *OriginalBBIDom = BBIDom->getBlock();
  377. assert(OriginalBBIDom);
  378. assert(LastValueMap[cast<Value>(OriginalBBIDom)]);
  379. DT->addNewBlock(
  380. New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
  381. }
  382. }
  383. // Remap all instructions in the most recent iteration
  384. remapInstructionsInBlocks(NewBlocks, LastValueMap);
  385. for (BasicBlock *NewBlock : NewBlocks) {
  386. for (Instruction &I : *NewBlock) {
  387. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  388. if (II->getIntrinsicID() == Intrinsic::assume)
  389. AC->registerAssumption(II);
  390. }
  391. }
  392. // Alter the ForeBlocks phi's, pointing them at the latest version of the
  393. // value from the previous iteration's phis
  394. for (PHINode &Phi : ForeBlocksFirst[It]->phis()) {
  395. Value *OldValue = Phi.getIncomingValueForBlock(AftBlocksLast[It]);
  396. assert(OldValue && "should have incoming edge from Aft[It]");
  397. Value *NewValue = OldValue;
  398. if (Value *PrevValue = PrevItValueMap[OldValue])
  399. NewValue = PrevValue;
  400. assert(Phi.getNumOperands() == 2);
  401. Phi.setIncomingBlock(0, ForeBlocksLast[It - 1]);
  402. Phi.setIncomingValue(0, NewValue);
  403. Phi.removeIncomingValue(1);
  404. }
  405. }
  406. // Now that all the basic blocks for the unrolled iterations are in place,
  407. // finish up connecting the blocks and phi nodes. At this point LastValueMap
  408. // is the last unrolled iterations values.
  409. // Update Phis in BB from OldBB to point to NewBB and use the latest value
  410. // from LastValueMap
  411. auto updatePHIBlocksAndValues = [](BasicBlock *BB, BasicBlock *OldBB,
  412. BasicBlock *NewBB,
  413. ValueToValueMapTy &LastValueMap) {
  414. for (PHINode &Phi : BB->phis()) {
  415. for (unsigned b = 0; b < Phi.getNumIncomingValues(); ++b) {
  416. if (Phi.getIncomingBlock(b) == OldBB) {
  417. Value *OldValue = Phi.getIncomingValue(b);
  418. if (Value *LastValue = LastValueMap[OldValue])
  419. Phi.setIncomingValue(b, LastValue);
  420. Phi.setIncomingBlock(b, NewBB);
  421. break;
  422. }
  423. }
  424. }
  425. };
  426. // Move all the phis from Src into Dest
  427. auto movePHIs = [](BasicBlock *Src, BasicBlock *Dest) {
  428. Instruction *insertPoint = Dest->getFirstNonPHI();
  429. while (PHINode *Phi = dyn_cast<PHINode>(Src->begin()))
  430. Phi->moveBefore(insertPoint);
  431. };
  432. // Update the PHI values outside the loop to point to the last block
  433. updatePHIBlocksAndValues(LoopExit, AftBlocksLast[0], AftBlocksLast.back(),
  434. LastValueMap);
  435. // Update ForeBlocks successors and phi nodes
  436. BranchInst *ForeTerm =
  437. cast<BranchInst>(ForeBlocksLast.back()->getTerminator());
  438. assert(ForeTerm->getNumSuccessors() == 1 && "Expecting one successor");
  439. ForeTerm->setSuccessor(0, SubLoopBlocksFirst[0]);
  440. if (CompletelyUnroll) {
  441. while (PHINode *Phi = dyn_cast<PHINode>(ForeBlocksFirst[0]->begin())) {
  442. Phi->replaceAllUsesWith(Phi->getIncomingValueForBlock(Preheader));
  443. Phi->getParent()->getInstList().erase(Phi);
  444. }
  445. } else {
  446. // Update the PHI values to point to the last aft block
  447. updatePHIBlocksAndValues(ForeBlocksFirst[0], AftBlocksLast[0],
  448. AftBlocksLast.back(), LastValueMap);
  449. }
  450. for (unsigned It = 1; It != Count; It++) {
  451. // Remap ForeBlock successors from previous iteration to this
  452. BranchInst *ForeTerm =
  453. cast<BranchInst>(ForeBlocksLast[It - 1]->getTerminator());
  454. assert(ForeTerm->getNumSuccessors() == 1 && "Expecting one successor");
  455. ForeTerm->setSuccessor(0, ForeBlocksFirst[It]);
  456. }
  457. // Subloop successors and phis
  458. BranchInst *SubTerm =
  459. cast<BranchInst>(SubLoopBlocksLast.back()->getTerminator());
  460. SubTerm->setSuccessor(!SubLoopContinueOnTrue, SubLoopBlocksFirst[0]);
  461. SubTerm->setSuccessor(SubLoopContinueOnTrue, AftBlocksFirst[0]);
  462. SubLoopBlocksFirst[0]->replacePhiUsesWith(ForeBlocksLast[0],
  463. ForeBlocksLast.back());
  464. SubLoopBlocksFirst[0]->replacePhiUsesWith(SubLoopBlocksLast[0],
  465. SubLoopBlocksLast.back());
  466. for (unsigned It = 1; It != Count; It++) {
  467. // Replace the conditional branch of the previous iteration subloop with an
  468. // unconditional one to this one
  469. BranchInst *SubTerm =
  470. cast<BranchInst>(SubLoopBlocksLast[It - 1]->getTerminator());
  471. BranchInst::Create(SubLoopBlocksFirst[It], SubTerm);
  472. SubTerm->eraseFromParent();
  473. SubLoopBlocksFirst[It]->replacePhiUsesWith(ForeBlocksLast[It],
  474. ForeBlocksLast.back());
  475. SubLoopBlocksFirst[It]->replacePhiUsesWith(SubLoopBlocksLast[It],
  476. SubLoopBlocksLast.back());
  477. movePHIs(SubLoopBlocksFirst[It], SubLoopBlocksFirst[0]);
  478. }
  479. // Aft blocks successors and phis
  480. BranchInst *AftTerm = cast<BranchInst>(AftBlocksLast.back()->getTerminator());
  481. if (CompletelyUnroll) {
  482. BranchInst::Create(LoopExit, AftTerm);
  483. AftTerm->eraseFromParent();
  484. } else {
  485. AftTerm->setSuccessor(!ContinueOnTrue, ForeBlocksFirst[0]);
  486. assert(AftTerm->getSuccessor(ContinueOnTrue) == LoopExit &&
  487. "Expecting the ContinueOnTrue successor of AftTerm to be LoopExit");
  488. }
  489. AftBlocksFirst[0]->replacePhiUsesWith(SubLoopBlocksLast[0],
  490. SubLoopBlocksLast.back());
  491. for (unsigned It = 1; It != Count; It++) {
  492. // Replace the conditional branch of the previous iteration subloop with an
  493. // unconditional one to this one
  494. BranchInst *AftTerm =
  495. cast<BranchInst>(AftBlocksLast[It - 1]->getTerminator());
  496. BranchInst::Create(AftBlocksFirst[It], AftTerm);
  497. AftTerm->eraseFromParent();
  498. AftBlocksFirst[It]->replacePhiUsesWith(SubLoopBlocksLast[It],
  499. SubLoopBlocksLast.back());
  500. movePHIs(AftBlocksFirst[It], AftBlocksFirst[0]);
  501. }
  502. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  503. // Dominator Tree. Remove the old links between Fore, Sub and Aft, adding the
  504. // new ones required.
  505. if (Count != 1) {
  506. SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
  507. DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete, ForeBlocksLast[0],
  508. SubLoopBlocksFirst[0]);
  509. DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete,
  510. SubLoopBlocksLast[0], AftBlocksFirst[0]);
  511. DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert,
  512. ForeBlocksLast.back(), SubLoopBlocksFirst[0]);
  513. DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert,
  514. SubLoopBlocksLast.back(), AftBlocksFirst[0]);
  515. DTU.applyUpdatesPermissive(DTUpdates);
  516. }
  517. // Merge adjacent basic blocks, if possible.
  518. SmallPtrSet<BasicBlock *, 16> MergeBlocks;
  519. MergeBlocks.insert(ForeBlocksLast.begin(), ForeBlocksLast.end());
  520. MergeBlocks.insert(SubLoopBlocksLast.begin(), SubLoopBlocksLast.end());
  521. MergeBlocks.insert(AftBlocksLast.begin(), AftBlocksLast.end());
  522. MergeBlockSuccessorsIntoGivenBlocks(MergeBlocks, L, &DTU, LI);
  523. // Apply updates to the DomTree.
  524. DT = &DTU.getDomTree();
  525. // At this point, the code is well formed. We now do a quick sweep over the
  526. // inserted code, doing constant propagation and dead code elimination as we
  527. // go.
  528. simplifyLoopAfterUnroll(SubLoop, true, LI, SE, DT, AC, TTI);
  529. simplifyLoopAfterUnroll(L, !CompletelyUnroll && Count > 1, LI, SE, DT, AC,
  530. TTI);
  531. NumCompletelyUnrolledAndJammed += CompletelyUnroll;
  532. ++NumUnrolledAndJammed;
  533. // Update LoopInfo if the loop is completely removed.
  534. if (CompletelyUnroll)
  535. LI->erase(L);
  536. #ifndef NDEBUG
  537. // We shouldn't have done anything to break loop simplify form or LCSSA.
  538. Loop *OutestLoop = SubLoop->getParentLoop()
  539. ? SubLoop->getParentLoop()->getParentLoop()
  540. ? SubLoop->getParentLoop()->getParentLoop()
  541. : SubLoop->getParentLoop()
  542. : SubLoop;
  543. assert(DT->verify());
  544. LI->verify(*DT);
  545. assert(OutestLoop->isRecursivelyLCSSAForm(*DT, *LI));
  546. if (!CompletelyUnroll)
  547. assert(L->isLoopSimplifyForm());
  548. assert(SubLoop->isLoopSimplifyForm());
  549. SE->verify();
  550. #endif
  551. return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
  552. : LoopUnrollResult::PartiallyUnrolled;
  553. }
  554. static bool getLoadsAndStores(BasicBlockSet &Blocks,
  555. SmallVector<Instruction *, 4> &MemInstr) {
  556. // Scan the BBs and collect legal loads and stores.
  557. // Returns false if non-simple loads/stores are found.
  558. for (BasicBlock *BB : Blocks) {
  559. for (Instruction &I : *BB) {
  560. if (auto *Ld = dyn_cast<LoadInst>(&I)) {
  561. if (!Ld->isSimple())
  562. return false;
  563. MemInstr.push_back(&I);
  564. } else if (auto *St = dyn_cast<StoreInst>(&I)) {
  565. if (!St->isSimple())
  566. return false;
  567. MemInstr.push_back(&I);
  568. } else if (I.mayReadOrWriteMemory()) {
  569. return false;
  570. }
  571. }
  572. }
  573. return true;
  574. }
  575. static bool preservesForwardDependence(Instruction *Src, Instruction *Dst,
  576. unsigned UnrollLevel, unsigned JamLevel,
  577. bool Sequentialized, Dependence *D) {
  578. // UnrollLevel might carry the dependency Src --> Dst
  579. // Does a different loop after unrolling?
  580. for (unsigned CurLoopDepth = UnrollLevel + 1; CurLoopDepth <= JamLevel;
  581. ++CurLoopDepth) {
  582. auto JammedDir = D->getDirection(CurLoopDepth);
  583. if (JammedDir == Dependence::DVEntry::LT)
  584. return true;
  585. if (JammedDir & Dependence::DVEntry::GT)
  586. return false;
  587. }
  588. return true;
  589. }
  590. static bool preservesBackwardDependence(Instruction *Src, Instruction *Dst,
  591. unsigned UnrollLevel, unsigned JamLevel,
  592. bool Sequentialized, Dependence *D) {
  593. // UnrollLevel might carry the dependency Dst --> Src
  594. for (unsigned CurLoopDepth = UnrollLevel + 1; CurLoopDepth <= JamLevel;
  595. ++CurLoopDepth) {
  596. auto JammedDir = D->getDirection(CurLoopDepth);
  597. if (JammedDir == Dependence::DVEntry::GT)
  598. return true;
  599. if (JammedDir & Dependence::DVEntry::LT)
  600. return false;
  601. }
  602. // Backward dependencies are only preserved if not interleaved.
  603. return Sequentialized;
  604. }
  605. // Check whether it is semantically safe Src and Dst considering any potential
  606. // dependency between them.
  607. //
  608. // @param UnrollLevel The level of the loop being unrolled
  609. // @param JamLevel The level of the loop being jammed; if Src and Dst are on
  610. // different levels, the outermost common loop counts as jammed level
  611. //
  612. // @return true if is safe and false if there is a dependency violation.
  613. static bool checkDependency(Instruction *Src, Instruction *Dst,
  614. unsigned UnrollLevel, unsigned JamLevel,
  615. bool Sequentialized, DependenceInfo &DI) {
  616. assert(UnrollLevel <= JamLevel &&
  617. "Expecting JamLevel to be at least UnrollLevel");
  618. if (Src == Dst)
  619. return true;
  620. // Ignore Input dependencies.
  621. if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
  622. return true;
  623. // Check whether unroll-and-jam may violate a dependency.
  624. // By construction, every dependency will be lexicographically non-negative
  625. // (if it was, it would violate the current execution order), such as
  626. // (0,0,>,*,*)
  627. // Unroll-and-jam changes the GT execution of two executions to the same
  628. // iteration of the chosen unroll level. That is, a GT dependence becomes a GE
  629. // dependence (or EQ, if we fully unrolled the loop) at the loop's position:
  630. // (0,0,>=,*,*)
  631. // Now, the dependency is not necessarily non-negative anymore, i.e.
  632. // unroll-and-jam may violate correctness.
  633. std::unique_ptr<Dependence> D = DI.depends(Src, Dst, true);
  634. if (!D)
  635. return true;
  636. assert(D->isOrdered() && "Expected an output, flow or anti dep.");
  637. if (D->isConfused()) {
  638. LLVM_DEBUG(dbgs() << " Confused dependency between:\n"
  639. << " " << *Src << "\n"
  640. << " " << *Dst << "\n");
  641. return false;
  642. }
  643. // If outer levels (levels enclosing the loop being unroll-and-jammed) have a
  644. // non-equal direction, then the locations accessed in the inner levels cannot
  645. // overlap in memory. We assumes the indexes never overlap into neighboring
  646. // dimensions.
  647. for (unsigned CurLoopDepth = 1; CurLoopDepth < UnrollLevel; ++CurLoopDepth)
  648. if (!(D->getDirection(CurLoopDepth) & Dependence::DVEntry::EQ))
  649. return true;
  650. auto UnrollDirection = D->getDirection(UnrollLevel);
  651. // If the distance carried by the unrolled loop is 0, then after unrolling
  652. // that distance will become non-zero resulting in non-overlapping accesses in
  653. // the inner loops.
  654. if (UnrollDirection == Dependence::DVEntry::EQ)
  655. return true;
  656. if (UnrollDirection & Dependence::DVEntry::LT &&
  657. !preservesForwardDependence(Src, Dst, UnrollLevel, JamLevel,
  658. Sequentialized, D.get()))
  659. return false;
  660. if (UnrollDirection & Dependence::DVEntry::GT &&
  661. !preservesBackwardDependence(Src, Dst, UnrollLevel, JamLevel,
  662. Sequentialized, D.get()))
  663. return false;
  664. return true;
  665. }
  666. static bool
  667. checkDependencies(Loop &Root, const BasicBlockSet &SubLoopBlocks,
  668. const DenseMap<Loop *, BasicBlockSet> &ForeBlocksMap,
  669. const DenseMap<Loop *, BasicBlockSet> &AftBlocksMap,
  670. DependenceInfo &DI, LoopInfo &LI) {
  671. SmallVector<BasicBlockSet, 8> AllBlocks;
  672. for (Loop *L : Root.getLoopsInPreorder())
  673. if (ForeBlocksMap.find(L) != ForeBlocksMap.end())
  674. AllBlocks.push_back(ForeBlocksMap.lookup(L));
  675. AllBlocks.push_back(SubLoopBlocks);
  676. for (Loop *L : Root.getLoopsInPreorder())
  677. if (AftBlocksMap.find(L) != AftBlocksMap.end())
  678. AllBlocks.push_back(AftBlocksMap.lookup(L));
  679. unsigned LoopDepth = Root.getLoopDepth();
  680. SmallVector<Instruction *, 4> EarlierLoadsAndStores;
  681. SmallVector<Instruction *, 4> CurrentLoadsAndStores;
  682. for (BasicBlockSet &Blocks : AllBlocks) {
  683. CurrentLoadsAndStores.clear();
  684. if (!getLoadsAndStores(Blocks, CurrentLoadsAndStores))
  685. return false;
  686. Loop *CurLoop = LI.getLoopFor((*Blocks.begin())->front().getParent());
  687. unsigned CurLoopDepth = CurLoop->getLoopDepth();
  688. for (auto *Earlier : EarlierLoadsAndStores) {
  689. Loop *EarlierLoop = LI.getLoopFor(Earlier->getParent());
  690. unsigned EarlierDepth = EarlierLoop->getLoopDepth();
  691. unsigned CommonLoopDepth = std::min(EarlierDepth, CurLoopDepth);
  692. for (auto *Later : CurrentLoadsAndStores) {
  693. if (!checkDependency(Earlier, Later, LoopDepth, CommonLoopDepth, false,
  694. DI))
  695. return false;
  696. }
  697. }
  698. size_t NumInsts = CurrentLoadsAndStores.size();
  699. for (size_t I = 0; I < NumInsts; ++I) {
  700. for (size_t J = I; J < NumInsts; ++J) {
  701. if (!checkDependency(CurrentLoadsAndStores[I], CurrentLoadsAndStores[J],
  702. LoopDepth, CurLoopDepth, true, DI))
  703. return false;
  704. }
  705. }
  706. EarlierLoadsAndStores.append(CurrentLoadsAndStores.begin(),
  707. CurrentLoadsAndStores.end());
  708. }
  709. return true;
  710. }
  711. static bool isEligibleLoopForm(const Loop &Root) {
  712. // Root must have a child.
  713. if (Root.getSubLoops().size() != 1)
  714. return false;
  715. const Loop *L = &Root;
  716. do {
  717. // All loops in Root need to be in simplify and rotated form.
  718. if (!L->isLoopSimplifyForm())
  719. return false;
  720. if (!L->isRotatedForm())
  721. return false;
  722. if (L->getHeader()->hasAddressTaken()) {
  723. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Address taken\n");
  724. return false;
  725. }
  726. unsigned SubLoopsSize = L->getSubLoops().size();
  727. if (SubLoopsSize == 0)
  728. return true;
  729. // Only one child is allowed.
  730. if (SubLoopsSize != 1)
  731. return false;
  732. L = L->getSubLoops()[0];
  733. } while (L);
  734. return true;
  735. }
  736. static Loop *getInnerMostLoop(Loop *L) {
  737. while (!L->getSubLoops().empty())
  738. L = L->getSubLoops()[0];
  739. return L;
  740. }
  741. bool llvm::isSafeToUnrollAndJam(Loop *L, ScalarEvolution &SE, DominatorTree &DT,
  742. DependenceInfo &DI, LoopInfo &LI) {
  743. if (!isEligibleLoopForm(*L)) {
  744. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Ineligible loop form\n");
  745. return false;
  746. }
  747. /* We currently handle outer loops like this:
  748. |
  749. ForeFirst <------\ }
  750. Blocks | } ForeBlocks of L
  751. ForeLast | }
  752. | |
  753. ... |
  754. | |
  755. ForeFirst <----\ | }
  756. Blocks | | } ForeBlocks of a inner loop of L
  757. ForeLast | | }
  758. | | |
  759. JamLoopFirst <\ | | }
  760. Blocks | | | } JamLoopBlocks of the innermost loop
  761. JamLoopLast -/ | | }
  762. | | |
  763. AftFirst | | }
  764. Blocks | | } AftBlocks of a inner loop of L
  765. AftLast ------/ | }
  766. | |
  767. ... |
  768. | |
  769. AftFirst | }
  770. Blocks | } AftBlocks of L
  771. AftLast --------/ }
  772. |
  773. There are (theoretically) any number of blocks in ForeBlocks, SubLoopBlocks
  774. and AftBlocks, providing that there is one edge from Fores to SubLoops,
  775. one edge from SubLoops to Afts and a single outer loop exit (from Afts).
  776. In practice we currently limit Aft blocks to a single block, and limit
  777. things further in the profitablility checks of the unroll and jam pass.
  778. Because of the way we rearrange basic blocks, we also require that
  779. the Fore blocks of L on all unrolled iterations are safe to move before the
  780. blocks of the direct child of L of all iterations. So we require that the
  781. phi node looping operands of ForeHeader can be moved to at least the end of
  782. ForeEnd, so that we can arrange cloned Fore Blocks before the subloop and
  783. match up Phi's correctly.
  784. i.e. The old order of blocks used to be
  785. (F1)1 (F2)1 J1_1 J1_2 (A2)1 (A1)1 (F1)2 (F2)2 J2_1 J2_2 (A2)2 (A1)2.
  786. It needs to be safe to transform this to
  787. (F1)1 (F1)2 (F2)1 (F2)2 J1_1 J1_2 J2_1 J2_2 (A2)1 (A2)2 (A1)1 (A1)2.
  788. There are then a number of checks along the lines of no calls, no
  789. exceptions, inner loop IV is consistent, etc. Note that for loops requiring
  790. runtime unrolling, UnrollRuntimeLoopRemainder can also fail in
  791. UnrollAndJamLoop if the trip count cannot be easily calculated.
  792. */
  793. // Split blocks into Fore/SubLoop/Aft based on dominators
  794. Loop *JamLoop = getInnerMostLoop(L);
  795. BasicBlockSet SubLoopBlocks;
  796. DenseMap<Loop *, BasicBlockSet> ForeBlocksMap;
  797. DenseMap<Loop *, BasicBlockSet> AftBlocksMap;
  798. if (!partitionOuterLoopBlocks(*L, *JamLoop, SubLoopBlocks, ForeBlocksMap,
  799. AftBlocksMap, DT)) {
  800. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Incompatible loop layout\n");
  801. return false;
  802. }
  803. // Aft blocks may need to move instructions to fore blocks, which becomes more
  804. // difficult if there are multiple (potentially conditionally executed)
  805. // blocks. For now we just exclude loops with multiple aft blocks.
  806. if (AftBlocksMap[L].size() != 1) {
  807. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Can't currently handle "
  808. "multiple blocks after the loop\n");
  809. return false;
  810. }
  811. // Check inner loop backedge count is consistent on all iterations of the
  812. // outer loop
  813. if (any_of(L->getLoopsInPreorder(), [&SE](Loop *SubLoop) {
  814. return !hasIterationCountInvariantInParent(SubLoop, SE);
  815. })) {
  816. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Inner loop iteration count is "
  817. "not consistent on each iteration\n");
  818. return false;
  819. }
  820. // Check the loop safety info for exceptions.
  821. SimpleLoopSafetyInfo LSI;
  822. LSI.computeLoopSafetyInfo(L);
  823. if (LSI.anyBlockMayThrow()) {
  824. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Something may throw\n");
  825. return false;
  826. }
  827. // We've ruled out the easy stuff and now need to check that there are no
  828. // interdependencies which may prevent us from moving the:
  829. // ForeBlocks before Subloop and AftBlocks.
  830. // Subloop before AftBlocks.
  831. // ForeBlock phi operands before the subloop
  832. // Make sure we can move all instructions we need to before the subloop
  833. BasicBlock *Header = L->getHeader();
  834. BasicBlock *Latch = L->getLoopLatch();
  835. BasicBlockSet AftBlocks = AftBlocksMap[L];
  836. Loop *SubLoop = L->getSubLoops()[0];
  837. if (!processHeaderPhiOperands(
  838. Header, Latch, AftBlocks, [&AftBlocks, &SubLoop](Instruction *I) {
  839. if (SubLoop->contains(I->getParent()))
  840. return false;
  841. if (AftBlocks.count(I->getParent())) {
  842. // If we hit a phi node in afts we know we are done (probably
  843. // LCSSA)
  844. if (isa<PHINode>(I))
  845. return false;
  846. // Can't move instructions with side effects or memory
  847. // reads/writes
  848. if (I->mayHaveSideEffects() || I->mayReadOrWriteMemory())
  849. return false;
  850. }
  851. // Keep going
  852. return true;
  853. })) {
  854. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; can't move required "
  855. "instructions after subloop to before it\n");
  856. return false;
  857. }
  858. // Check for memory dependencies which prohibit the unrolling we are doing.
  859. // Because of the way we are unrolling Fore/Sub/Aft blocks, we need to check
  860. // there are no dependencies between Fore-Sub, Fore-Aft, Sub-Aft and Sub-Sub.
  861. if (!checkDependencies(*L, SubLoopBlocks, ForeBlocksMap, AftBlocksMap, DI,
  862. LI)) {
  863. LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; failed dependency check\n");
  864. return false;
  865. }
  866. return true;
  867. }