Simpler for() loops.
[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, Instruction *P, Instruction *H) 
37       : Original(O), PreHeader(P), Header(H) { }
38   public:
39     Instruction *Original; // Original instruction
40     Instruction *PreHeader; // New 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 new 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 *NewPreHeader;
86     BasicBlock *Exit;
87
88     SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
89   };
90   
91   RegisterPass<LoopRotate> X ("loop-rotate", "Rotate Loops");
92 }
93
94 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
95
96 /// Rotate Loop L as many times as possible. Return true if
97 /// loop is rotated at least once.
98 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
99   
100   bool RotatedOneLoop = false;
101   initialize();
102
103   // One loop can be rotated multiple times.
104   while (rotateLoop(Lp,LPM)) {
105     RotatedOneLoop = true;
106     initialize();
107   }
108
109   return RotatedOneLoop;
110 }
111
112 /// Rotate loop LP. Return true if it loop is rotated.
113 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
114
115   L = Lp;
116
117   OrigHeader =  L->getHeader();
118   OrigPreHeader = L->getLoopPreheader();
119   OrigLatch = L->getLoopLatch();
120
121   // If loop has only one block then there is not much to rotate.
122   if (L->getBlocks().size() == 1)
123     return false;
124
125   if (!OrigHeader || !OrigLatch || !OrigPreHeader)
126     return false;
127
128   // If loop header is not one of the loop exit block then
129   // either this loop is already rotated or it is not 
130   // suitable for loop rotation transformations.
131   if (!L->isLoopExit(OrigHeader))
132     return false;
133
134   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
135   if (!BI)
136     return false;
137   assert (BI->isConditional() && "Branch Instruction is not condiitional");
138
139   // Updating PHInodes in loops with multiple exits adds complexity. 
140   // Keep it simple, and restrict loop rotation to loops with one exit only.
141   // In future, lift this restriction and support for multiple exits if
142   // required.
143   std::vector<BasicBlock *> ExitBlocks;
144   L->getExitBlocks(ExitBlocks);
145   if (ExitBlocks.size() > 1)
146     return false;
147
148   // Find new Loop header. NewHeader is a Header's one and only successor
149   // that is inside loop.  Header's other successor is out side the
150   // loop. Otherwise loop is not suitable for rotation.
151   Exit = BI->getSuccessor(0);
152   NewHeader = BI->getSuccessor(1);
153   if (L->contains(Exit))
154     std::swap(Exit, NewHeader);
155   assert (NewHeader && "Unable to determine new loop header");
156   assert(L->contains(NewHeader) && !L->contains(Exit) && 
157          "Unable to determine loop header and exit blocks");
158
159   // Check size of original header and reject
160   // loop if it is very big.
161   if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
162     return false;
163
164   // Now, this loop is suitable for rotation.
165
166   // Copy PHI nodes and other instructions from original header
167   // into new pre-header. Unlike original header, new pre-header is
168   // not a member of loop. New pre-header has only one predecessor,
169   // that is original loop pre-header.
170   //
171   // New loop header is one and only successor of original header that 
172   // is inside the loop. All other original header successors are outside 
173   // the loop. Copy PHI Nodes from original header into new loop header. 
174   // Add second incoming value, from new loop pre-header into these phi 
175   // nodes. If a value defined in original header is used outside original 
176   // header then new loop header will need new phi nodes with two incoming 
177   // values, one definition from original header and second definition is 
178   // from new loop pre-header (which is a clone of original header definition).
179
180   NewPreHeader = new BasicBlock("bb.nph", OrigHeader->getParent(), OrigHeader);
181   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
182   PHINode *PN = NULL;
183   for (; (PN = dyn_cast<PHINode>(I)); ++I) {
184     Instruction *In = I;
185
186     // Create new PHI node with one value incoming from OrigPreHeader.
187     // NewPreHeader has only one predecessor, OrigPreHeader.
188     PHINode *NPH = new PHINode(In->getType(), In->getName());
189     NPH->addIncoming(PN->getIncomingValueForBlock(OrigPreHeader), 
190                      OrigPreHeader);
191     NewPreHeader->getInstList().push_back(NPH);
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 NewPreHeader.
196     PHINode *NH = new PHINode(In->getType(), In->getName());
197     NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
198     NH->addIncoming(NPH, NewPreHeader);
199     NewHeader->getInstList().push_front(NH);
200     
201     // "In" can be replaced by NPH or NH at various places.
202     LoopHeaderInfo.push_back(RenameData(In, NPH, 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 NewPreHeader.
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     NewPreHeader->getInstList().push_back(C);
216     
217     // If this instruction is used outside this basic block then
218     // create new PHINode for this instruction.
219     Instruction *NewHeaderReplacement = NULL;
220     if (usedOutsideOriginalHeader(In)) {
221       PHINode *PN = new PHINode(In->getType(), In->getName());
222       PN->addIncoming(In, OrigHeader);
223       PN->addIncoming(C, NewPreHeader);
224       NewHeader->getInstList().push_front(PN);
225       NewHeaderReplacement = PN;
226     } 
227     
228     // "In" can be replaced by NPH or NH at various places.
229     LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
230   }
231
232   // Update new pre-header.
233   // Rename values that are defined in original header to reflects values
234   // defined in new pre-header.
235   for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
236     const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
237     Instruction *In = ILoopHeaderInfo.Original;
238     Instruction *C = ILoopHeaderInfo.PreHeader;
239
240     // If this instruction is not from new pre-header then is not new 
241     // pre-header then this instruction is not handled here.
242     if (C->getParent() != NewPreHeader)
243       continue;
244
245     // PHINodes uses value from pre-header predecessors.
246     if (isa<PHINode>(In))
247       continue;
248
249     for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
250       if (Instruction *OpPhi = dyn_cast<PHINode>(In->getOperand(opi))) {
251         if (const RenameData *D = findReplacementData(OpPhi))
252           C->setOperand(opi, D->PreHeader);
253       }
254       else if (Instruction *OpInsn = 
255                dyn_cast<Instruction>(In->getOperand(opi))) {
256         if (const RenameData *D = findReplacementData(OpInsn))
257           C->setOperand(opi, D->PreHeader);
258       }
259     }
260   }
261
262   // Rename uses of original header instructions to reflect their new
263   // definitions (either from new pre-header node or from newly created
264   // new header PHINodes.
265   //
266   // Original header instructions are used in
267   // 1) Original header:
268   //
269   //    If instruction is used in non-phi instructions then it is using
270   //    defintion from original heder iteself. Do not replace this use
271   //    with definition from new header or new pre-header.
272   //
273   //    If instruction is used in phi node then it is an incoming 
274   //    value. Rename its use to reflect new definition from new-preheader
275   //    or new header.
276   //
277   // 2) Inside loop but not in original header
278   //
279   //    Replace this use to reflect definition from new header.
280   for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
281     const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
282
283     if (!ILoopHeaderInfo.Header)
284       continue;
285
286     Instruction *OldPhi = ILoopHeaderInfo.Original;
287     Instruction *NewPhi = ILoopHeaderInfo.Header;
288
289     // Before replacing uses, collect them first, so that iterator is
290     // not invalidated.
291     SmallVector<Instruction *, 16> AllUses;
292     for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
293          UI != UE; ++UI) {
294       Instruction *U = cast<Instruction>(UI);
295       AllUses.push_back(U);
296     }
297
298     for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(), 
299            UE = AllUses.end(); UI != UE; ++UI) {
300       Instruction *U = *UI;
301       BasicBlock *Parent = U->getParent();
302
303       // Used inside original header
304       if (Parent == OrigHeader) {
305         // Do not rename uses inside original header non-phi instructions.
306         PHINode *PU = dyn_cast<PHINode>(U);
307         if (!PU)
308           continue;
309
310         // Do not rename uses inside original header phi nodes, if the
311         // incoming value is for new header.
312         if (PU->getBasicBlockIndex(NewHeader) != -1
313             && PU->getIncomingValueForBlock(NewHeader) == U)
314           continue;
315         
316        U->replaceUsesOfWith(OldPhi, NewPhi);
317        continue;
318       }
319
320       // Used inside loop, but not in original header.
321       if (L->contains(U->getParent())) {
322         if (U != NewPhi)
323           U->replaceUsesOfWith(OldPhi, NewPhi);
324         continue;
325       }
326
327       // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
328       assert (U->getParent() == Exit 
329               && "Need to propagate new PHI into Exit blocks");
330       assert (isa<PHINode>(U) && "Use in Exit Block that is not PHINode");        
331
332       PHINode *UPhi = cast<PHINode>(U);
333
334       // UPhi already has one incoming argument from original header. 
335       // Add second incoming argument from new Pre header.
336       
337       UPhi->addIncoming(ILoopHeaderInfo.PreHeader, NewPreHeader);
338     }
339   }
340   
341   /// Make sure all Exit block PHINodes have required incoming values.
342   updateExitBlock();
343
344   // Update CFG
345
346   // Removing incoming branch from loop preheader to original header.
347   // Now original header is inside the loop.
348   OrigHeader->removePredecessor(OrigPreHeader);
349
350   // Establish NewPreHeader as loop preheader. Add unconditional branch
351   // from original loop pre-header to new loop pre-header. Add NewPreHEader
352   // in loop nest.
353   BranchInst *PH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
354   PH_BI->setSuccessor(0, NewPreHeader);
355   LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
356   if (Loop *PL = LI.getLoopFor(OrigPreHeader))
357     PL->addBasicBlockToLoop(NewPreHeader, LI);
358
359   // Make NewHeader as the new header for the loop.
360   L->moveToHeader(NewHeader);
361
362   NumRotated++;
363   return true;
364 }
365
366 /// Make sure all Exit block PHINodes have required incoming values.
367 /// If incoming value is constant or defined outside the loop then
368 /// PHINode may not have an entry for new pre-header. 
369 void LoopRotate::updateExitBlock() {
370
371   for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
372        I != E; ++I) {
373
374     PHINode *PN = dyn_cast<PHINode>(I);
375     if (!PN)
376       break;
377
378     // There is already one incoming value from new pre-header block.
379     if (PN->getBasicBlockIndex(NewPreHeader) != -1)
380       return;
381
382     const RenameData *ILoopHeaderInfo;
383     Value *V = PN->getIncomingValueForBlock(OrigHeader);
384     if (isa<Instruction>(V) && 
385         (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
386       assert (ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
387       PN->addIncoming(ILoopHeaderInfo->PreHeader, NewPreHeader);
388     } else {
389       PN->addIncoming(V, NewPreHeader);
390     }
391   }
392 }
393
394 /// Initialize local data
395 void LoopRotate::initialize() {
396   L = NULL;
397   OrigHeader = NULL;
398   OrigPreHeader = NULL;
399   NewHeader = NULL;
400   NewPreHeader = NULL;
401   Exit = NULL;
402
403   LoopHeaderInfo.clear();
404 }
405
406 /// Return true if this instruction is used by any instructions in the loop that
407 /// aren't in original header.
408 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
409
410   for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
411        UI != UE; ++UI) {
412     Instruction *U = cast<Instruction>(UI);
413     if (U->getParent() != OrigHeader) {
414       if (L->contains(U->getParent()))
415         return true;
416     }
417   }
418
419   return false;
420 }
421
422 /// Find Replacement information for instruction. Return NULL if it is
423 /// not available.
424 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
425
426   // Since LoopHeaderInfo is small, linear walk is OK.
427   for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
428     const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
429     if (ILoopHeaderInfo.Original == In)
430       return &ILoopHeaderInfo;
431   }
432   return NULL;
433 }