Passes do not need to recursively initialize passes that they preserve, if
[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/IntrinsicInst.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Transforms/Utils/SSAUpdater.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 LoopRotate : public LoopPass {
36   public:
37     static char ID; // Pass ID, replacement for typeid
38     LoopRotate() : LoopPass(ID) {
39       initializeLoopRotatePass(*PassRegistry::getPassRegistry());
40     }
41
42     // Rotate Loop L as many times as possible. Return true if
43     // loop is rotated at least once.
44     bool runOnLoop(Loop *L, LPPassManager &LPM);
45
46     // LCSSA form makes instruction renaming easier.
47     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48       AU.addPreserved<DominatorTree>();
49       AU.addPreserved<DominanceFrontier>();
50       AU.addRequired<LoopInfo>();
51       AU.addPreserved<LoopInfo>();
52       AU.addRequiredID(LoopSimplifyID);
53       AU.addPreservedID(LoopSimplifyID);
54       AU.addRequiredID(LCSSAID);
55       AU.addPreservedID(LCSSAID);
56       AU.addPreserved<ScalarEvolution>();
57     }
58
59     // Helper functions
60
61     /// Do actual work
62     bool rotateLoop(Loop *L, LPPassManager &LPM);
63     
64     /// Initialize local data
65     void initialize();
66
67     /// After loop rotation, loop pre-header has multiple sucessors.
68     /// Insert one forwarding basic block to ensure that loop pre-header
69     /// has only one successor.
70     void preserveCanonicalLoopForm(LPPassManager &LPM);
71
72   private:
73     Loop *L;
74     BasicBlock *OrigHeader;
75     BasicBlock *OrigPreHeader;
76     BasicBlock *OrigLatch;
77     BasicBlock *NewHeader;
78     BasicBlock *Exit;
79     LPPassManager *LPM_Ptr;
80   };
81 }
82   
83 char LoopRotate::ID = 0;
84 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
85 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
86 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
87 INITIALIZE_PASS_DEPENDENCY(LCSSA)
88 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
89
90 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
91
92 /// Rotate Loop L as many times as possible. Return true if
93 /// the loop is rotated at least once.
94 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
95
96   bool RotatedOneLoop = false;
97   initialize();
98   LPM_Ptr = &LPM;
99
100   // One loop can be rotated multiple times.
101   while (rotateLoop(Lp,LPM)) {
102     RotatedOneLoop = true;
103     initialize();
104   }
105
106   return RotatedOneLoop;
107 }
108
109 /// Rotate loop LP. Return true if the loop is rotated.
110 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
111   L = Lp;
112
113   OrigPreHeader = L->getLoopPreheader();
114   if (!OrigPreHeader) return false;
115
116   OrigLatch = L->getLoopLatch();
117   if (!OrigLatch) return false;
118
119   OrigHeader =  L->getHeader();
120
121   // If the loop has only one block then there is not much to rotate.
122   if (L->getBlocks().size() == 1)
123     return false;
124
125   // If the loop header is not one of the loop exiting blocks then
126   // either this loop is already rotated or it is not
127   // suitable for loop rotation transformations.
128   if (!L->isLoopExiting(OrigHeader))
129     return false;
130
131   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
132   if (!BI)
133     return false;
134   assert(BI->isConditional() && "Branch Instruction is not conditional");
135
136   // Updating PHInodes in loops with multiple exits adds complexity. 
137   // Keep it simple, and restrict loop rotation to loops with one exit only.
138   // In future, lift this restriction and support for multiple exits if
139   // required.
140   SmallVector<BasicBlock*, 8> ExitBlocks;
141   L->getExitBlocks(ExitBlocks);
142   if (ExitBlocks.size() > 1)
143     return false;
144
145   // Check size of original header and reject
146   // loop if it is very big.
147   unsigned Size = 0;
148   
149   // FIXME: Use common api to estimate size.
150   for (BasicBlock::const_iterator OI = OrigHeader->begin(), 
151          OE = OrigHeader->end(); OI != OE; ++OI) {
152     if (isa<PHINode>(OI)) 
153       continue;           // PHI nodes don't count.
154     if (isa<DbgInfoIntrinsic>(OI))
155       continue;  // Debug intrinsics don't count as size.
156     ++Size;
157   }
158
159   if (Size > MAX_HEADER_SIZE)
160     return false;
161
162   // Now, this loop is suitable for rotation.
163
164   // Anything ScalarEvolution may know about this loop or the PHI nodes
165   // in its header will soon be invalidated.
166   if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
167     SE->forgetLoop(L);
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 the new header has exactly one predecessor.
181   // Remove any single-entry PHI nodes in it.
182   assert(NewHeader->getSinglePredecessor() &&
183          "New header doesn't have one pred!");
184   FoldSingleEntryPHINodes(NewHeader);
185
186   // Begin by walking OrigHeader and populating ValueMap with an entry for
187   // each Instruction.
188   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
189   DenseMap<const Value *, Value *> ValueMap;
190
191   // For PHI nodes, the value available in OldPreHeader is just the
192   // incoming value from OldPreHeader.
193   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
194     ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
195
196   // For the rest of the instructions, either hoist to the OrigPreheader if
197   // possible or create a clone in the OldPreHeader if not.
198   TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
199   while (I != E) {
200     Instruction *Inst = I++;
201     
202     // If the instruction's operands are invariant and it doesn't read or write
203     // memory, then it is safe to hoist.  Doing this doesn't change the order of
204     // execution in the preheader, but does prevent the instruction from
205     // executing in each iteration of the loop.  This means it is safe to hoist
206     // something that might trap, but isn't safe to hoist something that reads
207     // memory (without proving that the loop doesn't write).
208     if (L->hasLoopInvariantOperands(Inst) &&
209         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
210         !isa<TerminatorInst>(Inst)) {
211       Inst->moveBefore(LoopEntryBranch);
212       continue;
213     }
214     
215     // Otherwise, create a duplicate of the instruction.
216     Instruction *C = Inst->clone();
217     C->setName(Inst->getName());
218     C->insertBefore(LoopEntryBranch);
219     ValueMap[Inst] = C;
220   }
221
222   // Along with all the other instructions, we just cloned OrigHeader's
223   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
224   // successors by duplicating their incoming values for OrigHeader.
225   TerminatorInst *TI = OrigHeader->getTerminator();
226   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
227     for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
228          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
229       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
230
231   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
232   // OrigPreHeader's old terminator (the original branch into the loop), and
233   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
234   LoopEntryBranch->eraseFromParent();
235   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
236     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
237
238   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
239   // as necessary.
240   SSAUpdater SSA;
241   for (I = OrigHeader->begin(); I != E; ++I) {
242     Value *OrigHeaderVal = I;
243     Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
244
245     // The value now exits in two versions: the initial value in the preheader
246     // and the loop "next" value in the original header.
247     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
248     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
249     SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
250
251     // Visit each use of the OrigHeader instruction.
252     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
253          UE = OrigHeaderVal->use_end(); UI != UE; ) {
254       // Grab the use before incrementing the iterator.
255       Use &U = UI.getUse();
256
257       // Increment the iterator before removing the use from the list.
258       ++UI;
259
260       // SSAUpdater can't handle a non-PHI use in the same block as an
261       // earlier def. We can easily handle those cases manually.
262       Instruction *UserInst = cast<Instruction>(U.getUser());
263       if (!isa<PHINode>(UserInst)) {
264         BasicBlock *UserBB = UserInst->getParent();
265
266         // The original users in the OrigHeader are already using the
267         // original definitions.
268         if (UserBB == OrigHeader)
269           continue;
270
271         // Users in the OrigPreHeader need to use the value to which the
272         // original definitions are mapped.
273         if (UserBB == OrigPreHeader) {
274           U = OrigPreHeaderVal;
275           continue;
276         }
277       }
278
279       // Anything else can be handled by SSAUpdater.
280       SSA.RewriteUse(U);
281     }
282   }
283
284   // NewHeader is now the header of the loop.
285   L->moveToHeader(NewHeader);
286
287   // Move the original header to the bottom of the loop, where it now more
288   // naturally belongs. This isn't necessary for correctness, and CodeGen can
289   // usually reorder blocks on its own to fix things like this up, but it's
290   // still nice to keep the IR readable.
291   //
292   // The original header should have only one predecessor at this point, since
293   // we checked that the loop had a proper preheader and unique backedge before
294   // we started.
295   assert(OrigHeader->getSinglePredecessor() &&
296          "Original loop header has too many predecessors after loop rotation!");
297   OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
298
299   // Also, since this original header only has one predecessor, zap its
300   // PHI nodes, which are now trivial.
301   FoldSingleEntryPHINodes(OrigHeader);
302
303   // TODO: We could just go ahead and merge OrigHeader into its predecessor
304   // at this point, if we don't mind updating dominator info.
305
306   // Establish a new preheader, update dominators, etc.
307   preserveCanonicalLoopForm(LPM);
308
309   ++NumRotated;
310   return true;
311 }
312
313 /// Initialize local data
314 void LoopRotate::initialize() {
315   L = NULL;
316   OrigHeader = NULL;
317   OrigPreHeader = NULL;
318   NewHeader = NULL;
319   Exit = NULL;
320 }
321
322 /// After loop rotation, loop pre-header has multiple sucessors.
323 /// Insert one forwarding basic block to ensure that loop pre-header
324 /// has only one successor.
325 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
326
327   // Right now original pre-header has two successors, new header and
328   // exit block. Insert new block between original pre-header and
329   // new header such that loop's new pre-header has only one successor.
330   BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
331                                                 "bb.nph",
332                                                 OrigHeader->getParent(), 
333                                                 NewHeader);
334   LoopInfo &LI = getAnalysis<LoopInfo>();
335   if (Loop *PL = LI.getLoopFor(OrigPreHeader))
336     PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
337   BranchInst::Create(NewHeader, NewPreHeader);
338   
339   BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
340   if (OrigPH_BI->getSuccessor(0) == NewHeader)
341     OrigPH_BI->setSuccessor(0, NewPreHeader);
342   else {
343     assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
344            "Unexpected original pre-header terminator");
345     OrigPH_BI->setSuccessor(1, NewPreHeader);
346   }
347
348   PHINode *PN;
349   for (BasicBlock::iterator I = NewHeader->begin();
350        (PN = dyn_cast<PHINode>(I)); ++I) {
351     int index = PN->getBasicBlockIndex(OrigPreHeader);
352     assert(index != -1 && "Expected incoming value from Original PreHeader");
353     PN->setIncomingBlock(index, NewPreHeader);
354     assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 && 
355            "Expected only one incoming value from Original PreHeader");
356   }
357
358   if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
359     DT->addNewBlock(NewPreHeader, OrigPreHeader);
360     DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
361     DT->changeImmediateDominator(Exit, OrigPreHeader);
362     for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
363          BI != BE; ++BI) {
364       BasicBlock *B = *BI;
365       if (L->getHeader() != B) {
366         DomTreeNode *Node = DT->getNode(B);
367         if (Node && Node->getBlock() == OrigHeader)
368           DT->changeImmediateDominator(*BI, L->getHeader());
369       }
370     }
371     DT->changeImmediateDominator(OrigHeader, OrigLatch);
372   }
373
374   if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
375     // New Preheader's dominance frontier is Exit block.
376     DominanceFrontier::DomSetType NewPHSet;
377     NewPHSet.insert(Exit);
378     DF->addBasicBlock(NewPreHeader, NewPHSet);
379
380     // New Header's dominance frontier now includes itself and Exit block
381     DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
382     if (HeadI != DF->end()) {
383       DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
384       HeaderSet.clear();
385       HeaderSet.insert(L->getHeader());
386       HeaderSet.insert(Exit);
387     } else {
388       DominanceFrontier::DomSetType HeaderSet;
389       HeaderSet.insert(L->getHeader());
390       HeaderSet.insert(Exit);
391       DF->addBasicBlock(L->getHeader(), HeaderSet);
392     }
393
394     // Original header (new Loop Latch)'s dominance frontier is Exit.
395     DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
396     if (LatchI != DF->end()) {
397       DominanceFrontier::DomSetType &LatchSet = LatchI->second;
398       LatchSet = LatchI->second;
399       LatchSet.clear();
400       LatchSet.insert(Exit);
401     } else {
402       DominanceFrontier::DomSetType LatchSet;
403       LatchSet.insert(Exit);
404       DF->addBasicBlock(L->getHeader(), LatchSet);
405     }
406
407     // If a loop block dominates new loop latch then add to its frontiers
408     // new header and Exit and remove new latch (which is equal to original
409     // header).
410     BasicBlock *NewLatch = L->getLoopLatch();
411
412     assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
413
414     if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
415       for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
416            BI != BE; ++BI) {
417         BasicBlock *B = *BI;
418         if (DT->dominates(B, NewLatch)) {
419           DominanceFrontier::iterator BDFI = DF->find(B);
420           if (BDFI != DF->end()) {
421             DominanceFrontier::DomSetType &BSet = BDFI->second;
422             BSet.erase(NewLatch);
423             BSet.insert(L->getHeader());
424             BSet.insert(Exit);
425           } else {
426             DominanceFrontier::DomSetType BSet;
427             BSet.insert(L->getHeader());
428             BSet.insert(Exit);
429             DF->addBasicBlock(B, BSet);
430           }
431         }
432       }
433     }
434   }
435
436   // Preserve canonical loop form, which means Exit block should
437   // have only one predecessor.
438   SplitEdge(L->getLoopLatch(), Exit, this);
439
440   assert(NewHeader && L->getHeader() == NewHeader &&
441          "Invalid loop header after loop rotation");
442   assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
443          "Invalid loop preheader after loop rotation");
444   assert(L->getLoopLatch() &&
445          "Invalid loop latch after loop rotation");
446 }