Unbreak build with gcc 4.3: provide missed includes and silence most annoying warnings.
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnroll.cpp
1 //===-- LoopUnroll.cpp - Loop unroller 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 pass implements a simple loop unroller.  It works best when loops have
11 // been canonicalized by the -indvars pass, allowing it to determine the trip
12 // counts of loops easily.
13 //
14 // This pass will multi-block loops only if they contain no non-unrolled 
15 // subloops.  The process of unrolling can produce extraneous basic blocks 
16 // linked with unconditional branches.  This will be corrected in the future.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "loop-unroll"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/IntrinsicInst.h"
39 #include <algorithm>
40 #include <climits>
41 #include <cstdio>
42 using namespace llvm;
43
44 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
45 STATISTIC(NumUnrolled,    "Number of loops unrolled (completely or otherwise)");
46
47 namespace {
48   cl::opt<unsigned>
49   UnrollThreshold
50     ("unroll-threshold", cl::init(100), cl::Hidden,
51      cl::desc("The cut-off point for automatic loop unrolling"));
52
53   cl::opt<unsigned>
54   UnrollCount
55     ("unroll-count", cl::init(0), cl::Hidden,
56      cl::desc("Use this unroll count for all loops, for testing purposes"));
57
58   class VISIBILITY_HIDDEN LoopUnroll : public LoopPass {
59     LoopInfo *LI;  // The current loop information
60   public:
61     static char ID; // Pass ID, replacement for typeid
62     LoopUnroll() : LoopPass((intptr_t)&ID) {}
63
64     /// A magic value for use with the Threshold parameter to indicate
65     /// that the loop unroll should be performed regardless of how much
66     /// code expansion would result.
67     static const unsigned NoThreshold = UINT_MAX;
68
69     bool runOnLoop(Loop *L, LPPassManager &LPM);
70     bool unrollLoop(Loop *L, unsigned Count, unsigned Threshold);
71     BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB);
72
73     /// This transformation requires natural loop information & requires that
74     /// loop preheaders be inserted into the CFG...
75     ///
76     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77       AU.addRequiredID(LoopSimplifyID);
78       AU.addRequiredID(LCSSAID);
79       AU.addRequired<LoopInfo>();
80       AU.addPreservedID(LCSSAID);
81       AU.addPreserved<LoopInfo>();
82     }
83   };
84   char LoopUnroll::ID = 0;
85   RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
86 }
87
88 LoopPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
89
90 /// ApproximateLoopSize - Approximate the size of the loop.
91 static unsigned ApproximateLoopSize(const Loop *L) {
92   unsigned Size = 0;
93   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
94     BasicBlock *BB = L->getBlocks()[i];
95     Instruction *Term = BB->getTerminator();
96     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
97       if (isa<PHINode>(I) && BB == L->getHeader()) {
98         // Ignore PHI nodes in the header.
99       } else if (I->hasOneUse() && I->use_back() == Term) {
100         // Ignore instructions only used by the loop terminator.
101       } else if (isa<DbgInfoIntrinsic>(I)) {
102         // Ignore debug instructions
103       } else {
104         ++Size;
105       }
106
107       // TODO: Ignore expressions derived from PHI and constants if inval of phi
108       // is a constant, or if operation is associative.  This will get induction
109       // variables.
110     }
111   }
112
113   return Size;
114 }
115
116 // RemapInstruction - Convert the instruction operands from referencing the
117 // current values into those specified by ValueMap.
118 //
119 static inline void RemapInstruction(Instruction *I,
120                                     DenseMap<const Value *, Value*> &ValueMap) {
121   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
122     Value *Op = I->getOperand(op);
123     DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
124     if (It != ValueMap.end()) Op = It->second;
125     I->setOperand(op, Op);
126   }
127 }
128
129 // FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
130 // only has one predecessor, and that predecessor only has one successor.
131 // Returns the new combined block.
132 BasicBlock *LoopUnroll::FoldBlockIntoPredecessor(BasicBlock *BB) {
133   // Merge basic blocks into their predecessor if there is only one distinct
134   // pred, and if there is only one distinct successor of the predecessor, and
135   // if there are no PHI nodes.
136   //
137   BasicBlock *OnlyPred = BB->getSinglePredecessor();
138   if (!OnlyPred) return 0;
139
140   if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
141     return 0;
142
143   DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
144
145   // Resolve any PHI nodes at the start of the block.  They are all
146   // guaranteed to have exactly one entry if they exist, unless there are
147   // multiple duplicate (but guaranteed to be equal) entries for the
148   // incoming edges.  This occurs when there are multiple edges from
149   // OnlyPred to OnlySucc.
150   //
151   while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
152     PN->replaceAllUsesWith(PN->getIncomingValue(0));
153     BB->getInstList().pop_front();  // Delete the phi node...
154   }
155
156   // Delete the unconditional branch from the predecessor...
157   OnlyPred->getInstList().pop_back();
158
159   // Move all definitions in the successor to the predecessor...
160   OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
161
162   // Make all PHI nodes that referred to BB now refer to Pred as their
163   // source...
164   BB->replaceAllUsesWith(OnlyPred);
165
166   std::string OldName = BB->getName();
167
168   // Erase basic block from the function...
169   LI->removeBlock(BB);
170   BB->eraseFromParent();
171
172   // Inherit predecessor's name if it exists...
173   if (!OldName.empty() && !OnlyPred->hasName())
174     OnlyPred->setName(OldName);
175
176   return OnlyPred;
177 }
178
179 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
180   LI = &getAnalysis<LoopInfo>();
181
182   // Unroll the loop.
183   if (!unrollLoop(L, UnrollCount, UnrollThreshold))
184     return false;
185
186   // Update the loop information for this loop.
187   // If we completely unrolled the loop, remove it from the parent.
188   if (L->getNumBackEdges() == 0)
189     LPM.deleteLoopFromQueue(L);
190
191   return true;
192 }
193
194 /// Unroll the given loop by UnrollCount, or by a heuristically-determined
195 /// value if Count is zero. If Threshold is not NoThreshold, it is a value
196 /// to limit code size expansion. If the loop size would expand beyond the
197 /// threshold value, unrolling is suppressed. The return value is true if
198 /// any transformations are performed.
199 ///
200 bool LoopUnroll::unrollLoop(Loop *L, unsigned Count, unsigned Threshold) {
201   assert(L->isLCSSAForm());
202
203   BasicBlock *Header = L->getHeader();
204   BasicBlock *LatchBlock = L->getLoopLatch();
205   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
206
207   DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
208        << "] Loop %" << Header->getName() << "\n";
209
210   if (!BI || BI->isUnconditional()) {
211     // The loop-rotate pass can be helpful to avoid this in many cases.
212     DOUT << "  Can't unroll; loop not terminated by a conditional branch.\n";
213     return false;
214   }
215
216   // Determine the trip count and/or trip multiple. A TripCount value of zero
217   // is used to mean an unknown trip count. The TripMultiple value is the
218   // greatest known integer multiple of the trip count.
219   unsigned TripCount = 0;
220   unsigned TripMultiple = 1;
221   if (Value *TripCountValue = L->getTripCount()) {
222     if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCountValue)) {
223       // Guard against huge trip counts. This also guards against assertions in
224       // APInt from the use of getZExtValue, below.
225       if (TripCountC->getValue().getActiveBits() <= 32) {
226         TripCount = (unsigned)TripCountC->getZExtValue();
227       }
228     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCountValue)) {
229       switch (BO->getOpcode()) {
230       case BinaryOperator::Mul:
231         if (ConstantInt *MultipleC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
232           if (MultipleC->getValue().getActiveBits() <= 32) {
233             TripMultiple = (unsigned)MultipleC->getZExtValue();
234           }
235         }
236         break;
237       default: break;
238       }
239     }
240   }
241   if (TripCount != 0)
242     DOUT << "  Trip Count = " << TripCount << "\n";
243   if (TripMultiple != 1)
244     DOUT << "  Trip Multiple = " << TripMultiple << "\n";
245
246   // Automatically select an unroll count.
247   if (Count == 0) {
248     // Conservative heuristic: if we know the trip count, see if we can
249     // completely unroll (subject to the threshold, checked below); otherwise
250     // don't unroll.
251     if (TripCount != 0) {
252       Count = TripCount;
253     } else {
254       return false;
255     }
256   }
257
258   // Effectively "DCE" unrolled iterations that are beyond the tripcount
259   // and will never be executed.
260   if (TripCount != 0 && Count > TripCount)
261     Count = TripCount;
262
263   assert(Count > 0);
264   assert(TripMultiple > 0);
265   assert(TripCount == 0 || TripCount % TripMultiple == 0);
266
267   // Enforce the threshold.
268   if (Threshold != NoThreshold) {
269     unsigned LoopSize = ApproximateLoopSize(L);
270     DOUT << "  Loop Size = " << LoopSize << "\n";
271     uint64_t Size = (uint64_t)LoopSize*Count;
272     if (TripCount != 1 && Size > Threshold) {
273       DOUT << "  TOO LARGE TO UNROLL: "
274            << Size << ">" << Threshold << "\n";
275       return false;
276     }
277   }
278
279   // Are we eliminating the loop control altogether?
280   bool CompletelyUnroll = Count == TripCount;
281
282   // If we know the trip count, we know the multiple...
283   unsigned BreakoutTrip = 0;
284   if (TripCount != 0) {
285     BreakoutTrip = TripCount % Count;
286     TripMultiple = 0;
287   } else {
288     // Figure out what multiple to use.
289     BreakoutTrip = TripMultiple =
290       (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
291   }
292
293   if (CompletelyUnroll) {
294     DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
295          << " with trip count " << TripCount << "!\n";
296   } else {
297     DOUT << "UNROLLING loop %" << Header->getName()
298          << " by " << Count;
299     if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
300       DOUT << " with a breakout at trip " << BreakoutTrip;
301     } else if (TripMultiple != 1) {
302       DOUT << " with " << TripMultiple << " trips per branch";
303     }
304     DOUT << "!\n";
305   }
306
307   std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
308
309   bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
310   BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
311
312   // For the first iteration of the loop, we should use the precloned values for
313   // PHI nodes.  Insert associations now.
314   typedef DenseMap<const Value*, Value*> ValueMapTy;
315   ValueMapTy LastValueMap;
316   std::vector<PHINode*> OrigPHINode;
317   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
318     PHINode *PN = cast<PHINode>(I);
319     OrigPHINode.push_back(PN);
320     if (Instruction *I = 
321                 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
322       if (L->contains(I->getParent()))
323         LastValueMap[I] = I;
324   }
325
326   std::vector<BasicBlock*> Headers;
327   std::vector<BasicBlock*> Latches;
328   Headers.push_back(Header);
329   Latches.push_back(LatchBlock);
330
331   for (unsigned It = 1; It != Count; ++It) {
332     char SuffixBuffer[100];
333     sprintf(SuffixBuffer, ".%d", It);
334     
335     std::vector<BasicBlock*> NewBlocks;
336     
337     for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
338          E = LoopBlocks.end(); BB != E; ++BB) {
339       ValueMapTy ValueMap;
340       BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
341       Header->getParent()->getBasicBlockList().push_back(New);
342
343       // Loop over all of the PHI nodes in the block, changing them to use the
344       // incoming values from the previous block.
345       if (*BB == Header)
346         for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
347           PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
348           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
349           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
350             if (It > 1 && L->contains(InValI->getParent()))
351               InVal = LastValueMap[InValI];
352           ValueMap[OrigPHINode[i]] = InVal;
353           New->getInstList().erase(NewPHI);
354         }
355
356       // Update our running map of newest clones
357       LastValueMap[*BB] = New;
358       for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
359            VI != VE; ++VI)
360         LastValueMap[VI->first] = VI->second;
361
362       L->addBasicBlockToLoop(New, LI->getBase());
363
364       // Add phi entries for newly created values to all exit blocks except
365       // the successor of the latch block.  The successor of the exit block will
366       // be updated specially after unrolling all the way.
367       if (*BB != LatchBlock)
368         for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
369              UI != UE;) {
370           Instruction *UseInst = cast<Instruction>(*UI);
371           ++UI;
372           if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
373             PHINode *phi = cast<PHINode>(UseInst);
374             Value *Incoming = phi->getIncomingValueForBlock(*BB);
375             phi->addIncoming(Incoming, New);
376           }
377         }
378
379       // Keep track of new headers and latches as we create them, so that
380       // we can insert the proper branches later.
381       if (*BB == Header)
382         Headers.push_back(New);
383       if (*BB == LatchBlock) {
384         Latches.push_back(New);
385
386         // Also, clear out the new latch's back edge so that it doesn't look
387         // like a new loop, so that it's amenable to being merged with adjacent
388         // blocks later on.
389         TerminatorInst *Term = New->getTerminator();
390         assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
391         assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
392         Term->setSuccessor(!ContinueOnTrue, NULL);
393       }
394
395       NewBlocks.push_back(New);
396     }
397     
398     // Remap all instructions in the most recent iteration
399     for (unsigned i = 0; i < NewBlocks.size(); ++i)
400       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
401            E = NewBlocks[i]->end(); I != E; ++I)
402         RemapInstruction(I, LastValueMap);
403   }
404   
405   // The latch block exits the loop.  If there are any PHI nodes in the
406   // successor blocks, update them to use the appropriate values computed as the
407   // last iteration of the loop.
408   if (Count != 1) {
409     SmallPtrSet<PHINode*, 8> Users;
410     for (Value::use_iterator UI = LatchBlock->use_begin(),
411          UE = LatchBlock->use_end(); UI != UE; ++UI)
412       if (PHINode *phi = dyn_cast<PHINode>(*UI))
413         Users.insert(phi);
414     
415     BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
416     for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
417          SI != SE; ++SI) {
418       PHINode *PN = *SI;
419       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
420       // If this value was defined in the loop, take the value defined by the
421       // last iteration of the loop.
422       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
423         if (L->contains(InValI->getParent()))
424           InVal = LastValueMap[InVal];
425       }
426       PN->addIncoming(InVal, LastIterationBB);
427     }
428   }
429
430   // Now, if we're doing complete unrolling, loop over the PHI nodes in the
431   // original block, setting them to their incoming values.
432   if (CompletelyUnroll) {
433     BasicBlock *Preheader = L->getLoopPreheader();
434     for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
435       PHINode *PN = OrigPHINode[i];
436       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
437       Header->getInstList().erase(PN);
438     }
439   }
440
441   // Now that all the basic blocks for the unrolled iterations are in place,
442   // set up the branches to connect them.
443   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
444     // The original branch was replicated in each unrolled iteration.
445     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
446
447     // The branch destination.
448     unsigned j = (i + 1) % e;
449     BasicBlock *Dest = Headers[j];
450     bool NeedConditional = true;
451
452     // For a complete unroll, make the last iteration end with a branch
453     // to the exit block.
454     if (CompletelyUnroll && j == 0) {
455       Dest = LoopExit;
456       NeedConditional = false;
457     }
458
459     // If we know the trip count or a multiple of it, we can safely use an
460     // unconditional branch for some iterations.
461     if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
462       NeedConditional = false;
463     }
464
465     if (NeedConditional) {
466       // Update the conditional branch's successor for the following
467       // iteration.
468       Term->setSuccessor(!ContinueOnTrue, Dest);
469     } else {
470       Term->setUnconditionalDest(Dest);
471       // Merge adjacent basic blocks, if possible.
472       if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest)) {
473         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
474         std::replace(Headers.begin(), Headers.end(), Dest, Fold);
475       }
476     }
477   }
478   
479   // At this point, the code is well formed.  We now do a quick sweep over the
480   // inserted code, doing constant propagation and dead code elimination as we
481   // go.
482   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
483   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
484        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
485     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
486       Instruction *Inst = I++;
487
488       if (isInstructionTriviallyDead(Inst))
489         (*BB)->getInstList().erase(Inst);
490       else if (Constant *C = ConstantFoldInstruction(Inst)) {
491         Inst->replaceAllUsesWith(C);
492         (*BB)->getInstList().erase(Inst);
493       }
494     }
495
496   NumCompletelyUnrolled += CompletelyUnroll;
497   ++NumUnrolled;
498   return true;
499 }