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