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