Do not create new pre-header. Reuse original pre-header.
[oota-llvm.git] / lib / Transforms / Scalar / LoopRotation.cpp
1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Loop Rotation Pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "loop-rotate"
15
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"
26
27 using namespace llvm;
28
29 #define MAX_HEADER_SIZE 16
30
31 STATISTIC(NumRotated, "Number of loops rotated");
32 namespace {
33
34   class VISIBILITY_HIDDEN RenameData {
35   public:
36     RenameData(Instruction *O, Value *P, Instruction *H) 
37       : Original(O), PreHeader(P), Header(H) { }
38   public:
39     Instruction *Original; // Original instruction
40     Value *PreHeader; // Original pre-header replacement
41     Instruction *Header; // New header replacement
42   };
43   
44   class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
45
46   public:
47     
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);
51
52     // LCSSA form makes instruction renaming easier.
53     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54       AU.addRequiredID(LCSSAID);
55       AU.addPreservedID(LCSSAID);
56     }
57
58     // Helper functions
59
60     /// Do actual work
61     bool rotateLoop(Loop *L, LPPassManager &LPM);
62     
63     /// Initialize local data
64     void initialize();
65
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();
70
71     /// Return true if this instruction is used outside original header.
72     bool usedOutsideOriginalHeader(Instruction *In);
73
74     /// Find Replacement information for instruction. Return NULL if it is
75     /// not available.
76     const RenameData *findReplacementData(Instruction *I);
77
78   private:
79
80     Loop *L;
81     BasicBlock *OrigHeader;
82     BasicBlock *OrigPreHeader;
83     BasicBlock *OrigLatch;
84     BasicBlock *NewHeader;
85     BasicBlock *Exit;
86
87     SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
88   };
89   
90   RegisterPass<LoopRotate> X ("loop-rotate", "Rotate Loops");
91 }
92
93 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
94
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) {
98   
99   bool RotatedOneLoop = false;
100   initialize();
101
102   // One loop can be rotated multiple times.
103   while (rotateLoop(Lp,LPM)) {
104     RotatedOneLoop = true;
105     initialize();
106   }
107
108   return RotatedOneLoop;
109 }
110
111 /// Rotate loop LP. Return true if it loop is rotated.
112 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
113
114   L = Lp;
115
116   OrigHeader =  L->getHeader();
117   OrigPreHeader = L->getLoopPreheader();
118   OrigLatch = L->getLoopLatch();
119
120   // If loop has only one block then there is not much to rotate.
121   if (L->getBlocks().size() == 1)
122     return false;
123
124   if (!OrigHeader || !OrigLatch || !OrigPreHeader)
125     return false;
126
127   if (!OrigHeader || !OrigLatch || !OrigPreHeader)
128     return false;
129
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))
134     return false;
135
136   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
137   if (!BI)
138     return false;
139   assert (BI->isConditional() && "Branch Instruction is not condiitional");
140
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
144   // required.
145   std::vector<BasicBlock *> ExitBlocks;
146   L->getExitBlocks(ExitBlocks);
147   if (ExitBlocks.size() > 1)
148     return false;
149
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");
160
161   // Check size of original header and reject
162   // loop if it is very big.
163   if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
164     return false;
165
166   // Now, this loop is suitable for rotation.
167
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. 
171   //
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.
180
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();
185   PHINode *PN = NULL;
186   for (; (PN = dyn_cast<PHINode>(I)); ++I) {
187     Instruction *In = I;
188
189     // PHI nodes are not copied into original pre-header. Instead their values
190     // are directly propagated.
191     Value * NPV = PN->getIncomingValueForBlock(OrigPreHeader);
192
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);
200     
201     // "In" can be replaced by NH at various places.
202     LoopHeaderInfo.push_back(RenameData(In, NPV, NH));
203   }
204
205   // Now, handle non-phi instructions.
206   for (; I != E; ++I) {
207     Instruction *In = I;
208
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);
216
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);
223         }
224       }
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);
229       }
230     }
231
232
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;
242     } 
243     
244     // "In" can be replaced by NPH or NH at various places.
245     LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
246   }
247
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.
251   //
252   // Original header instructions are used in
253   // 1) Original header:
254   //
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.
258   //
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
261   //    or new header.
262   //
263   // 2) Inside loop but not in original header
264   //
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];
268
269     if (!ILoopHeaderInfo.Header)
270       continue;
271
272     Instruction *OldPhi = ILoopHeaderInfo.Original;
273     Instruction *NewPhi = ILoopHeaderInfo.Header;
274
275     // Before replacing uses, collect them first, so that iterator is
276     // not invalidated.
277     SmallVector<Instruction *, 16> AllUses;
278     for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
279          UI != UE; ++UI) {
280       Instruction *U = cast<Instruction>(UI);
281       AllUses.push_back(U);
282     }
283
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();
288
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);
293         if (!PU)
294           continue;
295
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)
300           continue;
301         
302        U->replaceUsesOfWith(OldPhi, NewPhi);
303        continue;
304       }
305
306       // Used inside loop, but not in original header.
307       if (L->contains(U->getParent())) {
308         if (U != NewPhi)
309           U->replaceUsesOfWith(OldPhi, NewPhi);
310         continue;
311       }
312
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");        
317
318       PHINode *UPhi = cast<PHINode>(U);
319
320       // UPhi already has one incoming argument from original header. 
321       // Add second incoming argument from new Pre header.
322       
323       UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
324     }
325   }
326   
327   /// Make sure all Exit block PHINodes have required incoming values.
328   updateExitBlock();
329
330   // Update CFG
331
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();
335        I != E; ++I) {
336     Instruction *In = I;
337     PHINode *PN = dyn_cast<PHINode>(In);
338     if (!PN)
339       break;
340
341     PN->removeIncomingValue(OrigPreHeader);
342   }
343
344   // Make NewHeader as the new header for the loop.
345   L->moveToHeader(NewHeader);
346
347   NumRotated++;
348   return true;
349 }
350
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() {
355
356   for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
357        I != E; ++I) {
358
359     PHINode *PN = dyn_cast<PHINode>(I);
360     if (!PN)
361       break;
362
363     // There is already one incoming value from original pre-header block.
364     if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
365       return;
366
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);
373     } else {
374       PN->addIncoming(V, OrigPreHeader);
375     }
376   }
377 }
378
379 /// Initialize local data
380 void LoopRotate::initialize() {
381   L = NULL;
382   OrigHeader = NULL;
383   OrigPreHeader = NULL;
384   NewHeader = NULL;
385   Exit = NULL;
386
387   LoopHeaderInfo.clear();
388 }
389
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) {
393
394   for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
395        UI != UE; ++UI) {
396     Instruction *U = cast<Instruction>(UI);
397     if (U->getParent() != OrigHeader) {
398       if (L->contains(U->getParent()))
399         return true;
400     }
401   }
402
403   return false;
404 }
405
406 /// Find Replacement information for instruction. Return NULL if it is
407 /// not available.
408 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
409
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;
415   }
416   return NULL;
417 }