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