LoopUnrollAndJam.cpp 38 KB

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