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