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);
81 BasicBlock *OrigHeader;
82 BasicBlock *OrigPreHeader;
83 BasicBlock *OrigLatch;
84 BasicBlock *NewHeader;
87 SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
90 RegisterPass<LoopRotate> X ("loop-rotate", "Rotate Loops");
93 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
95 /// Rotate Loop L as many times as possible. Return true if
96 /// loop is rotated at least once.
97 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
99 bool RotatedOneLoop = false;
102 // One loop can be rotated multiple times.
103 while (rotateLoop(Lp,LPM)) {
104 RotatedOneLoop = true;
108 return RotatedOneLoop;
111 /// Rotate loop LP. Return true if it loop is rotated.
112 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
116 OrigHeader = L->getHeader();
117 OrigPreHeader = L->getLoopPreheader();
118 OrigLatch = L->getLoopLatch();
120 // If loop has only one block then there is not much to rotate.
121 if (L->getBlocks().size() == 1)
124 if (!OrigHeader || !OrigLatch || !OrigPreHeader)
127 if (!OrigHeader || !OrigLatch || !OrigPreHeader)
130 // If loop header is not one of the loop exit block then
131 // either this loop is already rotated or it is not
132 // suitable for loop rotation transformations.
133 if (!L->isLoopExit(OrigHeader))
136 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
139 assert (BI->isConditional() && "Branch Instruction is not condiitional");
141 // Updating PHInodes in loops with multiple exits adds complexity.
142 // Keep it simple, and restrict loop rotation to loops with one exit only.
143 // In future, lift this restriction and support for multiple exits if
145 std::vector<BasicBlock *> ExitBlocks;
146 L->getExitBlocks(ExitBlocks);
147 if (ExitBlocks.size() > 1)
150 // Find new Loop header. NewHeader is a Header's one and only successor
151 // that is inside loop. Header's other successor is out side the
152 // loop. Otherwise loop is not suitable for rotation.
153 Exit = BI->getSuccessor(0);
154 NewHeader = BI->getSuccessor(1);
155 if (L->contains(Exit))
156 std::swap(Exit, NewHeader);
157 assert (NewHeader && "Unable to determine new loop header");
158 assert(L->contains(NewHeader) && !L->contains(Exit) &&
159 "Unable to determine loop header and exit blocks");
161 // Check size of original header and reject
162 // loop if it is very big.
163 if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
166 // Now, this loop is suitable for rotation.
168 // Copy PHI nodes and other instructions from original header
169 // into original pre-header. Unlike original header, original pre-header is
170 // not a member of loop.
172 // New loop header is one and only successor of original header that
173 // is inside the loop. All other original header successors are outside
174 // the loop. Copy PHI Nodes from original header into new loop header.
175 // Add second incoming value, from original loop pre-header into these phi
176 // nodes. If a value defined in original header is used outside original
177 // header then new loop header will need new phi nodes with two incoming
178 // values, one definition from original header and second definition is
179 // from original loop pre-header.
181 // Remove terminator from Original pre-header. Original pre-header will
182 // receive a clone of original header terminator as a new terminator.
183 OrigPreHeader->getInstList().pop_back();
184 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
186 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
189 // PHI nodes are not copied into original pre-header. Instead their values
190 // are directly propagated.
191 Value * NPV = PN->getIncomingValueForBlock(OrigPreHeader);
193 // Create new PHI node with two incoming values for NewHeader.
194 // One incoming value is from OrigLatch (through OrigHeader) and
195 // second incoming value is from original pre-header.
196 PHINode *NH = new PHINode(In->getType(), In->getName());
197 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
198 NH->addIncoming(NPV, OrigPreHeader);
199 NewHeader->getInstList().push_front(NH);
201 // "In" can be replaced by NH at various places.
202 LoopHeaderInfo.push_back(RenameData(In, NPV, NH));
205 // Now, handle non-phi instructions.
206 for (; I != E; ++I) {
209 assert (!isa<PHINode>(In) && "PHINode is not expected here");
210 // This is not a PHI instruction. Insert its clone into original pre-header.
211 // If this instruction is using a value from same basic block then
212 // update it to use value from cloned instruction.
213 Instruction *C = In->clone();
214 C->setName(In->getName());
215 OrigPreHeader->getInstList().push_back(C);
217 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
218 if (Instruction *OpPhi = dyn_cast<PHINode>(In->getOperand(opi))) {
219 if (const RenameData *D = findReplacementData(OpPhi)) {
220 // This is using values from original header PHI node.
221 // Here, directly used incoming value from original pre-header.
222 C->setOperand(opi, D->PreHeader);
225 else if (Instruction *OpInsn =
226 dyn_cast<Instruction>(In->getOperand(opi))) {
227 if (const RenameData *D = findReplacementData(OpInsn))
228 C->setOperand(opi, D->PreHeader);
233 // If this instruction is used outside this basic block then
234 // create new PHINode for this instruction.
235 Instruction *NewHeaderReplacement = NULL;
236 if (usedOutsideOriginalHeader(In)) {
237 PHINode *PN = new PHINode(In->getType(), In->getName());
238 PN->addIncoming(In, OrigHeader);
239 PN->addIncoming(C, OrigPreHeader);
240 NewHeader->getInstList().push_front(PN);
241 NewHeaderReplacement = PN;
244 // "In" can be replaced by NPH or NH at various places.
245 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
248 // Rename uses of original header instructions to reflect their new
249 // definitions (either from original pre-header node or from newly created
250 // new header PHINodes.
252 // Original header instructions are used in
253 // 1) Original header:
255 // If instruction is used in non-phi instructions then it is using
256 // defintion from original heder iteself. Do not replace this use
257 // with definition from new header or original pre-header.
259 // If instruction is used in phi node then it is an incoming
260 // value. Rename its use to reflect new definition from new-preheader
263 // 2) Inside loop but not in original header
265 // Replace this use to reflect definition from new header.
266 for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
267 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
269 if (!ILoopHeaderInfo.Header)
272 Instruction *OldPhi = ILoopHeaderInfo.Original;
273 Instruction *NewPhi = ILoopHeaderInfo.Header;
275 // Before replacing uses, collect them first, so that iterator is
277 SmallVector<Instruction *, 16> AllUses;
278 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
280 Instruction *U = cast<Instruction>(UI);
281 AllUses.push_back(U);
284 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
285 UE = AllUses.end(); UI != UE; ++UI) {
286 Instruction *U = *UI;
287 BasicBlock *Parent = U->getParent();
289 // Used inside original header
290 if (Parent == OrigHeader) {
291 // Do not rename uses inside original header non-phi instructions.
292 PHINode *PU = dyn_cast<PHINode>(U);
296 // Do not rename uses inside original header phi nodes, if the
297 // incoming value is for new header.
298 if (PU->getBasicBlockIndex(NewHeader) != -1
299 && PU->getIncomingValueForBlock(NewHeader) == U)
302 U->replaceUsesOfWith(OldPhi, NewPhi);
306 // Used inside loop, but not in original header.
307 if (L->contains(U->getParent())) {
309 U->replaceUsesOfWith(OldPhi, NewPhi);
313 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
314 assert (U->getParent() == Exit
315 && "Need to propagate new PHI into Exit blocks");
316 assert (isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
318 PHINode *UPhi = cast<PHINode>(U);
320 // UPhi already has one incoming argument from original header.
321 // Add second incoming argument from new Pre header.
323 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
327 /// Make sure all Exit block PHINodes have required incoming values.
332 // Removing incoming branch from loop preheader to original header.
333 // Now original header is inside the loop.
334 for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
337 PHINode *PN = dyn_cast<PHINode>(In);
341 PN->removeIncomingValue(OrigPreHeader);
344 // Make NewHeader as the new header for the loop.
345 L->moveToHeader(NewHeader);
351 /// Make sure all Exit block PHINodes have required incoming values.
352 /// If incoming value is constant or defined outside the loop then
353 /// PHINode may not have an entry for original pre-header.
354 void LoopRotate::updateExitBlock() {
356 for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
359 PHINode *PN = dyn_cast<PHINode>(I);
363 // There is already one incoming value from original pre-header block.
364 if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
367 const RenameData *ILoopHeaderInfo;
368 Value *V = PN->getIncomingValueForBlock(OrigHeader);
369 if (isa<Instruction>(V) &&
370 (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
371 assert (ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
372 PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
374 PN->addIncoming(V, OrigPreHeader);
379 /// Initialize local data
380 void LoopRotate::initialize() {
383 OrigPreHeader = NULL;
387 LoopHeaderInfo.clear();
390 /// Return true if this instruction is used by any instructions in the loop that
391 /// aren't in original header.
392 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
394 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
396 Instruction *U = cast<Instruction>(UI);
397 if (U->getParent() != OrigHeader) {
398 if (L->contains(U->getParent()))
406 /// Find Replacement information for instruction. Return NULL if it is
408 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
410 // Since LoopHeaderInfo is small, linear walk is OK.
411 for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
412 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
413 if (ILoopHeaderInfo.Original == In)
414 return &ILoopHeaderInfo;