blob: 603ba6adbb577bea88019f7f83525667f313ec45 [file] [log] [blame]
Chris Lattner83bf2882004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner83bf2882004-04-18 05:20:17 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner83bf2882004-04-18 05:20:17 +00008//===----------------------------------------------------------------------===//
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//
Owen Anderson3b53c4e2006-08-24 21:28:19 +000014// 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.
Chris Lattner83bf2882004-04-18 05:20:17 +000017//
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/LoopInfo.h"
26#include "llvm/Transforms/Utils/Cloning.h"
27#include "llvm/Transforms/Utils/Local.h"
Owen Anderson59312b12006-08-28 02:09:46 +000028#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
Chris Lattner64613ea2004-11-22 17:18:36 +000033#include "llvm/IntrinsicInst.h"
Chris Lattner83bf2882004-04-18 05:20:17 +000034#include <cstdio>
Chris Lattner5864aeb2004-04-19 03:01:23 +000035#include <set>
Reid Spencer17e6e442004-10-18 14:38:48 +000036#include <algorithm>
Chris Lattner83bf2882004-04-18 05:20:17 +000037using namespace llvm;
38
Chris Lattner0e5f4992006-12-19 21:40:18 +000039STATISTIC(NumUnrolled, "Number of loops completely unrolled");
Chris Lattner83bf2882004-04-18 05:20:17 +000040
Chris Lattner0e5f4992006-12-19 21:40:18 +000041namespace {
Chris Lattner83bf2882004-04-18 05:20:17 +000042 cl::opt<unsigned>
Chris Lattnere3a55862004-04-18 18:06:14 +000043 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
Chris Lattner83bf2882004-04-18 05:20:17 +000044 cl::desc("The cut-off point for loop unrolling"));
45
46 class LoopUnroll : public FunctionPass {
47 LoopInfo *LI; // The current loop information
48 public:
49 virtual bool runOnFunction(Function &F);
50 bool visitLoop(Loop *L);
Owen Anderson59312b12006-08-28 02:09:46 +000051 BasicBlock* FoldBlockIntoPredecessor(BasicBlock* BB);
Chris Lattner83bf2882004-04-18 05:20:17 +000052
53 /// This transformation requires natural loop information & requires that
54 /// loop preheaders be inserted into the CFG...
55 ///
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner83bf2882004-04-18 05:20:17 +000057 AU.addRequiredID(LoopSimplifyID);
Owen Anderson3b53c4e2006-08-24 21:28:19 +000058 AU.addRequiredID(LCSSAID);
Chris Lattner83bf2882004-04-18 05:20:17 +000059 AU.addRequired<LoopInfo>();
Owen Anderson3b53c4e2006-08-24 21:28:19 +000060 AU.addPreservedID(LCSSAID);
Chris Lattner9c2cc462004-04-18 05:38:37 +000061 AU.addPreserved<LoopInfo>();
Chris Lattner83bf2882004-04-18 05:20:17 +000062 }
63 };
Chris Lattner7f8897f2006-08-27 22:42:52 +000064 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
Chris Lattner83bf2882004-04-18 05:20:17 +000065}
66
67FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
68
69bool LoopUnroll::runOnFunction(Function &F) {
70 bool Changed = false;
71 LI = &getAnalysis<LoopInfo>();
72
Chris Lattner9c2cc462004-04-18 05:38:37 +000073 // Transform all the top-level loops. Copy the loop list so that the child
74 // can update the loop tree if it needs to delete the loop.
75 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
76 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
77 Changed |= visitLoop(SubLoops[i]);
Chris Lattner83bf2882004-04-18 05:20:17 +000078
79 return Changed;
80}
81
82/// ApproximateLoopSize - Approximate the size of the loop after it has been
83/// unrolled.
84static unsigned ApproximateLoopSize(const Loop *L) {
85 unsigned Size = 0;
86 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
87 BasicBlock *BB = L->getBlocks()[i];
88 Instruction *Term = BB->getTerminator();
89 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
90 if (isa<PHINode>(I) && BB == L->getHeader()) {
91 // Ignore PHI nodes in the header.
92 } else if (I->hasOneUse() && I->use_back() == Term) {
93 // Ignore instructions only used by the loop terminator.
Reid Spencer3ed469c2006-11-02 20:25:50 +000094 } else if (isa<DbgInfoIntrinsic>(I)) {
Jeff Cohen9d809302005-04-23 21:38:35 +000095 // Ignore debug instructions
Chris Lattner83bf2882004-04-18 05:20:17 +000096 } else {
97 ++Size;
98 }
99
100 // TODO: Ignore expressions derived from PHI and constants if inval of phi
101 // is a constant, or if operation is associative. This will get induction
102 // variables.
103 }
104 }
105
106 return Size;
107}
108
Misha Brukmanfd939082005-04-21 23:48:37 +0000109// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner83bf2882004-04-18 05:20:17 +0000110// current values into those specified by ValueMap.
111//
Misha Brukmanfd939082005-04-21 23:48:37 +0000112static inline void RemapInstruction(Instruction *I,
Chris Lattner83bf2882004-04-18 05:20:17 +0000113 std::map<const Value *, Value*> &ValueMap) {
114 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
115 Value *Op = I->getOperand(op);
116 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
117 if (It != ValueMap.end()) Op = It->second;
118 I->setOperand(op, Op);
119 }
120}
121
Owen Anderson59312b12006-08-28 02:09:46 +0000122// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
123// only has one predecessor, and that predecessor only has one successor.
124// Returns the new combined block.
125BasicBlock* LoopUnroll::FoldBlockIntoPredecessor(BasicBlock* BB) {
126 // Merge basic blocks into their predecessor if there is only one distinct
127 // pred, and if there is only one distinct successor of the predecessor, and
128 // if there are no PHI nodes.
129 //
Owen Andersond648e142006-08-29 06:10:56 +0000130 BasicBlock *OnlyPred = BB->getSinglePredecessor();
131 if (!OnlyPred) return 0;
Owen Anderson59312b12006-08-28 02:09:46 +0000132
Owen Andersond648e142006-08-29 06:10:56 +0000133 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
134 return 0;
135
Bill Wendlingb7427032006-11-26 09:46:52 +0000136 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
Owen Andersond648e142006-08-29 06:10:56 +0000137
138 // Resolve any PHI nodes at the start of the block. They are all
139 // guaranteed to have exactly one entry if they exist, unless there are
140 // multiple duplicate (but guaranteed to be equal) entries for the
141 // incoming edges. This occurs when there are multiple edges from
142 // OnlyPred to OnlySucc.
143 //
144 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
145 PN->replaceAllUsesWith(PN->getIncomingValue(0));
146 BB->getInstList().pop_front(); // Delete the phi node...
Owen Anderson59312b12006-08-28 02:09:46 +0000147 }
148
Owen Andersond648e142006-08-29 06:10:56 +0000149 // Delete the unconditional branch from the predecessor...
150 OnlyPred->getInstList().pop_back();
Owen Anderson59312b12006-08-28 02:09:46 +0000151
Owen Andersond648e142006-08-29 06:10:56 +0000152 // Move all definitions in the successor to the predecessor...
153 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Owen Anderson59312b12006-08-28 02:09:46 +0000154
Owen Andersond648e142006-08-29 06:10:56 +0000155 // Make all PHI nodes that referred to BB now refer to Pred as their
156 // source...
157 BB->replaceAllUsesWith(OnlyPred);
Owen Anderson59312b12006-08-28 02:09:46 +0000158
Owen Andersond648e142006-08-29 06:10:56 +0000159 std::string OldName = BB->getName();
Owen Anderson59312b12006-08-28 02:09:46 +0000160
Owen Andersond648e142006-08-29 06:10:56 +0000161 // Erase basic block from the function...
162 LI->removeBlock(BB);
163 BB->eraseFromParent();
Owen Anderson59312b12006-08-28 02:09:46 +0000164
Owen Andersond648e142006-08-29 06:10:56 +0000165 // Inherit predecessors name if it exists...
166 if (!OldName.empty() && !OnlyPred->hasName())
167 OnlyPred->setName(OldName);
Owen Anderson59312b12006-08-28 02:09:46 +0000168
Owen Andersond648e142006-08-29 06:10:56 +0000169 return OnlyPred;
Owen Anderson59312b12006-08-28 02:09:46 +0000170}
171
Chris Lattner83bf2882004-04-18 05:20:17 +0000172bool LoopUnroll::visitLoop(Loop *L) {
173 bool Changed = false;
174
175 // Recurse through all subloops before we process this loop. Copy the loop
176 // list so that the child can update the loop tree if it needs to delete the
177 // loop.
178 std::vector<Loop*> SubLoops(L->begin(), L->end());
179 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
180 Changed |= visitLoop(SubLoops[i]);
181
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000182 BasicBlock* Header = L->getHeader();
183 BasicBlock* LatchBlock = L->getLoopLatch();
Chris Lattner83bf2882004-04-18 05:20:17 +0000184
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000185 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Chris Lattner83bf2882004-04-18 05:20:17 +0000186 if (BI == 0) return Changed; // Must end in a conditional branch
187
188 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
189 if (!TripCountC) return Changed; // Must have constant trip count!
190
Reid Spencerb83eb642006-10-20 07:07:24 +0000191 uint64_t TripCountFull = TripCountC->getZExtValue();
192 if (TripCountFull != TripCountC->getZExtValue() || TripCountFull == 0)
Chris Lattner83bf2882004-04-18 05:20:17 +0000193 return Changed; // More than 2^32 iterations???
194
195 unsigned LoopSize = ApproximateLoopSize(L);
Bill Wendlingb7427032006-11-26 09:46:52 +0000196 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
197 << "] Loop %" << Header->getName() << " Loop Size = "
198 << LoopSize << " Trip Count = " << TripCountFull << " - ";
Chris Lattnerd4bc5642005-01-08 19:37:20 +0000199 uint64_t Size = (uint64_t)LoopSize*TripCountFull;
Chris Lattner82fec4e2004-05-13 20:43:31 +0000200 if (Size > UnrollThreshold) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000201 DOUT << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n";
Chris Lattner83bf2882004-04-18 05:20:17 +0000202 return Changed;
203 }
Bill Wendlingb7427032006-11-26 09:46:52 +0000204 DOUT << "UNROLLING!\n";
Misha Brukmanfd939082005-04-21 23:48:37 +0000205
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000206 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
207
Chris Lattnerd4bc5642005-01-08 19:37:20 +0000208 unsigned TripCount = (unsigned)TripCountFull;
209
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000210 BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
Chris Lattner83bf2882004-04-18 05:20:17 +0000211
212 // For the first iteration of the loop, we should use the precloned values for
213 // PHI nodes. Insert associations now.
214 std::map<const Value*, Value*> LastValueMap;
215 std::vector<PHINode*> OrigPHINode;
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000216 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000217 PHINode *PN = cast<PHINode>(I);
Chris Lattner83bf2882004-04-18 05:20:17 +0000218 OrigPHINode.push_back(PN);
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000219 if (Instruction *I =
220 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
221 if (L->contains(I->getParent()))
Chris Lattner83bf2882004-04-18 05:20:17 +0000222 LastValueMap[I] = I;
223 }
224
225 // Remove the exit branch from the loop
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000226 LatchBlock->getInstList().erase(BI);
227
228 std::vector<BasicBlock*> Headers;
229 std::vector<BasicBlock*> Latches;
230 Headers.push_back(Header);
231 Latches.push_back(LatchBlock);
Chris Lattner83bf2882004-04-18 05:20:17 +0000232
233 assert(TripCount != 0 && "Trip count of 0 is impossible!");
234 for (unsigned It = 1; It != TripCount; ++It) {
235 char SuffixBuffer[100];
236 sprintf(SuffixBuffer, ".%d", It);
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000237
238 std::vector<BasicBlock*> NewBlocks;
239
240 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
241 E = LoopBlocks.end(); BB != E; ++BB) {
242 std::map<const Value*, Value*> ValueMap;
243 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
244 Header->getParent()->getBasicBlockList().push_back(New);
Chris Lattner83bf2882004-04-18 05:20:17 +0000245
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000246 // Loop over all of the PHI nodes in the block, changing them to use the
247 // incoming values from the previous block.
248 if (*BB == Header)
249 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
250 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
251 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
252 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
253 if (It > 1 && L->contains(InValI->getParent()))
254 InVal = LastValueMap[InValI];
255 ValueMap[OrigPHINode[i]] = InVal;
256 New->getInstList().erase(NewPHI);
257 }
258
259 // Update our running map of newest clones
260 LastValueMap[*BB] = New;
261 for (std::map<const Value*, Value*>::iterator VI = ValueMap.begin(),
262 VE = ValueMap.end(); VI != VE; ++VI)
263 LastValueMap[VI->first] = VI->second;
264
265 L->addBasicBlockToLoop(New, *LI);
266
267 // Add phi entries for newly created values to all exit blocks except
268 // the successor of the latch block. The successor of the exit block will
269 // be updated specially after unrolling all the way.
270 if (*BB != LatchBlock)
271 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
272 UI != UE; ++UI) {
273 Instruction* UseInst = cast<Instruction>(*UI);
274 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
275 PHINode* phi = cast<PHINode>(UseInst);
276 Value* Incoming = phi->getIncomingValueForBlock(*BB);
277 if (isa<Instruction>(Incoming))
278 Incoming = LastValueMap[Incoming];
279
280 phi->addIncoming(Incoming, New);
281 }
282 }
283
284 // Keep track of new headers and latches as we create them, so that
285 // we can insert the proper branches later.
286 if (*BB == Header)
287 Headers.push_back(New);
288 if (*BB == LatchBlock)
289 Latches.push_back(New);
290
291 NewBlocks.push_back(New);
Chris Lattner83bf2882004-04-18 05:20:17 +0000292 }
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000293
294 // Remap all instructions in the most recent iteration
295 for (unsigned i = 0; i < NewBlocks.size(); ++i)
296 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
297 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner998f44f2004-04-18 17:32:39 +0000298 RemapInstruction(I, LastValueMap);
Chris Lattner998f44f2004-04-18 17:32:39 +0000299 }
Chris Lattner83bf2882004-04-18 05:20:17 +0000300
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000301
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000302
303 // Update PHI nodes that reference the final latch block
304 if (TripCount > 1) {
305 std::set<PHINode*> Users;
306 for (Value::use_iterator UI = LatchBlock->use_begin(),
307 UE = LatchBlock->use_end(); UI != UE; ++UI)
308 if (PHINode* phi = dyn_cast<PHINode>(*UI))
309 Users.insert(phi);
310
311 for (std::set<PHINode*>::iterator SI = Users.begin(), SE = Users.end();
312 SI != SE; ++SI) {
313 Value* InVal = (*SI)->getIncomingValueForBlock(LatchBlock);
314 if (isa<Instruction>(InVal))
315 InVal = LastValueMap[InVal];
316 (*SI)->removeIncomingValue(LatchBlock, false);
Owen Anderson20357252006-08-25 22:13:55 +0000317 if (InVal)
318 (*SI)->addIncoming(InVal, cast<BasicBlock>(LastValueMap[LatchBlock]));
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000319 }
320 }
Chris Lattner83bf2882004-04-18 05:20:17 +0000321
322 // Now loop over the PHI nodes in the original block, setting them to their
323 // incoming values.
324 BasicBlock *Preheader = L->getLoopPreheader();
325 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
326 PHINode *PN = OrigPHINode[i];
327 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000328 Header->getInstList().erase(PN);
Owen Anderson59312b12006-08-28 02:09:46 +0000329 }
330
331 // Insert the branches that link the different iterations together
332 for (unsigned i = 0; i < Latches.size()-1; ++i) {
333 new BranchInst(Headers[i+1], Latches[i]);
334 if(BasicBlock* Fold = FoldBlockIntoPredecessor(Headers[i+1])) {
335 std::replace(Latches.begin(), Latches.end(), Headers[i+1], Fold);
336 std::replace(Headers.begin(), Headers.end(), Headers[i+1], Fold);
337 }
338 }
339
340 // Finally, add an unconditional branch to the block to continue into the exit
341 // block.
342 new BranchInst(LoopExit, Latches[Latches.size()-1]);
343 FoldBlockIntoPredecessor(LoopExit);
344
Chris Lattner83bf2882004-04-18 05:20:17 +0000345 // At this point, the code is well formed. We now do a quick sweep over the
346 // inserted code, doing constant propagation and dead code elimination as we
347 // go.
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000348 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
349 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
Owen Anderson59312b12006-08-28 02:09:46 +0000350 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000351 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
352 Instruction *Inst = I++;
Misha Brukmanfd939082005-04-21 23:48:37 +0000353
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000354 if (isInstructionTriviallyDead(Inst))
355 (*BB)->getInstList().erase(Inst);
356 else if (Constant *C = ConstantFoldInstruction(Inst)) {
357 Inst->replaceAllUsesWith(C);
358 (*BB)->getInstList().erase(Inst);
359 }
Chris Lattner83bf2882004-04-18 05:20:17 +0000360 }
Chris Lattner83bf2882004-04-18 05:20:17 +0000361
Chris Lattner9c2cc462004-04-18 05:38:37 +0000362 // Update the loop information for this loop.
363 Loop *Parent = L->getParentLoop();
364
365 // Move all of the basic blocks in the loop into the parent loop.
Owen Anderson3b53c4e2006-08-24 21:28:19 +0000366 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
367 E = NewLoopBlocks.end(); BB != E; ++BB)
368 LI->changeLoopFor(*BB, Parent);
Chris Lattner9c2cc462004-04-18 05:38:37 +0000369
370 // Remove the loop from the parent.
371 if (Parent)
372 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
373 else
374 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
375
Chris Lattner83bf2882004-04-18 05:20:17 +0000376 ++NumUnrolled;
377 return true;
378}