Implement a TODO: Enhance loopinfo to merge away the unconditional branch
[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/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/InstructionSimplify.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/Transforms/Utils/ValueMapper.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 using namespace llvm;
28
29 #define MAX_HEADER_SIZE 16
30
31 STATISTIC(NumRotated, "Number of loops rotated");
32 namespace {
33
34   class LoopRotate : public LoopPass {
35   public:
36     static char ID; // Pass ID, replacement for typeid
37     LoopRotate() : LoopPass(ID) {
38       initializeLoopRotatePass(*PassRegistry::getPassRegistry());
39     }
40
41     // LCSSA form makes instruction renaming easier.
42     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
43       AU.addPreserved<DominatorTree>();
44       AU.addRequired<LoopInfo>();
45       AU.addPreserved<LoopInfo>();
46       AU.addRequiredID(LoopSimplifyID);
47       AU.addPreservedID(LoopSimplifyID);
48       AU.addRequiredID(LCSSAID);
49       AU.addPreservedID(LCSSAID);
50       AU.addPreserved<ScalarEvolution>();
51     }
52
53     bool runOnLoop(Loop *L, LPPassManager &LPM);
54     bool rotateLoop(Loop *L);
55     
56   private:
57     LoopInfo *LI;
58   };
59 }
60   
61 char LoopRotate::ID = 0;
62 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
63 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
64 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
65 INITIALIZE_PASS_DEPENDENCY(LCSSA)
66 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
67
68 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
69
70 /// Rotate Loop L as many times as possible. Return true if
71 /// the loop is rotated at least once.
72 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
73   LI = &getAnalysis<LoopInfo>();
74
75   // One loop can be rotated multiple times.
76   bool MadeChange = false;
77   while (rotateLoop(L))
78     MadeChange = true;
79
80   return MadeChange;
81 }
82
83 /// Rotate loop LP. Return true if the loop is rotated.
84 bool LoopRotate::rotateLoop(Loop *L) {
85   // If the loop has only one block then there is not much to rotate.
86   if (L->getBlocks().size() == 1)
87     return false;
88   
89   BasicBlock *OrigHeader = L->getHeader();
90   
91   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
92   if (BI == 0 || BI->isUnconditional())
93     return false;
94   
95   // If the loop header is not one of the loop exiting blocks then
96   // either this loop is already rotated or it is not
97   // suitable for loop rotation transformations.
98   if (!L->isLoopExiting(OrigHeader))
99     return false;
100
101   // Updating PHInodes in loops with multiple exits adds complexity. 
102   // Keep it simple, and restrict loop rotation to loops with one exit only.
103   // In future, lift this restriction and support for multiple exits if
104   // required.
105   SmallVector<BasicBlock*, 8> ExitBlocks;
106   L->getExitBlocks(ExitBlocks);
107   if (ExitBlocks.size() > 1)
108     return false;
109
110   // Check size of original header and reject loop if it is very big.
111   {
112     CodeMetrics Metrics;
113     Metrics.analyzeBasicBlock(OrigHeader);
114     if (Metrics.NumInsts > MAX_HEADER_SIZE)
115       return false;
116   }
117
118   // Now, this loop is suitable for rotation.
119   BasicBlock *OrigPreHeader = L->getLoopPreheader();
120   BasicBlock *OrigLatch = L->getLoopLatch();
121   assert(OrigPreHeader && OrigLatch && "Loop not in canonical form?");
122
123   // Anything ScalarEvolution may know about this loop or the PHI nodes
124   // in its header will soon be invalidated.
125   if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
126     SE->forgetLoop(L);
127
128   // Find new Loop header. NewHeader is a Header's one and only successor
129   // that is inside loop.  Header's other successor is outside the
130   // loop.  Otherwise loop is not suitable for rotation.
131   BasicBlock *Exit = BI->getSuccessor(0);
132   BasicBlock *NewHeader = BI->getSuccessor(1);
133   if (L->contains(Exit))
134     std::swap(Exit, NewHeader);
135   assert(NewHeader && "Unable to determine new loop header");
136   assert(L->contains(NewHeader) && !L->contains(Exit) && 
137          "Unable to determine loop header and exit blocks");
138   
139   // This code assumes that the new header has exactly one predecessor.
140   // Remove any single-entry PHI nodes in it.
141   assert(NewHeader->getSinglePredecessor() &&
142          "New header doesn't have one pred!");
143   FoldSingleEntryPHINodes(NewHeader);
144
145   // Begin by walking OrigHeader and populating ValueMap with an entry for
146   // each Instruction.
147   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
148   ValueToValueMapTy ValueMap;
149
150   // For PHI nodes, the value available in OldPreHeader is just the
151   // incoming value from OldPreHeader.
152   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
153     ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
154
155   // For the rest of the instructions, either hoist to the OrigPreheader if
156   // possible or create a clone in the OldPreHeader if not.
157   TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
158   while (I != E) {
159     Instruction *Inst = I++;
160     
161     // If the instruction's operands are invariant and it doesn't read or write
162     // memory, then it is safe to hoist.  Doing this doesn't change the order of
163     // execution in the preheader, but does prevent the instruction from
164     // executing in each iteration of the loop.  This means it is safe to hoist
165     // something that might trap, but isn't safe to hoist something that reads
166     // memory (without proving that the loop doesn't write).
167     if (L->hasLoopInvariantOperands(Inst) &&
168         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
169         !isa<TerminatorInst>(Inst)) {
170       Inst->moveBefore(LoopEntryBranch);
171       continue;
172     }
173     
174     // Otherwise, create a duplicate of the instruction.
175     Instruction *C = Inst->clone();
176     
177     // Eagerly remap the operands of the instruction.
178     RemapInstruction(C, ValueMap,
179                      RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
180     
181     // With the operands remapped, see if the instruction constant folds or is
182     // otherwise simplifyable.  This commonly occurs because the entry from PHI
183     // nodes allows icmps and other instructions to fold.
184     Value *V = SimplifyInstruction(C);
185     if (V && LI->replacementPreservesLCSSAForm(C, V)) {
186       // If so, then delete the temporary instruction and stick the folded value
187       // in the map.
188       delete C;
189       ValueMap[Inst] = V;
190     } else {
191       // Otherwise, stick the new instruction into the new block!
192       C->setName(Inst->getName());
193       C->insertBefore(LoopEntryBranch);
194       ValueMap[Inst] = C;
195     }
196   }
197
198   // Along with all the other instructions, we just cloned OrigHeader's
199   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
200   // successors by duplicating their incoming values for OrigHeader.
201   TerminatorInst *TI = OrigHeader->getTerminator();
202   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
203     for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
204          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
205       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
206
207   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
208   // OrigPreHeader's old terminator (the original branch into the loop), and
209   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
210   LoopEntryBranch->eraseFromParent();
211   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
212     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
213
214   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
215   // as necessary.
216   SSAUpdater SSA;
217   for (I = OrigHeader->begin(); I != E; ++I) {
218     Value *OrigHeaderVal = I;
219     Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
220
221     // If there are no uses of the value (e.g. because it returns void), there
222     // is nothing to rewrite.
223     if (OrigHeaderVal->use_empty() && OrigPreHeaderVal->use_empty())
224       continue;
225     
226     // The value now exits in two versions: the initial value in the preheader
227     // and the loop "next" value in the original header.
228     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
229     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
230     SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
231
232     // Visit each use of the OrigHeader instruction.
233     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
234          UE = OrigHeaderVal->use_end(); UI != UE; ) {
235       // Grab the use before incrementing the iterator.
236       Use &U = UI.getUse();
237
238       // Increment the iterator before removing the use from the list.
239       ++UI;
240
241       // SSAUpdater can't handle a non-PHI use in the same block as an
242       // earlier def. We can easily handle those cases manually.
243       Instruction *UserInst = cast<Instruction>(U.getUser());
244       if (!isa<PHINode>(UserInst)) {
245         BasicBlock *UserBB = UserInst->getParent();
246
247         // The original users in the OrigHeader are already using the
248         // original definitions.
249         if (UserBB == OrigHeader)
250           continue;
251
252         // Users in the OrigPreHeader need to use the value to which the
253         // original definitions are mapped.
254         if (UserBB == OrigPreHeader) {
255           U = OrigPreHeaderVal;
256           continue;
257         }
258       }
259
260       // Anything else can be handled by SSAUpdater.
261       SSA.RewriteUse(U);
262     }
263   }
264
265   // NewHeader is now the header of the loop.
266   L->moveToHeader(NewHeader);
267   assert(L->getHeader() == NewHeader && "Latch block is our new header");
268
269   // Move the original header to the bottom of the loop, where it now more
270   // naturally belongs. This isn't necessary for correctness, and CodeGen can
271   // usually reorder blocks on its own to fix things like this up, but it's
272   // still nice to keep the IR readable.
273   //
274   // The original header should have only one predecessor at this point, since
275   // we checked that the loop had a proper preheader and unique backedge before
276   // we started.
277   assert(OrigHeader->getSinglePredecessor() &&
278          "Original loop header has too many predecessors after loop rotation!");
279   OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
280
281   
282   // Update DominatorTree to reflect the CFG change we just made.  Then split
283   // edges as necessary to preserve LoopSimplify form.
284   if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
285     // Since OrigPreheader now has the conditional branch to Exit block, it is
286     // the dominator of Exit.
287     DT->changeImmediateDominator(Exit, OrigPreHeader);
288     DT->changeImmediateDominator(NewHeader, OrigPreHeader);
289     
290     // Update OrigHeader to be dominated by the new header block.
291     DT->changeImmediateDominator(OrigHeader, OrigLatch);
292   }
293   
294   // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
295   // thus is not a preheader anymore.  Split the edge to form a real preheader.
296   BasicBlock *NewPH = SplitCriticalEdge(OrigPreHeader, NewHeader, this);
297   NewPH->setName(NewHeader->getName() + ".lr.ph");
298   
299   // Preserve canonical loop form, which means that 'Exit' should have only one
300   // predecessor.
301   SplitCriticalEdge(L->getLoopLatch(), Exit, this);
302   
303   assert(L->getLoopPreheader() == NewPH &&
304          "Invalid loop preheader after loop rotation");
305   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
306
307   // Now that the CFG and DomTree are in a consistent state again, merge the
308   // OrigHeader block into OrigLatch.  We know that they are joined by an
309   // unconditional branch.  This is just a cleanup so the emitted code isn't
310   // too gross.
311   bool DidIt = MergeBlockIntoPredecessor(OrigHeader, this);
312   assert(DidIt && "Block merge failed??"); (void)DidIt;
313   
314   ++NumRotated;
315   return true;
316 }
317