1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source 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/Transforms/Utils/Local.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/SmallVector.h"
29 #define MAX_HEADER_SIZE 16
31 STATISTIC(NumRotated, "Number of loops rotated");
34 class VISIBILITY_HIDDEN RenameData {
36 RenameData(Instruction *O, Value *P, Instruction *H)
37 : Original(O), PreHeader(P), Header(H) { }
39 Instruction *Original; // Original instruction
40 Value *PreHeader; // Original pre-header replacement
41 Instruction *Header; // New header replacement
44 class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
48 // Rotate Loop L as many times as possible. Return true if
49 // loop is rotated at least once.
50 bool runOnLoop(Loop *L, LPPassManager &LPM);
52 // LCSSA form makes instruction renaming easier.
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.addRequiredID(LCSSAID);
55 AU.addPreservedID(LCSSAID);
61 bool rotateLoop(Loop *L, LPPassManager &LPM);
63 /// Initialize local data
66 /// Make sure all Exit block PHINodes have required incoming values.
67 /// If incoming value is constant or defined outside the loop then
68 /// PHINode may not have an entry for original pre-header.
69 void updateExitBlock();
71 /// Return true if this instruction is used outside original header.
72 bool usedOutsideOriginalHeader(Instruction *In);
74 /// Find Replacement information for instruction. Return NULL if it is
76 const RenameData *findReplacementData(Instruction *I);
78 /// After loop rotation, loop pre-header has multiple sucessors.
79 /// Insert one forwarding basic block to ensure that loop pre-header
80 /// has only one successor.
81 void preserveCanonicalLoopForm(LPPassManager &LPM);
86 BasicBlock *OrigHeader;
87 BasicBlock *OrigPreHeader;
88 BasicBlock *OrigLatch;
89 BasicBlock *NewHeader;
92 SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
95 RegisterPass<LoopRotate> X ("loop-rotate", "Rotate Loops");
98 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
100 /// Rotate Loop L as many times as possible. Return true if
101 /// loop is rotated at least once.
102 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
104 bool RotatedOneLoop = false;
107 // One loop can be rotated multiple times.
108 while (rotateLoop(Lp,LPM)) {
109 RotatedOneLoop = true;
113 return RotatedOneLoop;
116 /// Rotate loop LP. Return true if it loop is rotated.
117 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
121 OrigHeader = L->getHeader();
122 OrigPreHeader = L->getLoopPreheader();
123 OrigLatch = L->getLoopLatch();
125 // If loop has only one block then there is not much to rotate.
126 if (L->getBlocks().size() == 1)
129 assert (OrigHeader && OrigLatch && OrigPreHeader &&
130 "Loop is not in cannocial form");
132 // If loop header is not one of the loop exit block then
133 // either this loop is already rotated or it is not
134 // suitable for loop rotation transformations.
135 if (!L->isLoopExit(OrigHeader))
138 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
141 assert (BI->isConditional() && "Branch Instruction is not condiitional");
143 // Updating PHInodes in loops with multiple exits adds complexity.
144 // Keep it simple, and restrict loop rotation to loops with one exit only.
145 // In future, lift this restriction and support for multiple exits if
147 std::vector<BasicBlock *> ExitBlocks;
148 L->getExitBlocks(ExitBlocks);
149 if (ExitBlocks.size() > 1)
152 // Find new Loop header. NewHeader is a Header's one and only successor
153 // that is inside loop. Header's other successor is out side the
154 // loop. Otherwise loop is not suitable for rotation.
155 Exit = BI->getSuccessor(0);
156 NewHeader = BI->getSuccessor(1);
157 if (L->contains(Exit))
158 std::swap(Exit, NewHeader);
159 assert (NewHeader && "Unable to determine new loop header");
160 assert(L->contains(NewHeader) && !L->contains(Exit) &&
161 "Unable to determine loop header and exit blocks");
163 // Check size of original header and reject
164 // loop if it is very big.
165 if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
168 // Now, this loop is suitable for rotation.
170 // Copy PHI nodes and other instructions from original header
171 // into original pre-header. Unlike original header, original pre-header is
172 // not a member of loop.
174 // New loop header is one and only successor of original header that
175 // is inside the loop. All other original header successors are outside
176 // the loop. Copy PHI Nodes from original header into new loop header.
177 // Add second incoming value, from original loop pre-header into these phi
178 // nodes. If a value defined in original header is used outside original
179 // header then new loop header will need new phi nodes with two incoming
180 // values, one definition from original header and second definition is
181 // from original loop pre-header.
183 // Remove terminator from Original pre-header. Original pre-header will
184 // receive a clone of original header terminator as a new terminator.
185 OrigPreHeader->getInstList().pop_back();
186 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
188 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
191 // PHI nodes are not copied into original pre-header. Instead their values
192 // are directly propagated.
193 Value * NPV = PN->getIncomingValueForBlock(OrigPreHeader);
195 // Create new PHI node with two incoming values for NewHeader.
196 // One incoming value is from OrigLatch (through OrigHeader) and
197 // second incoming value is from original pre-header.
198 PHINode *NH = new PHINode(In->getType(), In->getName());
199 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
200 NH->addIncoming(NPV, OrigPreHeader);
201 NewHeader->getInstList().push_front(NH);
203 // "In" can be replaced by NH at various places.
204 LoopHeaderInfo.push_back(RenameData(In, NPV, NH));
207 // Now, handle non-phi instructions.
208 for (; I != E; ++I) {
211 assert (!isa<PHINode>(In) && "PHINode is not expected here");
212 // This is not a PHI instruction. Insert its clone into original pre-header.
213 // If this instruction is using a value from same basic block then
214 // update it to use value from cloned instruction.
215 Instruction *C = In->clone();
216 C->setName(In->getName());
217 OrigPreHeader->getInstList().push_back(C);
219 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
220 if (Instruction *OpPhi = dyn_cast<PHINode>(In->getOperand(opi))) {
221 if (const RenameData *D = findReplacementData(OpPhi)) {
222 // This is using values from original header PHI node.
223 // Here, directly used incoming value from original pre-header.
224 C->setOperand(opi, D->PreHeader);
227 else if (Instruction *OpInsn =
228 dyn_cast<Instruction>(In->getOperand(opi))) {
229 if (const RenameData *D = findReplacementData(OpInsn))
230 C->setOperand(opi, D->PreHeader);
235 // If this instruction is used outside this basic block then
236 // create new PHINode for this instruction.
237 Instruction *NewHeaderReplacement = NULL;
238 if (usedOutsideOriginalHeader(In)) {
239 PHINode *PN = new PHINode(In->getType(), In->getName());
240 PN->addIncoming(In, OrigHeader);
241 PN->addIncoming(C, OrigPreHeader);
242 NewHeader->getInstList().push_front(PN);
243 NewHeaderReplacement = PN;
246 // "In" can be replaced by NPH or NH at various places.
247 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
250 // Rename uses of original header instructions to reflect their new
251 // definitions (either from original pre-header node or from newly created
252 // new header PHINodes.
254 // Original header instructions are used in
255 // 1) Original header:
257 // If instruction is used in non-phi instructions then it is using
258 // defintion from original heder iteself. Do not replace this use
259 // with definition from new header or original pre-header.
261 // If instruction is used in phi node then it is an incoming
262 // value. Rename its use to reflect new definition from new-preheader
265 // 2) Inside loop but not in original header
267 // Replace this use to reflect definition from new header.
268 for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
269 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
271 if (!ILoopHeaderInfo.Header)
274 Instruction *OldPhi = ILoopHeaderInfo.Original;
275 Instruction *NewPhi = ILoopHeaderInfo.Header;
277 // Before replacing uses, collect them first, so that iterator is
279 SmallVector<Instruction *, 16> AllUses;
280 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
282 Instruction *U = cast<Instruction>(UI);
283 AllUses.push_back(U);
286 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
287 UE = AllUses.end(); UI != UE; ++UI) {
288 Instruction *U = *UI;
289 BasicBlock *Parent = U->getParent();
291 // Used inside original header
292 if (Parent == OrigHeader) {
293 // Do not rename uses inside original header non-phi instructions.
294 PHINode *PU = dyn_cast<PHINode>(U);
298 // Do not rename uses inside original header phi nodes, if the
299 // incoming value is for new header.
300 if (PU->getBasicBlockIndex(NewHeader) != -1
301 && PU->getIncomingValueForBlock(NewHeader) == U)
304 U->replaceUsesOfWith(OldPhi, NewPhi);
308 // Used inside loop, but not in original header.
309 if (L->contains(U->getParent())) {
311 U->replaceUsesOfWith(OldPhi, NewPhi);
315 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
316 assert (U->getParent() == Exit
317 && "Need to propagate new PHI into Exit blocks");
318 assert (isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
320 PHINode *UPhi = cast<PHINode>(U);
322 // UPhi already has one incoming argument from original header.
323 // Add second incoming argument from new Pre header.
325 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
329 /// Make sure all Exit block PHINodes have required incoming values.
334 // Removing incoming branch from loop preheader to original header.
335 // Now original header is inside the loop.
336 for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
339 PHINode *PN = dyn_cast<PHINode>(In);
343 PN->removeIncomingValue(OrigPreHeader);
346 // Make NewHeader as the new header for the loop.
347 L->moveToHeader(NewHeader);
349 preserveCanonicalLoopForm(LPM);
355 /// Make sure all Exit block PHINodes have required incoming values.
356 /// If incoming value is constant or defined outside the loop then
357 /// PHINode may not have an entry for original pre-header.
358 void LoopRotate::updateExitBlock() {
360 for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
363 PHINode *PN = dyn_cast<PHINode>(I);
367 // There is already one incoming value from original pre-header block.
368 if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
371 const RenameData *ILoopHeaderInfo;
372 Value *V = PN->getIncomingValueForBlock(OrigHeader);
373 if (isa<Instruction>(V) &&
374 (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
375 assert (ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
376 PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
378 PN->addIncoming(V, OrigPreHeader);
383 /// Initialize local data
384 void LoopRotate::initialize() {
387 OrigPreHeader = NULL;
391 LoopHeaderInfo.clear();
394 /// Return true if this instruction is used by any instructions in the loop that
395 /// aren't in original header.
396 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
398 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
400 Instruction *U = cast<Instruction>(UI);
401 if (U->getParent() != OrigHeader) {
402 if (L->contains(U->getParent()))
410 /// Find Replacement information for instruction. Return NULL if it is
412 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
414 // Since LoopHeaderInfo is small, linear walk is OK.
415 for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
416 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
417 if (ILoopHeaderInfo.Original == In)
418 return &ILoopHeaderInfo;
423 /// After loop rotation, loop pre-header has multiple sucessors.
424 /// Insert one forwarding basic block to ensure that loop pre-header
425 /// has only one successor.
426 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
428 // Right now original pre-header has two successors, new header and
429 // exit block. Insert new block between original pre-header and
430 // new header such that loop's new pre-header has only one successor.
431 BasicBlock *NewPreHeader = new BasicBlock("bb.nph", OrigHeader->getParent(),
433 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
434 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
435 PL->addBasicBlockToLoop(NewPreHeader, LI);
436 new BranchInst(NewHeader, NewPreHeader);
438 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
439 if (OrigPH_BI->getSuccessor(0) == NewHeader)
440 OrigPH_BI->setSuccessor(0, NewPreHeader);
442 assert (OrigPH_BI->getSuccessor(1) == NewHeader &&
443 "Unexpected original pre-header terminator");
444 OrigPH_BI->setSuccessor(1, NewPreHeader);
447 for (BasicBlock::iterator I = NewHeader->begin(), E = NewHeader->end();
450 PHINode *PN = dyn_cast<PHINode>(In);
454 int index = PN->getBasicBlockIndex(OrigPreHeader);
455 assert (index != -1 && "Expected incoming value from Original PreHeader");
456 PN->setIncomingBlock(index, NewPreHeader);
457 assert (PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
458 "Expected only one incoming value from Original PreHeader");
461 assert (NewHeader && L->getHeader() == NewHeader
462 && "Invalid loop header after loop rotation");
463 assert (NewPreHeader && L->getLoopPreheader() == NewPreHeader
464 && "Invalid loop preheader after loop rotation");
465 assert (L->getLoopLatch()
466 && "Invalid loop latch after loop rotation");