Preserve canonical loop form.
[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     /// 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);
82
83   private:
84
85     Loop *L;
86     BasicBlock *OrigHeader;
87     BasicBlock *OrigPreHeader;
88     BasicBlock *OrigLatch;
89     BasicBlock *NewHeader;
90     BasicBlock *Exit;
91
92     SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
93   };
94   
95   RegisterPass<LoopRotate> X ("loop-rotate", "Rotate Loops");
96 }
97
98 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
99
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) {
103   
104   bool RotatedOneLoop = false;
105   initialize();
106
107   // One loop can be rotated multiple times.
108   while (rotateLoop(Lp,LPM)) {
109     RotatedOneLoop = true;
110     initialize();
111   }
112
113   return RotatedOneLoop;
114 }
115
116 /// Rotate loop LP. Return true if it loop is rotated.
117 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
118
119   L = Lp;
120
121   OrigHeader =  L->getHeader();
122   OrigPreHeader = L->getLoopPreheader();
123   OrigLatch = L->getLoopLatch();
124
125   // If loop has only one block then there is not much to rotate.
126   if (L->getBlocks().size() == 1)
127     return false;
128
129   assert (OrigHeader && OrigLatch && OrigPreHeader &&
130           "Loop is not in cannocial form");
131
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))
136     return false;
137
138   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
139   if (!BI)
140     return false;
141   assert (BI->isConditional() && "Branch Instruction is not condiitional");
142
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
146   // required.
147   std::vector<BasicBlock *> ExitBlocks;
148   L->getExitBlocks(ExitBlocks);
149   if (ExitBlocks.size() > 1)
150     return false;
151
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");
162
163   // Check size of original header and reject
164   // loop if it is very big.
165   if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
166     return false;
167
168   // Now, this loop is suitable for rotation.
169
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. 
173   //
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.
182
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();
187   PHINode *PN = NULL;
188   for (; (PN = dyn_cast<PHINode>(I)); ++I) {
189     Instruction *In = I;
190
191     // PHI nodes are not copied into original pre-header. Instead their values
192     // are directly propagated.
193     Value * NPV = PN->getIncomingValueForBlock(OrigPreHeader);
194
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);
202     
203     // "In" can be replaced by NH at various places.
204     LoopHeaderInfo.push_back(RenameData(In, NPV, NH));
205   }
206
207   // Now, handle non-phi instructions.
208   for (; I != E; ++I) {
209     Instruction *In = I;
210
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);
218
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);
225         }
226       }
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);
231       }
232     }
233
234
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;
244     } 
245     
246     // "In" can be replaced by NPH or NH at various places.
247     LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
248   }
249
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.
253   //
254   // Original header instructions are used in
255   // 1) Original header:
256   //
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.
260   //
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
263   //    or new header.
264   //
265   // 2) Inside loop but not in original header
266   //
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];
270
271     if (!ILoopHeaderInfo.Header)
272       continue;
273
274     Instruction *OldPhi = ILoopHeaderInfo.Original;
275     Instruction *NewPhi = ILoopHeaderInfo.Header;
276
277     // Before replacing uses, collect them first, so that iterator is
278     // not invalidated.
279     SmallVector<Instruction *, 16> AllUses;
280     for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
281          UI != UE; ++UI) {
282       Instruction *U = cast<Instruction>(UI);
283       AllUses.push_back(U);
284     }
285
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();
290
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);
295         if (!PU)
296           continue;
297
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)
302           continue;
303         
304        U->replaceUsesOfWith(OldPhi, NewPhi);
305        continue;
306       }
307
308       // Used inside loop, but not in original header.
309       if (L->contains(U->getParent())) {
310         if (U != NewPhi)
311           U->replaceUsesOfWith(OldPhi, NewPhi);
312         continue;
313       }
314
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");        
319
320       PHINode *UPhi = cast<PHINode>(U);
321
322       // UPhi already has one incoming argument from original header. 
323       // Add second incoming argument from new Pre header.
324       
325       UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
326     }
327   }
328   
329   /// Make sure all Exit block PHINodes have required incoming values.
330   updateExitBlock();
331
332   // Update CFG
333
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();
337        I != E; ++I) {
338     Instruction *In = I;
339     PHINode *PN = dyn_cast<PHINode>(In);
340     if (!PN)
341       break;
342
343     PN->removeIncomingValue(OrigPreHeader);
344   }
345
346   // Make NewHeader as the new header for the loop.
347   L->moveToHeader(NewHeader);
348
349   preserveCanonicalLoopForm(LPM);
350
351   NumRotated++;
352   return true;
353 }
354
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() {
359
360   for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
361        I != E; ++I) {
362
363     PHINode *PN = dyn_cast<PHINode>(I);
364     if (!PN)
365       break;
366
367     // There is already one incoming value from original pre-header block.
368     if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
369       return;
370
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);
377     } else {
378       PN->addIncoming(V, OrigPreHeader);
379     }
380   }
381 }
382
383 /// Initialize local data
384 void LoopRotate::initialize() {
385   L = NULL;
386   OrigHeader = NULL;
387   OrigPreHeader = NULL;
388   NewHeader = NULL;
389   Exit = NULL;
390
391   LoopHeaderInfo.clear();
392 }
393
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) {
397
398   for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
399        UI != UE; ++UI) {
400     Instruction *U = cast<Instruction>(UI);
401     if (U->getParent() != OrigHeader) {
402       if (L->contains(U->getParent()))
403         return true;
404     }
405   }
406
407   return false;
408 }
409
410 /// Find Replacement information for instruction. Return NULL if it is
411 /// not available.
412 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
413
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;
419   }
420   return NULL;
421 }
422
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) {
427
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(), 
432                                 OrigPreHeader);
433   LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
434   if (Loop *PL = LI.getLoopFor(OrigPreHeader))
435     PL->addBasicBlockToLoop(NewPreHeader, LI);
436   new BranchInst(NewHeader, NewPreHeader);
437   
438   BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
439   if (OrigPH_BI->getSuccessor(0) == NewHeader)
440     OrigPH_BI->setSuccessor(0, NewPreHeader);
441   else {
442     assert (OrigPH_BI->getSuccessor(1) == NewPreHeader &&
443             "Unexpected original pre-header terminator");
444     OrigPH_BI->setSuccessor(1, NewPreHeader);
445   }
446   
447   for (BasicBlock::iterator I = NewHeader->begin(), E = NewHeader->end();
448        I != E; ++I) {
449     Instruction *In = I;
450     PHINode *PN = dyn_cast<PHINode>(In);
451     if (!PN)
452       break;
453
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");
459   }
460
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");
467 }