Clean up the use of static and anonymous namespaces. This turned up
[oota-llvm.git] / lib / Transforms / Scalar / LoopRotation.cpp
1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Analysis/Dominators.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/SmallVector.h"
29
30 using namespace llvm;
31
32 #define MAX_HEADER_SIZE 16
33
34 STATISTIC(NumRotated, "Number of loops rotated");
35 namespace {
36
37   class VISIBILITY_HIDDEN RenameData {
38   public:
39     RenameData(Instruction *O, Value *P, Instruction *H) 
40       : Original(O), PreHeader(P), Header(H) { }
41   public:
42     Instruction *Original; // Original instruction
43     Value *PreHeader; // Original pre-header replacement
44     Instruction *Header; // New header replacement
45   };
46   
47   class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
48
49   public:
50     static char ID; // Pass ID, replacement for typeid
51     LoopRotate() : LoopPass((intptr_t)&ID) {}
52
53     // Rotate Loop L as many times as possible. Return true if
54     // loop is rotated at least once.
55     bool runOnLoop(Loop *L, LPPassManager &LPM);
56
57     // LCSSA form makes instruction renaming easier.
58     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59       AU.addRequiredID(LoopSimplifyID);
60       AU.addPreservedID(LoopSimplifyID);
61       AU.addRequiredID(LCSSAID);
62       AU.addPreservedID(LCSSAID);
63       AU.addPreserved<ScalarEvolution>();
64       AU.addPreserved<LoopInfo>();
65       AU.addPreserved<DominatorTree>();
66       AU.addPreserved<DominanceFrontier>();
67     }
68
69     // Helper functions
70
71     /// Do actual work
72     bool rotateLoop(Loop *L, LPPassManager &LPM);
73     
74     /// Initialize local data
75     void initialize();
76
77     /// Make sure all Exit block PHINodes have required incoming values.
78     /// If incoming value is constant or defined outside the loop then
79     /// PHINode may not have an entry for original pre-header. 
80     void  updateExitBlock();
81
82     /// Return true if this instruction is used outside original header.
83     bool usedOutsideOriginalHeader(Instruction *In);
84
85     /// Find Replacement information for instruction. Return NULL if it is
86     /// not available.
87     const RenameData *findReplacementData(Instruction *I);
88
89     /// After loop rotation, loop pre-header has multiple sucessors.
90     /// Insert one forwarding basic block to ensure that loop pre-header
91     /// has only one successor.
92     void preserveCanonicalLoopForm(LPPassManager &LPM);
93
94   private:
95
96     Loop *L;
97     BasicBlock *OrigHeader;
98     BasicBlock *OrigPreHeader;
99     BasicBlock *OrigLatch;
100     BasicBlock *NewHeader;
101     BasicBlock *Exit;
102     LPPassManager *LPM_Ptr;
103     SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
104   };
105 }
106   
107 char LoopRotate::ID = 0;
108 static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
109
110 LoopPass *llvm::createLoopRotatePass() { return new LoopRotate(); }
111
112 /// Rotate Loop L as many times as possible. Return true if
113 /// loop is rotated at least once.
114 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
115
116   bool RotatedOneLoop = false;
117   initialize();
118   LPM_Ptr = &LPM;
119
120   // One loop can be rotated multiple times.
121   while (rotateLoop(Lp,LPM)) {
122     RotatedOneLoop = true;
123     initialize();
124   }
125
126   return RotatedOneLoop;
127 }
128
129 /// Rotate loop LP. Return true if the loop is rotated.
130 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
131
132   L = Lp;
133
134   OrigHeader =  L->getHeader();
135   OrigPreHeader = L->getLoopPreheader();
136   OrigLatch = L->getLoopLatch();
137
138   // If loop has only one block then there is not much to rotate.
139   if (L->getBlocks().size() == 1)
140     return false;
141
142   assert (OrigHeader && OrigLatch && OrigPreHeader &&
143           "Loop is not in canonical form");
144
145   // If loop header is not one of the loop exit block then
146   // either this loop is already rotated or it is not 
147   // suitable for loop rotation transformations.
148   if (!L->isLoopExit(OrigHeader))
149     return false;
150
151   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
152   if (!BI)
153     return false;
154   assert (BI->isConditional() && "Branch Instruction is not conditional");
155
156   // Updating PHInodes in loops with multiple exits adds complexity. 
157   // Keep it simple, and restrict loop rotation to loops with one exit only.
158   // In future, lift this restriction and support for multiple exits if
159   // required.
160   SmallVector<BasicBlock*, 8> ExitBlocks;
161   L->getExitBlocks(ExitBlocks);
162   if (ExitBlocks.size() > 1)
163     return false;
164
165   // Check size of original header and reject
166   // loop if it is very big.
167   if (OrigHeader->getInstList().size() > MAX_HEADER_SIZE)
168     return false;
169
170   // Now, this loop is suitable for rotation.
171
172   // Find new Loop header. NewHeader is a Header's one and only successor
173   // that is inside loop.  Header's other successor is out side the
174   // loop. Otherwise loop is not suitable for rotation.
175   Exit = BI->getSuccessor(0);
176   NewHeader = BI->getSuccessor(1);
177   if (L->contains(Exit))
178     std::swap(Exit, NewHeader);
179   assert (NewHeader && "Unable to determine new loop header");
180   assert(L->contains(NewHeader) && !L->contains(Exit) && 
181          "Unable to determine loop header and exit blocks");
182
183   // Copy PHI nodes and other instructions from original header
184   // into original pre-header. Unlike original header, original pre-header is
185   // not a member of loop. 
186   //
187   // New loop header is one and only successor of original header that 
188   // is inside the loop. All other original header successors are outside 
189   // the loop. Copy PHI Nodes from original header into new loop header. 
190   // Add second incoming value, from original loop pre-header into these phi 
191   // nodes. If a value defined in original header is used outside original 
192   // header then new loop header will need new phi nodes with two incoming 
193   // values, one definition from original header and second definition is 
194   // from original loop pre-header.
195
196   // Remove terminator from Original pre-header. Original pre-header will
197   // receive a clone of original header terminator as a new terminator.
198   OrigPreHeader->getInstList().pop_back();
199   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
200   PHINode *PN = NULL;
201   for (; (PN = dyn_cast<PHINode>(I)); ++I) {
202     Instruction *In = I;
203
204     // PHI nodes are not copied into original pre-header. Instead their values
205     // are directly propagated.
206     Value * NPV = PN->getIncomingValueForBlock(OrigPreHeader);
207
208     // Create new PHI node with two incoming values for NewHeader.
209     // One incoming value is from OrigLatch (through OrigHeader) and 
210     // second incoming value is from original pre-header.
211     PHINode *NH = PHINode::Create(In->getType(), In->getName());
212     NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
213     NH->addIncoming(NPV, OrigPreHeader);
214     NewHeader->getInstList().push_front(NH);
215     
216     // "In" can be replaced by NH at various places.
217     LoopHeaderInfo.push_back(RenameData(In, NPV, NH));
218   }
219
220   // Now, handle non-phi instructions.
221   for (; I != E; ++I) {
222     Instruction *In = I;
223
224     assert (!isa<PHINode>(In) && "PHINode is not expected here");
225     // This is not a PHI instruction. Insert its clone into original pre-header.
226     // If this instruction is using a value from same basic block then
227     // update it to use value from cloned instruction.
228     Instruction *C = In->clone();
229     C->setName(In->getName());
230     OrigPreHeader->getInstList().push_back(C);
231
232     for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
233       if (Instruction *OpPhi = dyn_cast<PHINode>(In->getOperand(opi))) {
234         if (const RenameData *D = findReplacementData(OpPhi)) {
235           // This is using values from original header PHI node.
236           // Here, directly used incoming value from original pre-header.
237           C->setOperand(opi, D->PreHeader);
238         }
239       }
240       else if (Instruction *OpInsn = 
241                dyn_cast<Instruction>(In->getOperand(opi))) {
242         if (const RenameData *D = findReplacementData(OpInsn))
243           C->setOperand(opi, D->PreHeader);
244       }
245     }
246
247
248     // If this instruction is used outside this basic block then
249     // create new PHINode for this instruction.
250     Instruction *NewHeaderReplacement = NULL;
251     if (usedOutsideOriginalHeader(In)) {
252       // FIXME: remove this when we have first-class aggregates.
253       if (isa<StructType>(In->getType())) {
254         // Can't create PHI nodes for this type.  If there are any getResults
255         // not defined in this block, move them back to this block.  PHI
256         // nodes will be created for all getResults later.
257         BasicBlock::iterator InsertPoint;
258         if (InvokeInst *II = dyn_cast<InvokeInst>(In)) {
259           InsertPoint = II->getNormalDest()->begin();
260           while (isa<PHINode>(InsertPoint)) 
261             ++InsertPoint;
262         } else {
263           InsertPoint = I;  // call
264           ++InsertPoint;
265         }
266         for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
267              UI != UE; ++UI) {
268           GetResultInst *InGR = cast<GetResultInst>(UI);
269           if (InGR->getParent() != OrigHeader) {
270             // Move InGR to immediately after the call or in the normal dest of
271             // the invoke.  It will be picked up, cloned and PHI'd on the next
272             // iteration.
273             InGR->moveBefore(InsertPoint);
274           }
275         }
276       } else {
277         PHINode *PN = PHINode::Create(In->getType(), In->getName());
278         PN->addIncoming(In, OrigHeader);
279         PN->addIncoming(C, OrigPreHeader);
280         NewHeader->getInstList().push_front(PN);
281         NewHeaderReplacement = PN;
282       }
283     }
284     LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
285   }
286
287   // Rename uses of original header instructions to reflect their new
288   // definitions (either from original pre-header node or from newly created
289   // new header PHINodes.
290   //
291   // Original header instructions are used in
292   // 1) Original header:
293   //
294   //    If instruction is used in non-phi instructions then it is using
295   //    defintion from original heder iteself. Do not replace this use
296   //    with definition from new header or original pre-header.
297   //
298   //    If instruction is used in phi node then it is an incoming 
299   //    value. Rename its use to reflect new definition from new-preheader
300   //    or new header.
301   //
302   // 2) Inside loop but not in original header
303   //
304   //    Replace this use to reflect definition from new header.
305   for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
306     const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
307
308     if (!ILoopHeaderInfo.Header)
309       continue;
310
311     Instruction *OldPhi = ILoopHeaderInfo.Original;
312     Instruction *NewPhi = ILoopHeaderInfo.Header;
313
314     // Before replacing uses, collect them first, so that iterator is
315     // not invalidated.
316     SmallVector<Instruction *, 16> AllUses;
317     for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
318          UI != UE; ++UI) {
319       Instruction *U = cast<Instruction>(UI);
320       AllUses.push_back(U);
321     }
322
323     for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(), 
324            UE = AllUses.end(); UI != UE; ++UI) {
325       Instruction *U = *UI;
326       BasicBlock *Parent = U->getParent();
327
328       // Used inside original header
329       if (Parent == OrigHeader) {
330         // Do not rename uses inside original header non-phi instructions.
331         PHINode *PU = dyn_cast<PHINode>(U);
332         if (!PU)
333           continue;
334
335         // Do not rename uses inside original header phi nodes, if the
336         // incoming value is for new header.
337         if (PU->getBasicBlockIndex(NewHeader) != -1
338             && PU->getIncomingValueForBlock(NewHeader) == U)
339           continue;
340         
341        U->replaceUsesOfWith(OldPhi, NewPhi);
342        continue;
343       }
344
345       // Used inside loop, but not in original header.
346       if (L->contains(U->getParent())) {
347         if (U != NewPhi)
348           U->replaceUsesOfWith(OldPhi, NewPhi);
349         continue;
350       }
351       
352       // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
353       if (U->getParent() == Exit) {
354         assert (isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
355         
356         PHINode *UPhi = cast<PHINode>(U);
357         // UPhi already has one incoming argument from original header. 
358         // Add second incoming argument from new Pre header.
359         UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
360       } else {
361         // Used outside Exit block. Create a new PHI node from exit block
362         // to receive value from ne new header ane pre header.
363         PHINode *PN = PHINode::Create(U->getType(), U->getName());
364         PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
365         PN->addIncoming(OldPhi, OrigHeader);
366         Exit->getInstList().push_front(PN);
367         U->replaceUsesOfWith(OldPhi, PN);
368       }
369     }
370   }
371   
372   /// Make sure all Exit block PHINodes have required incoming values.
373   updateExitBlock();
374
375   // Update CFG
376
377   // Removing incoming branch from loop preheader to original header.
378   // Now original header is inside the loop.
379   for (BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
380        I != E; ++I) {
381     Instruction *In = I;
382     PHINode *PN = dyn_cast<PHINode>(In);
383     if (!PN)
384       break;
385
386     PN->removeIncomingValue(OrigPreHeader);
387   }
388
389   // Make NewHeader as the new header for the loop.
390   L->moveToHeader(NewHeader);
391
392   preserveCanonicalLoopForm(LPM);
393
394   NumRotated++;
395   return true;
396 }
397
398 /// Make sure all Exit block PHINodes have required incoming values.
399 /// If incoming value is constant or defined outside the loop then
400 /// PHINode may not have an entry for original pre-header. 
401 void LoopRotate::updateExitBlock() {
402
403   for (BasicBlock::iterator I = Exit->begin(), E = Exit->end();
404        I != E; ++I) {
405
406     PHINode *PN = dyn_cast<PHINode>(I);
407     if (!PN)
408       break;
409
410     // There is already one incoming value from original pre-header block.
411     if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
412       continue;
413
414     const RenameData *ILoopHeaderInfo;
415     Value *V = PN->getIncomingValueForBlock(OrigHeader);
416     if (isa<Instruction>(V) && 
417         (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
418       assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
419       PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
420     } else {
421       PN->addIncoming(V, OrigPreHeader);
422     }
423   }
424 }
425
426 /// Initialize local data
427 void LoopRotate::initialize() {
428   L = NULL;
429   OrigHeader = NULL;
430   OrigPreHeader = NULL;
431   NewHeader = NULL;
432   Exit = NULL;
433
434   LoopHeaderInfo.clear();
435 }
436
437 /// Return true if this instruction is used by any instructions in the loop that
438 /// aren't in original header.
439 bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
440
441   for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
442        UI != UE; ++UI) {
443     Instruction *U = cast<Instruction>(UI);
444     if (U->getParent() != OrigHeader) {
445       if (L->contains(U->getParent()))
446         return true;
447     }
448   }
449
450   return false;
451 }
452
453 /// Find Replacement information for instruction. Return NULL if it is
454 /// not available.
455 const RenameData *LoopRotate::findReplacementData(Instruction *In) {
456
457   // Since LoopHeaderInfo is small, linear walk is OK.
458   for(unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
459     const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
460     if (ILoopHeaderInfo.Original == In)
461       return &ILoopHeaderInfo;
462   }
463   return NULL;
464 }
465
466 /// After loop rotation, loop pre-header has multiple sucessors.
467 /// Insert one forwarding basic block to ensure that loop pre-header
468 /// has only one successor.
469 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
470
471   // Right now original pre-header has two successors, new header and
472   // exit block. Insert new block between original pre-header and
473   // new header such that loop's new pre-header has only one successor.
474   BasicBlock *NewPreHeader = BasicBlock::Create("bb.nph", OrigHeader->getParent(), 
475                                                 NewHeader);
476   LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
477   if (Loop *PL = LI.getLoopFor(OrigPreHeader))
478     PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
479   BranchInst::Create(NewHeader, NewPreHeader);
480   
481   BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
482   if (OrigPH_BI->getSuccessor(0) == NewHeader)
483     OrigPH_BI->setSuccessor(0, NewPreHeader);
484   else {
485     assert (OrigPH_BI->getSuccessor(1) == NewHeader &&
486             "Unexpected original pre-header terminator");
487     OrigPH_BI->setSuccessor(1, NewPreHeader);
488   }
489   
490   for (BasicBlock::iterator I = NewHeader->begin(), E = NewHeader->end();
491        I != E; ++I) {
492     Instruction *In = I;
493     PHINode *PN = dyn_cast<PHINode>(In);
494     if (!PN)
495       break;
496
497     int index = PN->getBasicBlockIndex(OrigPreHeader);
498     assert (index != -1 && "Expected incoming value from Original PreHeader");
499     PN->setIncomingBlock(index, NewPreHeader);
500     assert (PN->getBasicBlockIndex(OrigPreHeader) == -1 && 
501             "Expected only one incoming value from Original PreHeader");
502   }
503
504   if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
505     DT->addNewBlock(NewPreHeader, OrigPreHeader);
506     DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
507     DT->changeImmediateDominator(Exit, OrigPreHeader);
508     for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
509          BI != BE; ++BI) {
510       BasicBlock *B = *BI;
511       if (L->getHeader() != B) {
512         DomTreeNode *Node = DT->getNode(B);
513         if (Node && Node->getBlock() == OrigHeader)
514           DT->changeImmediateDominator(*BI, L->getHeader());
515       }
516     }
517     DT->changeImmediateDominator(OrigHeader, OrigLatch);
518   }
519
520   if(DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
521
522     // New Preheader's dominance frontier is Exit block.
523     DominanceFrontier::DomSetType NewPHSet;
524     NewPHSet.insert(Exit);
525     DF->addBasicBlock(NewPreHeader, NewPHSet);
526
527     // New Header's dominance frontier now includes itself and Exit block
528     DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
529     if (HeadI != DF->end()) {
530       DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
531       HeaderSet.clear();
532       HeaderSet.insert(L->getHeader());
533       HeaderSet.insert(Exit);
534     } else {
535       DominanceFrontier::DomSetType HeaderSet;
536       HeaderSet.insert(L->getHeader());
537       HeaderSet.insert(Exit);
538       DF->addBasicBlock(L->getHeader(), HeaderSet);
539     }
540
541     // Original header (new Loop Latch)'s dominance frontier is Exit.
542     DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
543     if (LatchI != DF->end()) {
544       DominanceFrontier::DomSetType &LatchSet = LatchI->second;
545       LatchSet = LatchI->second;
546       LatchSet.clear();
547       LatchSet.insert(Exit);
548     } else {
549       DominanceFrontier::DomSetType LatchSet;
550       LatchSet.insert(Exit);
551       DF->addBasicBlock(L->getHeader(), LatchSet);
552     }
553
554     // If a loop block dominates new loop latch then its frontier is
555     // new header and Exit.
556     BasicBlock *NewLatch = L->getLoopLatch();
557     DominatorTree *DT = getAnalysisToUpdate<DominatorTree>();
558     for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
559          BI != BE; ++BI) {
560       BasicBlock *B = *BI;
561       if (DT->dominates(B, NewLatch)) {
562         DominanceFrontier::iterator BDFI = DF->find(B);
563         if (BDFI != DF->end()) {
564           DominanceFrontier::DomSetType &BSet = BDFI->second;
565           BSet = BDFI->second;
566           BSet.clear();
567           BSet.insert(L->getHeader());
568           BSet.insert(Exit);
569         } else {
570           DominanceFrontier::DomSetType BSet;
571           BSet.insert(L->getHeader());
572           BSet.insert(Exit);
573           DF->addBasicBlock(B, BSet);
574         }
575       }
576     }
577   }
578
579   // Preserve canonical loop form, which means Exit block should
580   // have only one predecessor.
581   BasicBlock *NExit = SplitEdge(L->getLoopLatch(), Exit, this);
582
583   // Preserve LCSSA.
584   BasicBlock::iterator I = Exit->begin(), E = Exit->end();
585   PHINode *PN = NULL;
586   for (; (PN = dyn_cast<PHINode>(I)); ++I) {
587     PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName());
588     unsigned N = PN->getNumIncomingValues();
589     for (unsigned index = 0; index < N; ++index)
590       if (PN->getIncomingBlock(index) == NExit) {
591         NewPN->addIncoming(PN->getIncomingValue(index), L->getLoopLatch());
592         PN->setIncomingValue(index, NewPN);
593         PN->setIncomingBlock(index, NExit);
594         NExit->getInstList().push_front(NewPN);
595       }
596   }
597
598   assert (NewHeader && L->getHeader() == NewHeader 
599           && "Invalid loop header after loop rotation");
600   assert (NewPreHeader && L->getLoopPreheader() == NewPreHeader
601           && "Invalid loop preheader after loop rotation");
602   assert (L->getLoopLatch() 
603           && "Invalid loop latch after loop rotation");
604
605 }