split ssa updating code out to its own helper function. Don't bother
[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 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
84 /// old header into the preheader.  If there were uses of the values produced by
85 /// these instruction that were outside of the loop, we have to insert PHI nodes
86 /// to merge the two values.  Do this now.
87 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
88                                             BasicBlock *OrigPreheader,
89                                             ValueToValueMapTy &ValueMap) {
90   // Remove PHI node entries that are no longer live.
91   BasicBlock::iterator I, E = OrigHeader->end();
92   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
93     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
94     
95   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
96   // as necessary.
97   SSAUpdater SSA;
98   for (I = OrigHeader->begin(); I != E; ++I) {
99     Value *OrigHeaderVal = I;
100     
101     // If there are no uses of the value (e.g. because it returns void), there
102     // is nothing to rewrite.
103     if (OrigHeaderVal->use_empty())
104       continue;
105     
106     Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
107
108     // The value now exits in two versions: the initial value in the preheader
109     // and the loop "next" value in the original header.
110     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
111     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
112     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
113     
114     // Visit each use of the OrigHeader instruction.
115     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
116          UE = OrigHeaderVal->use_end(); UI != UE; ) {
117       // Grab the use before incrementing the iterator.
118       Use &U = UI.getUse();
119       
120       // Increment the iterator before removing the use from the list.
121       ++UI;
122       
123       // SSAUpdater can't handle a non-PHI use in the same block as an
124       // earlier def. We can easily handle those cases manually.
125       Instruction *UserInst = cast<Instruction>(U.getUser());
126       if (!isa<PHINode>(UserInst)) {
127         BasicBlock *UserBB = UserInst->getParent();
128         
129         // The original users in the OrigHeader are already using the
130         // original definitions.
131         if (UserBB == OrigHeader)
132           continue;
133         
134         // Users in the OrigPreHeader need to use the value to which the
135         // original definitions are mapped.
136         if (UserBB == OrigPreheader) {
137           U = OrigPreHeaderVal;
138           continue;
139         }
140       }
141       
142       // Anything else can be handled by SSAUpdater.
143       SSA.RewriteUse(U);
144     }
145   }
146 }  
147
148 /// Rotate loop LP. Return true if the loop is rotated.
149 bool LoopRotate::rotateLoop(Loop *L) {
150   // If the loop has only one block then there is not much to rotate.
151   if (L->getBlocks().size() == 1)
152     return false;
153   
154   BasicBlock *OrigHeader = L->getHeader();
155   
156   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
157   if (BI == 0 || BI->isUnconditional())
158     return false;
159   
160   // If the loop header is not one of the loop exiting blocks then
161   // either this loop is already rotated or it is not
162   // suitable for loop rotation transformations.
163   if (!L->isLoopExiting(OrigHeader))
164     return false;
165
166   // Updating PHInodes in loops with multiple exits adds complexity. 
167   // Keep it simple, and restrict loop rotation to loops with one exit only.
168   // In future, lift this restriction and support for multiple exits if
169   // required.
170   SmallVector<BasicBlock*, 8> ExitBlocks;
171   L->getExitBlocks(ExitBlocks);
172   if (ExitBlocks.size() > 1)
173     return false;
174
175   // Check size of original header and reject loop if it is very big.
176   {
177     CodeMetrics Metrics;
178     Metrics.analyzeBasicBlock(OrigHeader);
179     if (Metrics.NumInsts > MAX_HEADER_SIZE)
180       return false;
181   }
182
183   // Now, this loop is suitable for rotation.
184   BasicBlock *OrigPreheader = L->getLoopPreheader();
185   BasicBlock *OrigLatch = L->getLoopLatch();
186   assert(OrigPreheader && OrigLatch && "Loop not in canonical form?");
187
188   // Anything ScalarEvolution may know about this loop or the PHI nodes
189   // in its header will soon be invalidated.
190   if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
191     SE->forgetLoop(L);
192
193   // Find new Loop header. NewHeader is a Header's one and only successor
194   // that is inside loop.  Header's other successor is outside the
195   // loop.  Otherwise loop is not suitable for rotation.
196   BasicBlock *Exit = BI->getSuccessor(0);
197   BasicBlock *NewHeader = BI->getSuccessor(1);
198   if (L->contains(Exit))
199     std::swap(Exit, NewHeader);
200   assert(NewHeader && "Unable to determine new loop header");
201   assert(L->contains(NewHeader) && !L->contains(Exit) && 
202          "Unable to determine loop header and exit blocks");
203   
204   // This code assumes that the new header has exactly one predecessor.
205   // Remove any single-entry PHI nodes in it.
206   assert(NewHeader->getSinglePredecessor() &&
207          "New header doesn't have one pred!");
208   FoldSingleEntryPHINodes(NewHeader);
209
210   // Begin by walking OrigHeader and populating ValueMap with an entry for
211   // each Instruction.
212   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
213   ValueToValueMapTy ValueMap;
214
215   // For PHI nodes, the value available in OldPreHeader is just the
216   // incoming value from OldPreHeader.
217   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
218     ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
219
220   // For the rest of the instructions, either hoist to the OrigPreheader if
221   // possible or create a clone in the OldPreHeader if not.
222   TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
223   while (I != E) {
224     Instruction *Inst = I++;
225     
226     // If the instruction's operands are invariant and it doesn't read or write
227     // memory, then it is safe to hoist.  Doing this doesn't change the order of
228     // execution in the preheader, but does prevent the instruction from
229     // executing in each iteration of the loop.  This means it is safe to hoist
230     // something that might trap, but isn't safe to hoist something that reads
231     // memory (without proving that the loop doesn't write).
232     if (L->hasLoopInvariantOperands(Inst) &&
233         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
234         !isa<TerminatorInst>(Inst)) {
235       Inst->moveBefore(LoopEntryBranch);
236       continue;
237     }
238     
239     // Otherwise, create a duplicate of the instruction.
240     Instruction *C = Inst->clone();
241     
242     // Eagerly remap the operands of the instruction.
243     RemapInstruction(C, ValueMap,
244                      RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
245     
246     // With the operands remapped, see if the instruction constant folds or is
247     // otherwise simplifyable.  This commonly occurs because the entry from PHI
248     // nodes allows icmps and other instructions to fold.
249     Value *V = SimplifyInstruction(C);
250     if (V && LI->replacementPreservesLCSSAForm(C, V)) {
251       // If so, then delete the temporary instruction and stick the folded value
252       // in the map.
253       delete C;
254       ValueMap[Inst] = V;
255     } else {
256       // Otherwise, stick the new instruction into the new block!
257       C->setName(Inst->getName());
258       C->insertBefore(LoopEntryBranch);
259       ValueMap[Inst] = C;
260     }
261   }
262
263   // Along with all the other instructions, we just cloned OrigHeader's
264   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
265   // successors by duplicating their incoming values for OrigHeader.
266   TerminatorInst *TI = OrigHeader->getTerminator();
267   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
268     for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
269          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
270       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
271
272   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
273   // OrigPreHeader's old terminator (the original branch into the loop), and
274   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
275   LoopEntryBranch->eraseFromParent();
276
277   // If there were any uses of instructions in the duplicated block outside the
278   // loop, update them, inserting PHI nodes as required
279   RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
280
281   // NewHeader is now the header of the loop.
282   L->moveToHeader(NewHeader);
283   assert(L->getHeader() == NewHeader && "Latch block is our new header");
284
285   // Update DominatorTree to reflect the CFG change we just made.  Then split
286   // edges as necessary to preserve LoopSimplify form.
287   if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
288     // Since OrigPreheader now has the conditional branch to Exit block, it is
289     // the dominator of Exit.
290     DT->changeImmediateDominator(Exit, OrigPreheader);
291     DT->changeImmediateDominator(NewHeader, OrigPreheader);
292     
293     // Update OrigHeader to be dominated by the new header block.
294     DT->changeImmediateDominator(OrigHeader, OrigLatch);
295   }
296   
297   // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
298   // thus is not a preheader anymore.  Split the edge to form a real preheader.
299   BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
300   NewPH->setName(NewHeader->getName() + ".lr.ph");
301   
302   // Preserve canonical loop form, which means that 'Exit' should have only one
303   // predecessor.
304   BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
305   ExitSplit->moveBefore(Exit);
306   
307   assert(L->getLoopPreheader() == NewPH &&
308          "Invalid loop preheader after loop rotation");
309   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
310
311   // Now that the CFG and DomTree are in a consistent state again, merge the
312   // OrigHeader block into OrigLatch.  We know that they are joined by an
313   // unconditional branch.  This is just a cleanup so the emitted code isn't
314   // too gross.
315   bool DidIt = MergeBlockIntoPredecessor(OrigHeader, this);
316   assert(DidIt && "Block merge failed??"); (void)DidIt;
317   
318   ++NumRotated;
319   return true;
320 }
321