LoopRotation.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
  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 Rotation Pass.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar.h"
  14. #include "llvm/ADT/Statistic.h"
  15. #include "llvm/Analysis/AssumptionCache.h"
  16. #include "llvm/Analysis/CodeMetrics.h"
  17. #include "llvm/Analysis/InstructionSimplify.h"
  18. #include "llvm/Analysis/LoopPass.h"
  19. #include "llvm/Analysis/ScalarEvolution.h"
  20. #include "llvm/Analysis/TargetTransformInfo.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/IR/CFG.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/IntrinsicInst.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  31. #include "llvm/Transforms/Utils/Local.h"
  32. #include "llvm/Transforms/Utils/SSAUpdater.h"
  33. #include "llvm/Transforms/Utils/ValueMapper.h"
  34. using namespace llvm;
  35. #define DEBUG_TYPE "loop-rotate"
  36. static cl::opt<unsigned>
  37. DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
  38. cl::desc("The default maximum header size for automatic loop rotation"));
  39. STATISTIC(NumRotated, "Number of loops rotated");
  40. namespace {
  41. class LoopRotate : public LoopPass {
  42. public:
  43. static char ID; // Pass ID, replacement for typeid
  44. LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
  45. initializeLoopRotatePass(*PassRegistry::getPassRegistry());
  46. if (SpecifiedMaxHeaderSize == -1)
  47. MaxHeaderSize = DefaultRotationThreshold;
  48. else
  49. MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
  50. }
  51. // LCSSA form makes instruction renaming easier.
  52. void getAnalysisUsage(AnalysisUsage &AU) const override {
  53. AU.addRequired<AssumptionCacheTracker>();
  54. AU.addPreserved<DominatorTreeWrapperPass>();
  55. AU.addRequired<LoopInfoWrapperPass>();
  56. AU.addPreserved<LoopInfoWrapperPass>();
  57. AU.addRequiredID(LoopSimplifyID);
  58. AU.addPreservedID(LoopSimplifyID);
  59. AU.addRequiredID(LCSSAID);
  60. AU.addPreservedID(LCSSAID);
  61. AU.addPreserved<ScalarEvolution>();
  62. AU.addRequired<TargetTransformInfoWrapperPass>();
  63. }
  64. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  65. bool simplifyLoopLatch(Loop *L);
  66. bool rotateLoop(Loop *L, bool SimplifiedLatch);
  67. private:
  68. unsigned MaxHeaderSize;
  69. LoopInfo *LI;
  70. const TargetTransformInfo *TTI;
  71. AssumptionCache *AC;
  72. DominatorTree *DT;
  73. };
  74. }
  75. char LoopRotate::ID = 0;
  76. INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
  77. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  78. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  79. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  80. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  81. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  82. INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
  83. Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
  84. return new LoopRotate(MaxHeaderSize);
  85. }
  86. /// Rotate Loop L as many times as possible. Return true if
  87. /// the loop is rotated at least once.
  88. bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
  89. if (skipOptnoneFunction(L))
  90. return false;
  91. // Save the loop metadata.
  92. MDNode *LoopMD = L->getLoopID();
  93. Function &F = *L->getHeader()->getParent();
  94. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  95. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  96. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  97. auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  98. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  99. // Simplify the loop latch before attempting to rotate the header
  100. // upward. Rotation may not be needed if the loop tail can be folded into the
  101. // loop exit.
  102. bool SimplifiedLatch = simplifyLoopLatch(L);
  103. // One loop can be rotated multiple times.
  104. bool MadeChange = false;
  105. while (rotateLoop(L, SimplifiedLatch)) {
  106. MadeChange = true;
  107. SimplifiedLatch = false;
  108. }
  109. // Restore the loop metadata.
  110. // NB! We presume LoopRotation DOESN'T ADD its own metadata.
  111. if ((MadeChange || SimplifiedLatch) && LoopMD)
  112. L->setLoopID(LoopMD);
  113. return MadeChange;
  114. }
  115. /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
  116. /// old header into the preheader. If there were uses of the values produced by
  117. /// these instruction that were outside of the loop, we have to insert PHI nodes
  118. /// to merge the two values. Do this now.
  119. static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
  120. BasicBlock *OrigPreheader,
  121. ValueToValueMapTy &ValueMap) {
  122. // Remove PHI node entries that are no longer live.
  123. BasicBlock::iterator I, E = OrigHeader->end();
  124. for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
  125. PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
  126. // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
  127. // as necessary.
  128. SSAUpdater SSA;
  129. for (I = OrigHeader->begin(); I != E; ++I) {
  130. Value *OrigHeaderVal = I;
  131. // If there are no uses of the value (e.g. because it returns void), there
  132. // is nothing to rewrite.
  133. if (OrigHeaderVal->use_empty())
  134. continue;
  135. Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
  136. // The value now exits in two versions: the initial value in the preheader
  137. // and the loop "next" value in the original header.
  138. SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
  139. SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
  140. SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
  141. // Visit each use of the OrigHeader instruction.
  142. for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
  143. UE = OrigHeaderVal->use_end(); UI != UE; ) {
  144. // Grab the use before incrementing the iterator.
  145. Use &U = *UI;
  146. // Increment the iterator before removing the use from the list.
  147. ++UI;
  148. // SSAUpdater can't handle a non-PHI use in the same block as an
  149. // earlier def. We can easily handle those cases manually.
  150. Instruction *UserInst = cast<Instruction>(U.getUser());
  151. if (!isa<PHINode>(UserInst)) {
  152. BasicBlock *UserBB = UserInst->getParent();
  153. // The original users in the OrigHeader are already using the
  154. // original definitions.
  155. if (UserBB == OrigHeader)
  156. continue;
  157. // Users in the OrigPreHeader need to use the value to which the
  158. // original definitions are mapped.
  159. if (UserBB == OrigPreheader) {
  160. U = OrigPreHeaderVal;
  161. continue;
  162. }
  163. }
  164. // Anything else can be handled by SSAUpdater.
  165. SSA.RewriteUse(U);
  166. }
  167. }
  168. }
  169. /// Determine whether the instructions in this range may be safely and cheaply
  170. /// speculated. This is not an important enough situation to develop complex
  171. /// heuristics. We handle a single arithmetic instruction along with any type
  172. /// conversions.
  173. static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
  174. BasicBlock::iterator End, Loop *L) {
  175. bool seenIncrement = false;
  176. bool MultiExitLoop = false;
  177. if (!L->getExitingBlock())
  178. MultiExitLoop = true;
  179. for (BasicBlock::iterator I = Begin; I != End; ++I) {
  180. if (!isSafeToSpeculativelyExecute(I))
  181. return false;
  182. if (isa<DbgInfoIntrinsic>(I))
  183. continue;
  184. switch (I->getOpcode()) {
  185. default:
  186. return false;
  187. case Instruction::GetElementPtr:
  188. // GEPs are cheap if all indices are constant.
  189. if (!cast<GEPOperator>(I)->hasAllConstantIndices())
  190. return false;
  191. // fall-thru to increment case
  192. case Instruction::Add:
  193. case Instruction::Sub:
  194. case Instruction::And:
  195. case Instruction::Or:
  196. case Instruction::Xor:
  197. case Instruction::Shl:
  198. case Instruction::LShr:
  199. case Instruction::AShr: {
  200. Value *IVOpnd = !isa<Constant>(I->getOperand(0))
  201. ? I->getOperand(0)
  202. : !isa<Constant>(I->getOperand(1))
  203. ? I->getOperand(1)
  204. : nullptr;
  205. if (!IVOpnd)
  206. return false;
  207. // If increment operand is used outside of the loop, this speculation
  208. // could cause extra live range interference.
  209. if (MultiExitLoop) {
  210. for (User *UseI : IVOpnd->users()) {
  211. auto *UserInst = cast<Instruction>(UseI);
  212. if (!L->contains(UserInst))
  213. return false;
  214. }
  215. }
  216. if (seenIncrement)
  217. return false;
  218. seenIncrement = true;
  219. break;
  220. }
  221. case Instruction::Trunc:
  222. case Instruction::ZExt:
  223. case Instruction::SExt:
  224. // ignore type conversions
  225. break;
  226. }
  227. }
  228. return true;
  229. }
  230. /// Fold the loop tail into the loop exit by speculating the loop tail
  231. /// instructions. Typically, this is a single post-increment. In the case of a
  232. /// simple 2-block loop, hoisting the increment can be much better than
  233. /// duplicating the entire loop header. In the case of loops with early exits,
  234. /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
  235. /// canonical form so downstream passes can handle it.
  236. ///
  237. /// I don't believe this invalidates SCEV.
  238. bool LoopRotate::simplifyLoopLatch(Loop *L) {
  239. BasicBlock *Latch = L->getLoopLatch();
  240. if (!Latch || Latch->hasAddressTaken())
  241. return false;
  242. BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
  243. if (!Jmp || !Jmp->isUnconditional())
  244. return false;
  245. BasicBlock *LastExit = Latch->getSinglePredecessor();
  246. if (!LastExit || !L->isLoopExiting(LastExit))
  247. return false;
  248. BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
  249. if (!BI)
  250. return false;
  251. if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
  252. return false;
  253. DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
  254. << LastExit->getName() << "\n");
  255. // Hoist the instructions from Latch into LastExit.
  256. LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
  257. unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
  258. BasicBlock *Header = Jmp->getSuccessor(0);
  259. assert(Header == L->getHeader() && "expected a backward branch");
  260. // Remove Latch from the CFG so that LastExit becomes the new Latch.
  261. BI->setSuccessor(FallThruPath, Header);
  262. Latch->replaceSuccessorsPhiUsesWith(LastExit);
  263. Jmp->eraseFromParent();
  264. // Nuke the Latch block.
  265. assert(Latch->empty() && "unable to evacuate Latch");
  266. LI->removeBlock(Latch);
  267. if (DT)
  268. DT->eraseNode(Latch);
  269. Latch->eraseFromParent();
  270. return true;
  271. }
  272. /// Rotate loop LP. Return true if the loop is rotated.
  273. ///
  274. /// \param SimplifiedLatch is true if the latch was just folded into the final
  275. /// loop exit. In this case we may want to rotate even though the new latch is
  276. /// now an exiting branch. This rotation would have happened had the latch not
  277. /// been simplified. However, if SimplifiedLatch is false, then we avoid
  278. /// rotating loops in which the latch exits to avoid excessive or endless
  279. /// rotation. LoopRotate should be repeatable and converge to a canonical
  280. /// form. This property is satisfied because simplifying the loop latch can only
  281. /// happen once across multiple invocations of the LoopRotate pass.
  282. bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
  283. // If the loop has only one block then there is not much to rotate.
  284. if (L->getBlocks().size() == 1)
  285. return false;
  286. BasicBlock *OrigHeader = L->getHeader();
  287. BasicBlock *OrigLatch = L->getLoopLatch();
  288. BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
  289. if (!BI || BI->isUnconditional())
  290. return false;
  291. // If the loop header is not one of the loop exiting blocks then
  292. // either this loop is already rotated or it is not
  293. // suitable for loop rotation transformations.
  294. if (!L->isLoopExiting(OrigHeader))
  295. return false;
  296. // If the loop latch already contains a branch that leaves the loop then the
  297. // loop is already rotated.
  298. if (!OrigLatch)
  299. return false;
  300. // Rotate if either the loop latch does *not* exit the loop, or if the loop
  301. // latch was just simplified.
  302. if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
  303. return false;
  304. // Check size of original header and reject loop if it is very big or we can't
  305. // duplicate blocks inside it.
  306. {
  307. SmallPtrSet<const Value *, 32> EphValues;
  308. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  309. CodeMetrics Metrics;
  310. Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
  311. if (Metrics.notDuplicatable) {
  312. DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
  313. << " instructions: "; L->dump());
  314. return false;
  315. }
  316. if (Metrics.NumInsts > MaxHeaderSize)
  317. return false;
  318. }
  319. // Now, this loop is suitable for rotation.
  320. BasicBlock *OrigPreheader = L->getLoopPreheader();
  321. // If the loop could not be converted to canonical form, it must have an
  322. // indirectbr in it, just give up.
  323. if (!OrigPreheader)
  324. return false;
  325. // Anything ScalarEvolution may know about this loop or the PHI nodes
  326. // in its header will soon be invalidated.
  327. if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
  328. SE->forgetLoop(L);
  329. DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
  330. // Find new Loop header. NewHeader is a Header's one and only successor
  331. // that is inside loop. Header's other successor is outside the
  332. // loop. Otherwise loop is not suitable for rotation.
  333. BasicBlock *Exit = BI->getSuccessor(0);
  334. BasicBlock *NewHeader = BI->getSuccessor(1);
  335. if (L->contains(Exit))
  336. std::swap(Exit, NewHeader);
  337. assert(NewHeader && "Unable to determine new loop header");
  338. assert(L->contains(NewHeader) && !L->contains(Exit) &&
  339. "Unable to determine loop header and exit blocks");
  340. // This code assumes that the new header has exactly one predecessor.
  341. // Remove any single-entry PHI nodes in it.
  342. assert(NewHeader->getSinglePredecessor() &&
  343. "New header doesn't have one pred!");
  344. FoldSingleEntryPHINodes(NewHeader);
  345. // Begin by walking OrigHeader and populating ValueMap with an entry for
  346. // each Instruction.
  347. BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
  348. ValueToValueMapTy ValueMap;
  349. // For PHI nodes, the value available in OldPreHeader is just the
  350. // incoming value from OldPreHeader.
  351. for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
  352. ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
  353. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  354. // For the rest of the instructions, either hoist to the OrigPreheader if
  355. // possible or create a clone in the OldPreHeader if not.
  356. TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
  357. while (I != E) {
  358. Instruction *Inst = I++;
  359. // If the instruction's operands are invariant and it doesn't read or write
  360. // memory, then it is safe to hoist. Doing this doesn't change the order of
  361. // execution in the preheader, but does prevent the instruction from
  362. // executing in each iteration of the loop. This means it is safe to hoist
  363. // something that might trap, but isn't safe to hoist something that reads
  364. // memory (without proving that the loop doesn't write).
  365. if (L->hasLoopInvariantOperands(Inst) &&
  366. !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
  367. !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
  368. !isa<AllocaInst>(Inst)) {
  369. Inst->moveBefore(LoopEntryBranch);
  370. continue;
  371. }
  372. // Otherwise, create a duplicate of the instruction.
  373. Instruction *C = Inst->clone();
  374. // Eagerly remap the operands of the instruction.
  375. RemapInstruction(C, ValueMap,
  376. RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
  377. // With the operands remapped, see if the instruction constant folds or is
  378. // otherwise simplifyable. This commonly occurs because the entry from PHI
  379. // nodes allows icmps and other instructions to fold.
  380. // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
  381. Value *V = SimplifyInstruction(C, DL);
  382. if (V && LI->replacementPreservesLCSSAForm(C, V)) {
  383. // If so, then delete the temporary instruction and stick the folded value
  384. // in the map.
  385. delete C;
  386. ValueMap[Inst] = V;
  387. } else {
  388. // Otherwise, stick the new instruction into the new block!
  389. C->setName(Inst->getName());
  390. C->insertBefore(LoopEntryBranch);
  391. ValueMap[Inst] = C;
  392. }
  393. }
  394. // Along with all the other instructions, we just cloned OrigHeader's
  395. // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
  396. // successors by duplicating their incoming values for OrigHeader.
  397. TerminatorInst *TI = OrigHeader->getTerminator();
  398. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  399. for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
  400. PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  401. PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
  402. // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
  403. // OrigPreHeader's old terminator (the original branch into the loop), and
  404. // remove the corresponding incoming values from the PHI nodes in OrigHeader.
  405. LoopEntryBranch->eraseFromParent();
  406. // If there were any uses of instructions in the duplicated block outside the
  407. // loop, update them, inserting PHI nodes as required
  408. RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
  409. // NewHeader is now the header of the loop.
  410. L->moveToHeader(NewHeader);
  411. assert(L->getHeader() == NewHeader && "Latch block is our new header");
  412. // At this point, we've finished our major CFG changes. As part of cloning
  413. // the loop into the preheader we've simplified instructions and the
  414. // duplicated conditional branch may now be branching on a constant. If it is
  415. // branching on a constant and if that constant means that we enter the loop,
  416. // then we fold away the cond branch to an uncond branch. This simplifies the
  417. // loop in cases important for nested loops, and it also means we don't have
  418. // to split as many edges.
  419. BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
  420. assert(PHBI->isConditional() && "Should be clone of BI condbr!");
  421. if (!isa<ConstantInt>(PHBI->getCondition()) ||
  422. PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
  423. != NewHeader) {
  424. // The conditional branch can't be folded, handle the general case.
  425. // Update DominatorTree to reflect the CFG change we just made. Then split
  426. // edges as necessary to preserve LoopSimplify form.
  427. if (DT) {
  428. // Everything that was dominated by the old loop header is now dominated
  429. // by the original loop preheader. Conceptually the header was merged
  430. // into the preheader, even though we reuse the actual block as a new
  431. // loop latch.
  432. DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
  433. SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
  434. OrigHeaderNode->end());
  435. DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
  436. for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
  437. DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
  438. assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
  439. assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
  440. // Update OrigHeader to be dominated by the new header block.
  441. DT->changeImmediateDominator(OrigHeader, OrigLatch);
  442. }
  443. // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
  444. // thus is not a preheader anymore.
  445. // Split the edge to form a real preheader.
  446. BasicBlock *NewPH = SplitCriticalEdge(
  447. OrigPreheader, NewHeader,
  448. CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
  449. NewPH->setName(NewHeader->getName() + ".lr.ph");
  450. // Preserve canonical loop form, which means that 'Exit' should have only
  451. // one predecessor. Note that Exit could be an exit block for multiple
  452. // nested loops, causing both of the edges to now be critical and need to
  453. // be split.
  454. SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
  455. bool SplitLatchEdge = false;
  456. for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
  457. PE = ExitPreds.end();
  458. PI != PE; ++PI) {
  459. // We only need to split loop exit edges.
  460. Loop *PredLoop = LI->getLoopFor(*PI);
  461. if (!PredLoop || PredLoop->contains(Exit))
  462. continue;
  463. if (isa<IndirectBrInst>((*PI)->getTerminator()))
  464. continue;
  465. SplitLatchEdge |= L->getLoopLatch() == *PI;
  466. BasicBlock *ExitSplit = SplitCriticalEdge(
  467. *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
  468. ExitSplit->moveBefore(Exit);
  469. }
  470. assert(SplitLatchEdge &&
  471. "Despite splitting all preds, failed to split latch exit?");
  472. } else {
  473. // We can fold the conditional branch in the preheader, this makes things
  474. // simpler. The first step is to remove the extra edge to the Exit block.
  475. Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
  476. BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
  477. NewBI->setDebugLoc(PHBI->getDebugLoc());
  478. PHBI->eraseFromParent();
  479. // With our CFG finalized, update DomTree if it is available.
  480. if (DT) {
  481. // Update OrigHeader to be dominated by the new header block.
  482. DT->changeImmediateDominator(NewHeader, OrigPreheader);
  483. DT->changeImmediateDominator(OrigHeader, OrigLatch);
  484. // Brute force incremental dominator tree update. Call
  485. // findNearestCommonDominator on all CFG predecessors of each child of the
  486. // original header.
  487. DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
  488. SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
  489. OrigHeaderNode->end());
  490. bool Changed;
  491. do {
  492. Changed = false;
  493. for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
  494. DomTreeNode *Node = HeaderChildren[I];
  495. BasicBlock *BB = Node->getBlock();
  496. pred_iterator PI = pred_begin(BB);
  497. BasicBlock *NearestDom = *PI;
  498. for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
  499. NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
  500. // Remember if this changes the DomTree.
  501. if (Node->getIDom()->getBlock() != NearestDom) {
  502. DT->changeImmediateDominator(BB, NearestDom);
  503. Changed = true;
  504. }
  505. }
  506. // If the dominator changed, this may have an effect on other
  507. // predecessors, continue until we reach a fixpoint.
  508. } while (Changed);
  509. }
  510. }
  511. assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
  512. assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
  513. // Now that the CFG and DomTree are in a consistent state again, try to merge
  514. // the OrigHeader block into OrigLatch. This will succeed if they are
  515. // connected by an unconditional branch. This is just a cleanup so the
  516. // emitted code isn't too gross in this common case.
  517. MergeBlockIntoPredecessor(OrigHeader, DT, LI);
  518. DEBUG(dbgs() << "LoopRotation: into "; L->dump());
  519. ++NumRotated;
  520. return true;
  521. }