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