Eliminate tabs and trailing spaces
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnroll.cpp
1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 is currently extremely limited.  It only currently only unrolls
15 // single basic block loops that execute a constant number of times.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "loop-unroll"
20 #include "llvm/Transforms/Scalar.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/IntrinsicInst.h"
32 #include <cstdio>
33 #include <set>
34 #include <algorithm>
35
36 using namespace llvm;
37
38 namespace {
39   Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
40
41   cl::opt<unsigned>
42   UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
43                   cl::desc("The cut-off point for loop unrolling"));
44
45   class LoopUnroll : public FunctionPass {
46     LoopInfo *LI;  // The current loop information
47   public:
48     virtual bool runOnFunction(Function &F);
49     bool visitLoop(Loop *L);
50
51     /// This transformation requires natural loop information & requires that
52     /// loop preheaders be inserted into the CFG...
53     ///
54     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55       AU.addRequiredID(LoopSimplifyID);
56       AU.addRequired<LoopInfo>();
57       AU.addPreserved<LoopInfo>();
58     }
59   };
60   RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
61 }
62
63 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
64
65 bool LoopUnroll::runOnFunction(Function &F) {
66   bool Changed = false;
67   LI = &getAnalysis<LoopInfo>();
68
69   // Transform all the top-level loops.  Copy the loop list so that the child
70   // can update the loop tree if it needs to delete the loop.
71   std::vector<Loop*> SubLoops(LI->begin(), LI->end());
72   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
73     Changed |= visitLoop(SubLoops[i]);
74
75   return Changed;
76 }
77
78 /// ApproximateLoopSize - Approximate the size of the loop after it has been
79 /// unrolled.
80 static unsigned ApproximateLoopSize(const Loop *L) {
81   unsigned Size = 0;
82   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
83     BasicBlock *BB = L->getBlocks()[i];
84     Instruction *Term = BB->getTerminator();
85     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
86       if (isa<PHINode>(I) && BB == L->getHeader()) {
87         // Ignore PHI nodes in the header.
88       } else if (I->hasOneUse() && I->use_back() == Term) {
89         // Ignore instructions only used by the loop terminator.
90       } else if (DbgInfoIntrinsic *DbgI = dyn_cast<DbgInfoIntrinsic>(I)) {
91         // Ignore debug instructions
92       } else {
93         ++Size;
94       }
95
96       // TODO: Ignore expressions derived from PHI and constants if inval of phi
97       // is a constant, or if operation is associative.  This will get induction
98       // variables.
99     }
100   }
101
102   return Size;
103 }
104
105 // RemapInstruction - Convert the instruction operands from referencing the
106 // current values into those specified by ValueMap.
107 //
108 static inline void RemapInstruction(Instruction *I,
109                                     std::map<const Value *, Value*> &ValueMap) {
110   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
111     Value *Op = I->getOperand(op);
112     std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
113     if (It != ValueMap.end()) Op = It->second;
114     I->setOperand(op, Op);
115   }
116 }
117
118 bool LoopUnroll::visitLoop(Loop *L) {
119   bool Changed = false;
120
121   // Recurse through all subloops before we process this loop.  Copy the loop
122   // list so that the child can update the loop tree if it needs to delete the
123   // loop.
124   std::vector<Loop*> SubLoops(L->begin(), L->end());
125   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
126     Changed |= visitLoop(SubLoops[i]);
127
128   // We only handle single basic block loops right now.
129   if (L->getBlocks().size() != 1)
130     return Changed;
131
132   BasicBlock *BB = L->getHeader();
133   BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
134   if (BI == 0) return Changed;  // Must end in a conditional branch
135
136   ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
137   if (!TripCountC) return Changed;  // Must have constant trip count!
138
139   uint64_t TripCountFull = TripCountC->getRawValue();
140   if (TripCountFull != TripCountC->getRawValue() || TripCountFull == 0)
141     return Changed; // More than 2^32 iterations???
142
143   unsigned LoopSize = ApproximateLoopSize(L);
144   DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
145         << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
146         << " Trip Count = " << TripCountFull << " - ");
147   uint64_t Size = (uint64_t)LoopSize*TripCountFull;
148   if (Size > UnrollThreshold) {
149     DEBUG(std::cerr << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n");
150     return Changed;
151   }
152   DEBUG(std::cerr << "UNROLLING!\n");
153
154   unsigned TripCount = (unsigned)TripCountFull;
155
156   BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
157
158   // Create a new basic block to temporarily hold all of the cloned code.
159   BasicBlock *NewBlock = new BasicBlock();
160
161   // For the first iteration of the loop, we should use the precloned values for
162   // PHI nodes.  Insert associations now.
163   std::map<const Value*, Value*> LastValueMap;
164   std::vector<PHINode*> OrigPHINode;
165   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
166     PHINode *PN = cast<PHINode>(I);
167     OrigPHINode.push_back(PN);
168     if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
169       if (I->getParent() == BB)
170         LastValueMap[I] = I;
171   }
172
173   // Remove the exit branch from the loop
174   BB->getInstList().erase(BI);
175
176   assert(TripCount != 0 && "Trip count of 0 is impossible!");
177   for (unsigned It = 1; It != TripCount; ++It) {
178     char SuffixBuffer[100];
179     sprintf(SuffixBuffer, ".%d", It);
180     std::map<const Value*, Value*> ValueMap;
181     BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
182
183     // Loop over all of the PHI nodes in the block, changing them to use the
184     // incoming values from the previous block.
185     for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
186       PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
187       Value *InVal = NewPHI->getIncomingValueForBlock(BB);
188       if (Instruction *InValI = dyn_cast<Instruction>(InVal))
189         if (InValI->getParent() == BB)
190           InVal = LastValueMap[InValI];
191       ValueMap[OrigPHINode[i]] = InVal;
192       New->getInstList().erase(NewPHI);
193     }
194
195     for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
196       RemapInstruction(I, ValueMap);
197
198     // Now that all of the instructions are remapped, splice them into the end
199     // of the NewBlock.
200     NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
201     delete New;
202
203     // LastValue map now contains values from this iteration.
204     std::swap(LastValueMap, ValueMap);
205   }
206
207   // If there was more than one iteration, replace any uses of values computed
208   // in the loop with values computed during the last iteration of the loop.
209   if (TripCount != 1) {
210     std::set<User*> Users;
211     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
212       Users.insert(I->use_begin(), I->use_end());
213
214     // We don't want to reprocess entries with PHI nodes in them.  For this
215     // reason, we look at each operand of each user exactly once, performing the
216     // stubstitution exactly once.
217     for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
218          ++UI) {
219       Instruction *I = cast<Instruction>(*UI);
220       if (I->getParent() != BB && I->getParent() != NewBlock)
221         RemapInstruction(I, LastValueMap);
222     }
223   }
224
225   // Now that we cloned the block as many times as we needed, stitch the new
226   // code into the original block and delete the temporary block.
227   BB->getInstList().splice(BB->end(), NewBlock->getInstList());
228   delete NewBlock;
229
230   // Now loop over the PHI nodes in the original block, setting them to their
231   // incoming values.
232   BasicBlock *Preheader = L->getLoopPreheader();
233   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
234     PHINode *PN = OrigPHINode[i];
235     PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
236     BB->getInstList().erase(PN);
237   }
238
239   // Finally, add an unconditional branch to the block to continue into the exit
240   // block.
241   new BranchInst(LoopExit, BB);
242
243   // At this point, the code is well formed.  We now do a quick sweep over the
244   // inserted code, doing constant propagation and dead code elimination as we
245   // go.
246   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
247     Instruction *Inst = I++;
248
249     if (isInstructionTriviallyDead(Inst))
250       BB->getInstList().erase(Inst);
251     else if (Constant *C = ConstantFoldInstruction(Inst)) {
252       Inst->replaceAllUsesWith(C);
253       BB->getInstList().erase(Inst);
254     }
255   }
256
257   // Update the loop information for this loop.
258   Loop *Parent = L->getParentLoop();
259
260   // Move all of the basic blocks in the loop into the parent loop.
261   LI->changeLoopFor(BB, Parent);
262
263   // Remove the loop from the parent.
264   if (Parent)
265     delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
266   else
267     delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
268
269
270   // FIXME: Should update dominator analyses
271
272
273   // Now that everything is up-to-date that will be, we fold the loop block into
274   // the preheader and exit block, updating our analyses as we go.
275   LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
276                                  BB->getInstList().begin(),
277                                  prior(BB->getInstList().end()));
278   LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
279                                  Preheader->getInstList().begin(),
280                                  prior(Preheader->getInstList().end()));
281
282   // Make all other blocks in the program branch to LoopExit now instead of
283   // Preheader.
284   Preheader->replaceAllUsesWith(LoopExit);
285
286   Function *F = LoopExit->getParent();
287   if (Parent) {
288     // Otherwise, if this is a sub-loop, and the preheader was the loop header
289     // of the parent loop, move the exit block to be the new parent loop header.
290     if (Parent->getHeader() == Preheader) {
291       assert(Parent->contains(LoopExit) &&
292              "Exit block isn't contained in parent?");
293       Parent->moveToHeader(LoopExit);
294     }
295   } else {
296     // If the preheader was the entry block of this function, move the exit
297     // block to be the new entry of the function.
298     if (Preheader == &F->front())
299       F->getBasicBlockList().splice(F->begin(),
300                                     F->getBasicBlockList(), LoopExit);
301   }
302
303   // Remove BB and LoopExit from our analyses.
304   LI->removeBlock(Preheader);
305   LI->removeBlock(BB);
306
307   // Actually delete the blocks now.
308   F->getBasicBlockList().erase(Preheader);
309   F->getBasicBlockList().erase(BB);
310
311   ++NumUnrolled;
312   return true;
313 }