1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Rotation Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-rotate"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/SmallVector.h"
32 #define MAX_HEADER_SIZE 16
34 STATISTIC(NumRotated, "Number of loops rotated");
37 class VISIBILITY_HIDDEN RenameData {
39 RenameData(Instruction *O, Value *P, Instruction *H)
40 : Original(O), PreHeader(P), Header(H) { }
42 Instruction *Original; // Original instruction
43 Value *PreHeader; // Original pre-header replacement
44 Instruction *Header; // New header replacement
47 class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
50 static char ID; // Pass ID, replacement for typeid
51 LoopRotate() : LoopPass((intptr_t)&ID) {}
53 // Rotate Loop L as many times as possible. Return true if
54 // loop is rotated at least once.
55 bool runOnLoop(Loop *L, LPPassManager &LPM);
57 // LCSSA form makes instruction renaming easier.
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequiredID(LoopSimplifyID);
60 AU.addPreservedID(LoopSimplifyID);
61 AU.addRequiredID(LCSSAID);
62 AU.addPreservedID(LCSSAID);
63 AU.addPreserved<ScalarEvolution>();
64 AU.addPreserved<LoopInfo>();
65 AU.addPreserved<DominatorTree>();
66 AU.addPreserved<DominanceFrontier>();
72 bool rotateLoop(Loop *L, LPPassManager &LPM);
74 /// Initialize local data
77 /// Make sure all Exit block PHINodes have required incoming values.
78 /// If incoming value is constant or defined outside the loop then
79 /// PHINode may not have an entry for original pre-header.
80 void updateExitBlock();
82 /// Return true if this instruction is used outside original header.
83 bool usedOutsideOriginalHeader(Instruction *In);
85 /// Find Replacement information for instruction. Return NULL if it is
87 const RenameData *findReplacementData(Instruction *I);
89 /// After loop rotation, loop pre-header has multiple sucessors.
90 /// Insert one forwarding basic block to ensure that loop pre-header
91 /// has only one successor.
92 void preserveCanonicalLoopForm(LPPassManager &LPM);
97 BasicBlock *OrigHeader;
98 BasicBlock *OrigPreHeader;
99 BasicBlock *OrigLatch;
100 BasicBlock *NewHeader;
102 LPPassManager *LPM_Ptr;
103 SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
106 char LoopRotate::ID = 0;
107 RegisterPass<LoopRotate> X ("loop-rotate", "Rotate Loops");
110 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
112 /// Rotate Loop L as many times as possible. Return true if
113 /// loop is rotated at least once.
114 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
116 bool RotatedOneLoop = false;
120 // One loop can be rotated multiple times.
121 while (rotateLoop(Lp,LPM)) {
122 RotatedOneLoop = true;
126 return RotatedOneLoop;
129 /// Rotate loop LP. Return true if the loop is rotated.
130 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
134 OrigHeader = L->getHeader();
135 OrigPreHeader = L->getLoopPreheader();
136 OrigLatch = L->getLoopLatch();
138 // If loop has only one block then there is not much to rotate.
139 if (L->getBlocks().size() == 1)
142 assert (OrigHeader && OrigLatch && OrigPreHeader &&
143 "Loop is not in canonical form");
145 // If loop header is not one of the loop exit block then
146 // either this loop is already rotated or it is not
147 // suitable for loop rotation transformations.
148 if (!L->isLoopExit(OrigHeader))
151 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
154 assert (BI->isConditional() && "Branch Instruction is not conditional");
156 // Updating PHInodes in loops with multiple exits adds complexity.
157 // Keep it simple, and restrict loop rotation to loops with one exit only.
158 // In future, lift this restriction and support for multiple exits if
160 SmallVector<BasicBlock*, 8> ExitBlocks;
161 L->getExitBlocks(ExitBlocks);
162 if (ExitBlocks.size() > 1)
165 // Check size of original header and reject
166 // loop if it is very big.
167 if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
170 // Now, this loop is suitable for rotation.
172 // Find new Loop header. NewHeader is a Header's one and only successor
173 // that is inside loop. Header's other successor is out side the
174 // loop. Otherwise loop is not suitable for rotation.
175 Exit = BI->getSuccessor(0);
176 NewHeader = BI->getSuccessor(1);
177 if (L->contains(Exit))
178 std::swap(Exit, NewHeader);
179 assert (NewHeader && "Unable to determine new loop header");
180 assert(L->contains(NewHeader) && !L->contains(Exit) &&
181 "Unable to determine loop header and exit blocks");
183 // Copy PHI nodes and other instructions from original header
184 // into original pre-header. Unlike original header, original pre-header is
185 // not a member of loop.
187 // New loop header is one and only successor of original header that
188 // is inside the loop. All other original header successors are outside
189 // the loop. Copy PHI Nodes from original header into new loop header.
190 // Add second incoming value, from original loop pre-header into these phi
191 // nodes. If a value defined in original header is used outside original
192 // header then new loop header will need new phi nodes with two incoming
193 // values, one definition from original header and second definition is
194 // from original loop pre-header.
196 // Remove terminator from Original pre-header. Original pre-header will
197 // receive a clone of original header terminator as a new terminator.
198 OrigPreHeader->getInstList().pop_back();
199 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
201 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
204 // PHI nodes are not copied into original pre-header. Instead their values
205 // are directly propagated.
206 Value * NPV = PN->getIncomingValueForBlock(OrigPreHeader);
208 // Create new PHI node with two incoming values for NewHeader.
209 // One incoming value is from OrigLatch (through OrigHeader) and
210 // second incoming value is from original pre-header.
211 PHINode *NH = PHINode::Create(In->getType(), In->getName());
212 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
213 NH->addIncoming(NPV, OrigPreHeader);
214 NewHeader->getInstList().push_front(NH);
216 // "In" can be replaced by NH at various places.
217 LoopHeaderInfo.push_back(RenameData(In, NPV, NH));
220 // Now, handle non-phi instructions.
221 for (; I != E; ++I) {
224 assert (!isa<PHINode>(In) && "PHINode is not expected here");
225 // This is not a PHI instruction. Insert its clone into original pre-header.
226 // If this instruction is using a value from same basic block then
227 // update it to use value from cloned instruction.
228 Instruction *C = In->clone();
229 C->setName(In->getName());
230 OrigPreHeader->getInstList().push_back(C);
232 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
233 if (Instruction *OpPhi = dyn_cast<PHINode>(In->getOperand(opi))) {
234 if (const RenameData *D = findReplacementData(OpPhi)) {
235 // This is using values from original header PHI node.
236 // Here, directly used incoming value from original pre-header.
237 C->setOperand(opi, D->PreHeader);
240 else if (Instruction *OpInsn =
241 dyn_cast<Instruction>(In->getOperand(opi))) {
242 if (const RenameData *D = findReplacementData(OpInsn))
243 C->setOperand(opi, D->PreHeader);
248 // If this instruction is used outside this basic block then
249 // create new PHINode for this instruction.
250 Instruction *NewHeaderReplacement = NULL;
251 if (usedOutsideOriginalHeader(In)) {
252 const StructType *STy = dyn_cast<StructType>(In->getType());
254 // Can't create PHI nodes for this type. If there are any getResults
255 // not defined in this block, move them back to this block. PHI
256 // nodes will be created for all getResults later.
257 BasicBlock::iterator InsertPoint;
258 if (InvokeInst *II = dyn_cast<InvokeInst>(In)) {
259 InsertPoint = II->getNormalDest()->begin();
260 while (isa<PHINode>(InsertPoint))
263 InsertPoint = I; // call
266 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
268 GetResultInst *InGR = cast<GetResultInst>(UI);
269 if (InGR->getParent() != OrigHeader) {
270 // move InGR to immediately follow call. It will be picked
271 // up, cloned and PHI'd on the next iteration.
272 InGR->moveBefore(InsertPoint);
276 PHINode *PN = PHINode::Create(In->getType(), In->getName());
277 PN->addIncoming(In, OrigHeader);
278 PN->addIncoming(C, OrigPreHeader);
279 NewHeader->getInstList().push_front(PN);
280 NewHeaderReplacement = PN;
283 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
286 // Rename uses of original header instructions to reflect their new
287 // definitions (either from original pre-header node or from newly created
288 // new header PHINodes.
290 // Original header instructions are used in
291 // 1) Original header:
293 // If instruction is used in non-phi instructions then it is using
294 // defintion from original heder iteself. Do not replace this use
295 // with definition from new header or original pre-header.
297 // If instruction is used in phi node then it is an incoming
298 // value. Rename its use to reflect new definition from new-preheader
301 // 2) Inside loop but not in original header
303 // Replace this use to reflect definition from new header.
304 for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
305 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
307 if (!ILoopHeaderInfo.Header)
310 Instruction *OldPhi = ILoopHeaderInfo.Original;
311 Instruction *NewPhi = ILoopHeaderInfo.Header;
313 // Before replacing uses, collect them first, so that iterator is
315 SmallVector<Instruction *, 16> AllUses;
316 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
318 Instruction *U = cast<Instruction>(UI);
319 AllUses.push_back(U);
322 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
323 UE = AllUses.end(); UI != UE; ++UI) {
324 Instruction *U = *UI;
325 BasicBlock *Parent = U->getParent();
327 // Used inside original header
328 if (Parent == OrigHeader) {
329 // Do not rename uses inside original header non-phi instructions.
330 PHINode *PU = dyn_cast<PHINode>(U);
334 // Do not rename uses inside original header phi nodes, if the
335 // incoming value is for new header.
336 if (PU->getBasicBlockIndex(NewHeader) != -1
337 && PU->getIncomingValueForBlock(NewHeader) == U)
340 U->replaceUsesOfWith(OldPhi, NewPhi);
344 // Used inside loop, but not in original header.
345 if (L->contains(U->getParent())) {
347 U->replaceUsesOfWith(OldPhi, NewPhi);
351 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
352 if (U->getParent() == Exit) {
353 assert (isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
355 PHINode *UPhi = cast<PHINode>(U);
356 // UPhi already has one incoming argument from original header.
357 // Add second incoming argument from new Pre header.
358 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
360 // Used outside Exit block. Create a new PHI node from exit block
361 // to receive value from ne new header ane pre header.
362 PHINode *PN = PHINode::Create(U->getType(), U->getName());
363 PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
364 PN->addIncoming(OldPhi, OrigHeader);
365 Exit->getInstList().push_front(PN);
366 U->replaceUsesOfWith(OldPhi, PN);
371 /// Make sure all Exit block PHINodes have required incoming values.
376 // Removing incoming branch from loop preheader to original header.
377 // Now original header is inside the loop.
378 for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
381 PHINode *PN = dyn_cast<PHINode>(In);
385 PN->removeIncomingValue(OrigPreHeader);
388 // Make NewHeader as the new header for the loop.
389 L->moveToHeader(NewHeader);
391 preserveCanonicalLoopForm(LPM);
397 /// Make sure all Exit block PHINodes have required incoming values.
398 /// If incoming value is constant or defined outside the loop then
399 /// PHINode may not have an entry for original pre-header.
400 void LoopRotate::updateExitBlock() {
402 for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
405 PHINode *PN = dyn_cast<PHINode>(I);
409 // There is already one incoming value from original pre-header block.
410 if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
413 const RenameData *ILoopHeaderInfo;
414 Value *V = PN->getIncomingValueForBlock(OrigHeader);
415 if (isa<Instruction>(V) &&
416 (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
417 assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
418 PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
420 PN->addIncoming(V, OrigPreHeader);
425 /// Initialize local data
426 void LoopRotate::initialize() {
429 OrigPreHeader = NULL;
433 LoopHeaderInfo.clear();
436 /// Return true if this instruction is used by any instructions in the loop that
437 /// aren't in original header.
438 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
440 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
442 Instruction *U = cast<Instruction>(UI);
443 if (U->getParent() != OrigHeader) {
444 if (L->contains(U->getParent()))
452 /// Find Replacement information for instruction. Return NULL if it is
454 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
456 // Since LoopHeaderInfo is small, linear walk is OK.
457 for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
458 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
459 if (ILoopHeaderInfo.Original == In)
460 return &ILoopHeaderInfo;
465 /// After loop rotation, loop pre-header has multiple sucessors.
466 /// Insert one forwarding basic block to ensure that loop pre-header
467 /// has only one successor.
468 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
470 // Right now original pre-header has two successors, new header and
471 // exit block. Insert new block between original pre-header and
472 // new header such that loop's new pre-header has only one successor.
473 BasicBlock *NewPreHeader = BasicBlock::Create("bb.nph", OrigHeader->getParent(),
475 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
476 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
477 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
478 BranchInst::Create(NewHeader, NewPreHeader);
480 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
481 if (OrigPH_BI->getSuccessor(0) == NewHeader)
482 OrigPH_BI->setSuccessor(0, NewPreHeader);
484 assert (OrigPH_BI->getSuccessor(1) == NewHeader &&
485 "Unexpected original pre-header terminator");
486 OrigPH_BI->setSuccessor(1, NewPreHeader);
489 for (BasicBlock::iterator I = NewHeader->begin(), E = NewHeader->end();
492 PHINode *PN = dyn_cast<PHINode>(In);
496 int index = PN->getBasicBlockIndex(OrigPreHeader);
497 assert (index != -1 && "Expected incoming value from Original PreHeader");
498 PN->setIncomingBlock(index, NewPreHeader);
499 assert (PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
500 "Expected only one incoming value from Original PreHeader");
503 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
504 DT->addNewBlock(NewPreHeader, OrigPreHeader);
505 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
506 DT->changeImmediateDominator(Exit, OrigPreHeader);
507 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
510 if (L->getHeader() != B) {
511 DomTreeNode *Node = DT->getNode(B);
512 if (Node && Node->getBlock() == OrigHeader)
513 DT->changeImmediateDominator(*BI, L->getHeader());
516 DT->changeImmediateDominator(OrigHeader, OrigLatch);
519 if(DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
521 // New Preheader's dominance frontier is Exit block.
522 DominanceFrontier::DomSetType NewPHSet;
523 NewPHSet.insert(Exit);
524 DF->addBasicBlock(NewPreHeader, NewPHSet);
526 // New Header's dominance frontier now includes itself and Exit block
527 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
528 if (HeadI != DF->end()) {
529 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
531 HeaderSet.insert(L->getHeader());
532 HeaderSet.insert(Exit);
534 DominanceFrontier::DomSetType HeaderSet;
535 HeaderSet.insert(L->getHeader());
536 HeaderSet.insert(Exit);
537 DF->addBasicBlock(L->getHeader(), HeaderSet);
540 // Original header (new Loop Latch)'s dominance frontier is Exit.
541 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
542 if (LatchI != DF->end()) {
543 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
544 LatchSet = LatchI->second;
546 LatchSet.insert(Exit);
548 DominanceFrontier::DomSetType LatchSet;
549 LatchSet.insert(Exit);
550 DF->addBasicBlock(L->getHeader(), LatchSet);
553 // If a loop block dominates new loop latch then its frontier is
554 // new header and Exit.
555 BasicBlock *NewLatch = L->getLoopLatch();
556 DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
557 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
560 if (DT->dominates(B, NewLatch)) {
561 DominanceFrontier::iterator BDFI = DF->find(B);
562 if (BDFI != DF->end()) {
563 DominanceFrontier::DomSetType &BSet = BDFI->second;
566 BSet.insert(L->getHeader());
569 DominanceFrontier::DomSetType BSet;
570 BSet.insert(L->getHeader());
572 DF->addBasicBlock(B, BSet);
578 // Preserve canonical loop form, which means Exit block should
579 // have only one predecessor.
580 BasicBlock *NExit = SplitEdge(L->getLoopLatch(), Exit, this);
583 BasicBlock::iterator I = Exit->begin(), E = Exit->end();
585 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
586 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName());
587 unsigned N = PN->getNumIncomingValues();
588 for (unsigned index = 0; index < N; ++index)
589 if (PN->getIncomingBlock(index) == NExit) {
590 NewPN->addIncoming(PN->getIncomingValue(index), L->getLoopLatch());
591 PN->setIncomingValue(index, NewPN);
592 PN->setIncomingBlock(index, NExit);
593 NExit->getInstList().push_front(NewPN);
597 assert (NewHeader && L->getHeader() == NewHeader
598 && "Invalid loop header after loop rotation");
599 assert (NewPreHeader && L->getLoopPreheader() == NewPreHeader
600 && "Invalid loop preheader after loop rotation");
601 assert (L->getLoopLatch()
602 && "Invalid loop latch after loop rotation");