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