Change how PHINodes store their operands.
[oota-llvm.git] / lib / Transforms / Utils / LoopUnroll.cpp
1 //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
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 some loop unrolling utilities. It does not define any
11 // actual pass or policy, but provides a single function to perform loop
12 // unrolling.
13 //
14 // It works best when loops have been canonicalized by the -indvars pass,
15 // allowing it to determine the trip counts of loops easily.
16 //
17 // The process of unrolling can produce extraneous basic blocks linked with
18 // unconditional branches.  This will be corrected in the future.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "loop-unroll"
23 #include "llvm/Transforms/Utils/UnrollLoop.h"
24 #include "llvm/BasicBlock.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32 #include "llvm/Transforms/Utils/Cloning.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 using namespace llvm;
35
36 // TODO: Should these be here or in LoopUnroll?
37 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
38 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
39
40 /// RemapInstruction - Convert the instruction operands from referencing the
41 /// current values into those specified by VMap.
42 static inline void RemapInstruction(Instruction *I,
43                                     ValueToValueMapTy &VMap) {
44   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
45     Value *Op = I->getOperand(op);
46     ValueToValueMapTy::iterator It = VMap.find(Op);
47     if (It != VMap.end())
48       I->setOperand(op, It->second);
49   }
50
51   if (PHINode *PN = dyn_cast<PHINode>(I)) {
52     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
53       ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
54       if (It != VMap.end())
55         PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
56     }
57   }
58 }
59
60 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
61 /// only has one predecessor, and that predecessor only has one successor.
62 /// The LoopInfo Analysis that is passed will be kept consistent.
63 /// Returns the new combined block.
64 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI) {
65   // Merge basic blocks into their predecessor if there is only one distinct
66   // pred, and if there is only one distinct successor of the predecessor, and
67   // if there are no PHI nodes.
68   BasicBlock *OnlyPred = BB->getSinglePredecessor();
69   if (!OnlyPred) return 0;
70
71   if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
72     return 0;
73
74   DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
75
76   // Resolve any PHI nodes at the start of the block.  They are all
77   // guaranteed to have exactly one entry if they exist, unless there are
78   // multiple duplicate (but guaranteed to be equal) entries for the
79   // incoming edges.  This occurs when there are multiple edges from
80   // OnlyPred to OnlySucc.
81   FoldSingleEntryPHINodes(BB);
82
83   // Delete the unconditional branch from the predecessor...
84   OnlyPred->getInstList().pop_back();
85
86   // Make all PHI nodes that referred to BB now refer to Pred as their
87   // source...
88   BB->replaceAllUsesWith(OnlyPred);
89
90   // Move all definitions in the successor to the predecessor...
91   OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
92
93   std::string OldName = BB->getName();
94
95   // Erase basic block from the function...
96   LI->removeBlock(BB);
97   BB->eraseFromParent();
98
99   // Inherit predecessor's name if it exists...
100   if (!OldName.empty() && !OnlyPred->hasName())
101     OnlyPred->setName(OldName);
102
103   return OnlyPred;
104 }
105
106 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
107 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
108 /// can only fail when the loop's latch block is not terminated by a conditional
109 /// branch instruction. However, if the trip count (and multiple) are not known,
110 /// loop unrolling will mostly produce more code that is no faster.
111 ///
112 /// The LoopInfo Analysis that is passed will be kept consistent.
113 ///
114 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
115 /// removed from the LoopPassManager as well. LPM can also be NULL.
116 bool llvm::UnrollLoop(Loop *L, unsigned Count,
117                       LoopInfo *LI, LPPassManager *LPM) {
118   BasicBlock *Preheader = L->getLoopPreheader();
119   if (!Preheader) {
120     DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
121     return false;
122   }
123
124   BasicBlock *LatchBlock = L->getLoopLatch();
125   if (!LatchBlock) {
126     DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
127     return false;
128   }
129
130   BasicBlock *Header = L->getHeader();
131   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
132   
133   if (!BI || BI->isUnconditional()) {
134     // The loop-rotate pass can be helpful to avoid this in many cases.
135     DEBUG(dbgs() <<
136              "  Can't unroll; loop not terminated by a conditional branch.\n");
137     return false;
138   }
139   
140   if (Header->hasAddressTaken()) {
141     // The loop-rotate pass can be helpful to avoid this in many cases.
142     DEBUG(dbgs() <<
143           "  Won't unroll loop: address of header block is taken.\n");
144     return false;
145   }
146
147   // Notify ScalarEvolution that the loop will be substantially changed,
148   // if not outright eliminated.
149   if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>())
150     SE->forgetLoop(L);
151
152   // Find trip count
153   unsigned TripCount = L->getSmallConstantTripCount();
154   // Find trip multiple if count is not available
155   unsigned TripMultiple = 1;
156   if (TripCount == 0)
157     TripMultiple = L->getSmallConstantTripMultiple();
158
159   if (TripCount != 0)
160     DEBUG(dbgs() << "  Trip Count = " << TripCount << "\n");
161   if (TripMultiple != 1)
162     DEBUG(dbgs() << "  Trip Multiple = " << TripMultiple << "\n");
163
164   // Effectively "DCE" unrolled iterations that are beyond the tripcount
165   // and will never be executed.
166   if (TripCount != 0 && Count > TripCount)
167     Count = TripCount;
168
169   assert(Count > 0);
170   assert(TripMultiple > 0);
171   assert(TripCount == 0 || TripCount % TripMultiple == 0);
172
173   // Are we eliminating the loop control altogether?
174   bool CompletelyUnroll = Count == TripCount;
175
176   // If we know the trip count, we know the multiple...
177   unsigned BreakoutTrip = 0;
178   if (TripCount != 0) {
179     BreakoutTrip = TripCount % Count;
180     TripMultiple = 0;
181   } else {
182     // Figure out what multiple to use.
183     BreakoutTrip = TripMultiple =
184       (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
185   }
186
187   if (CompletelyUnroll) {
188     DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
189           << " with trip count " << TripCount << "!\n");
190   } else {
191     DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
192           << " by " << Count);
193     if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
194       DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
195     } else if (TripMultiple != 1) {
196       DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
197     }
198     DEBUG(dbgs() << "!\n");
199   }
200
201   std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
202
203   bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
204   BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
205
206   // For the first iteration of the loop, we should use the precloned values for
207   // PHI nodes.  Insert associations now.
208   ValueToValueMapTy LastValueMap;
209   std::vector<PHINode*> OrigPHINode;
210   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
211     PHINode *PN = cast<PHINode>(I);
212     OrigPHINode.push_back(PN);
213     if (Instruction *I = 
214                 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
215       if (L->contains(I))
216         LastValueMap[I] = I;
217   }
218
219   std::vector<BasicBlock*> Headers;
220   std::vector<BasicBlock*> Latches;
221   Headers.push_back(Header);
222   Latches.push_back(LatchBlock);
223
224   for (unsigned It = 1; It != Count; ++It) {
225     std::vector<BasicBlock*> NewBlocks;
226     
227     for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
228          E = LoopBlocks.end(); BB != E; ++BB) {
229       ValueToValueMapTy VMap;
230       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
231       Header->getParent()->getBasicBlockList().push_back(New);
232
233       // Loop over all of the PHI nodes in the block, changing them to use the
234       // incoming values from the previous block.
235       if (*BB == Header)
236         for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
237           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
238           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
239           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
240             if (It > 1 && L->contains(InValI))
241               InVal = LastValueMap[InValI];
242           VMap[OrigPHINode[i]] = InVal;
243           New->getInstList().erase(NewPHI);
244         }
245
246       // Update our running map of newest clones
247       LastValueMap[*BB] = New;
248       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
249            VI != VE; ++VI)
250         LastValueMap[VI->first] = VI->second;
251
252       L->addBasicBlockToLoop(New, LI->getBase());
253
254       // Add phi entries for newly created values to all exit blocks except
255       // the successor of the latch block.  The successor of the exit block will
256       // be updated specially after unrolling all the way.
257       if (*BB != LatchBlock)
258         for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB); SI != SE;
259              ++SI)
260           if (!L->contains(*SI))
261             for (BasicBlock::iterator BBI = (*SI)->begin(), BBE = (*SI)->end();
262                  PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
263               Value *Incoming = phi->getIncomingValueForBlock(*BB);
264               phi->addIncoming(Incoming, New);
265             }
266
267       // Keep track of new headers and latches as we create them, so that
268       // we can insert the proper branches later.
269       if (*BB == Header)
270         Headers.push_back(New);
271       if (*BB == LatchBlock) {
272         Latches.push_back(New);
273
274         // Also, clear out the new latch's back edge so that it doesn't look
275         // like a new loop, so that it's amenable to being merged with adjacent
276         // blocks later on.
277         TerminatorInst *Term = New->getTerminator();
278         assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
279         assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
280         Term->setSuccessor(!ContinueOnTrue, NULL);
281       }
282
283       NewBlocks.push_back(New);
284     }
285     
286     // Remap all instructions in the most recent iteration
287     for (unsigned i = 0; i < NewBlocks.size(); ++i)
288       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
289            E = NewBlocks[i]->end(); I != E; ++I)
290         ::RemapInstruction(I, LastValueMap);
291   }
292   
293   // The latch block exits the loop.  If there are any PHI nodes in the
294   // successor blocks, update them to use the appropriate values computed as the
295   // last iteration of the loop.
296   if (Count != 1) {
297     BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
298     for (succ_iterator SI = succ_begin(LatchBlock), SE = succ_end(LatchBlock);
299          SI != SE; ++SI) {
300       for (BasicBlock::iterator BBI = (*SI)->begin(), BBE = (*SI)->end();
301            PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
302         Value *InVal = PN->removeIncomingValue(LatchBlock, false);
303         // If this value was defined in the loop, take the value defined by the
304         // last iteration of the loop.
305         if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
306           if (L->contains(InValI))
307             InVal = LastValueMap[InVal];
308         }
309         PN->addIncoming(InVal, LastIterationBB);
310       }
311     }
312   }
313
314   // Now, if we're doing complete unrolling, loop over the PHI nodes in the
315   // original block, setting them to their incoming values.
316   if (CompletelyUnroll) {
317     BasicBlock *Preheader = L->getLoopPreheader();
318     for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
319       PHINode *PN = OrigPHINode[i];
320       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
321       Header->getInstList().erase(PN);
322     }
323   }
324
325   // Now that all the basic blocks for the unrolled iterations are in place,
326   // set up the branches to connect them.
327   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
328     // The original branch was replicated in each unrolled iteration.
329     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
330
331     // The branch destination.
332     unsigned j = (i + 1) % e;
333     BasicBlock *Dest = Headers[j];
334     bool NeedConditional = true;
335
336     // For a complete unroll, make the last iteration end with a branch
337     // to the exit block.
338     if (CompletelyUnroll && j == 0) {
339       Dest = LoopExit;
340       NeedConditional = false;
341     }
342
343     // If we know the trip count or a multiple of it, we can safely use an
344     // unconditional branch for some iterations.
345     if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
346       NeedConditional = false;
347     }
348
349     if (NeedConditional) {
350       // Update the conditional branch's successor for the following
351       // iteration.
352       Term->setSuccessor(!ContinueOnTrue, Dest);
353     } else {
354       // Replace the conditional branch with an unconditional one.
355       BranchInst::Create(Dest, Term);
356       Term->eraseFromParent();
357     }
358   }
359
360   // Merge adjacent basic blocks, if possible.
361   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
362     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
363     if (Term->isUnconditional()) {
364       BasicBlock *Dest = Term->getSuccessor(0);
365       if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI))
366         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
367     }
368   }
369   
370   // At this point, the code is well formed.  We now do a quick sweep over the
371   // inserted code, doing constant propagation and dead code elimination as we
372   // go.
373   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
374   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
375        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
376     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
377       Instruction *Inst = I++;
378
379       if (isInstructionTriviallyDead(Inst))
380         (*BB)->getInstList().erase(Inst);
381       else if (Value *V = SimplifyInstruction(Inst))
382         if (LI->replacementPreservesLCSSAForm(Inst, V)) {
383           Inst->replaceAllUsesWith(V);
384           (*BB)->getInstList().erase(Inst);
385         }
386     }
387
388   NumCompletelyUnrolled += CompletelyUnroll;
389   ++NumUnrolled;
390   // Remove the loop from the LoopPassManager if it's completely removed.
391   if (CompletelyUnroll && LPM != NULL)
392     LPM->deleteLoopFromQueue(L);
393
394   return true;
395 }