blob: 655ddc4179244d6e5cfc52b2cb3f5c61e211774c [file] [log] [blame]
Chris Lattner946b2552004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner946b2552004-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner946b2552004-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 Andersone001d812006-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 Lattner946b2552004-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"
Chris Lattner024f4ab2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner946b2552004-04-18 05:20:17 +000026#include "llvm/Analysis/LoopInfo.h"
27#include "llvm/Transforms/Utils/Cloning.h"
28#include "llvm/Transforms/Utils/Local.h"
Owen Anderson62c84fe2006-08-28 02:09:46 +000029#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/ADT/STLExtras.h"
Chris Lattner6d048a02004-11-22 17:18:36 +000034#include "llvm/IntrinsicInst.h"
Chris Lattner946b2552004-04-18 05:20:17 +000035#include <cstdio>
Chris Lattnerbc021772004-04-19 03:01:23 +000036#include <set>
Reid Spencerce078332004-10-18 14:38:48 +000037#include <algorithm>
Chris Lattner946b2552004-04-18 05:20:17 +000038using namespace llvm;
39
Chris Lattner79a42ac2006-12-19 21:40:18 +000040STATISTIC(NumUnrolled, "Number of loops completely unrolled");
Chris Lattner946b2552004-04-18 05:20:17 +000041
Chris Lattner79a42ac2006-12-19 21:40:18 +000042namespace {
Chris Lattner946b2552004-04-18 05:20:17 +000043 cl::opt<unsigned>
Chris Lattnerd1525022004-04-18 18:06:14 +000044 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
Chris Lattner946b2552004-04-18 05:20:17 +000045 cl::desc("The cut-off point for loop unrolling"));
46
47 class LoopUnroll : public FunctionPass {
48 LoopInfo *LI; // The current loop information
49 public:
50 virtual bool runOnFunction(Function &F);
51 bool visitLoop(Loop *L);
Owen Anderson62c84fe2006-08-28 02:09:46 +000052 BasicBlock* FoldBlockIntoPredecessor(BasicBlock* BB);
Chris Lattner946b2552004-04-18 05:20:17 +000053
54 /// This transformation requires natural loop information & requires that
55 /// loop preheaders be inserted into the CFG...
56 ///
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner946b2552004-04-18 05:20:17 +000058 AU.addRequiredID(LoopSimplifyID);
Owen Andersone001d812006-08-24 21:28:19 +000059 AU.addRequiredID(LCSSAID);
Chris Lattner946b2552004-04-18 05:20:17 +000060 AU.addRequired<LoopInfo>();
Owen Andersone001d812006-08-24 21:28:19 +000061 AU.addPreservedID(LCSSAID);
Chris Lattnerf2cc8412004-04-18 05:38:37 +000062 AU.addPreserved<LoopInfo>();
Chris Lattner946b2552004-04-18 05:20:17 +000063 }
64 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000065 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
Chris Lattner946b2552004-04-18 05:20:17 +000066}
67
68FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
69
70bool LoopUnroll::runOnFunction(Function &F) {
71 bool Changed = false;
72 LI = &getAnalysis<LoopInfo>();
73
Chris Lattnerf2cc8412004-04-18 05:38:37 +000074 // Transform all the top-level loops. Copy the loop list so that the child
75 // can update the loop tree if it needs to delete the loop.
76 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
77 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
78 Changed |= visitLoop(SubLoops[i]);
Chris Lattner946b2552004-04-18 05:20:17 +000079
80 return Changed;
81}
82
83/// ApproximateLoopSize - Approximate the size of the loop after it has been
84/// unrolled.
85static unsigned ApproximateLoopSize(const Loop *L) {
86 unsigned Size = 0;
87 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
88 BasicBlock *BB = L->getBlocks()[i];
89 Instruction *Term = BB->getTerminator();
90 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
91 if (isa<PHINode>(I) && BB == L->getHeader()) {
92 // Ignore PHI nodes in the header.
93 } else if (I->hasOneUse() && I->use_back() == Term) {
94 // Ignore instructions only used by the loop terminator.
Reid Spencerde46e482006-11-02 20:25:50 +000095 } else if (isa<DbgInfoIntrinsic>(I)) {
Jeff Cohen82639852005-04-23 21:38:35 +000096 // Ignore debug instructions
Chris Lattner946b2552004-04-18 05:20:17 +000097 } else {
98 ++Size;
99 }
100
101 // TODO: Ignore expressions derived from PHI and constants if inval of phi
102 // is a constant, or if operation is associative. This will get induction
103 // variables.
104 }
105 }
106
107 return Size;
108}
109
Misha Brukmanb1c93172005-04-21 23:48:37 +0000110// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner946b2552004-04-18 05:20:17 +0000111// current values into those specified by ValueMap.
112//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000113static inline void RemapInstruction(Instruction *I,
Chris Lattner946b2552004-04-18 05:20:17 +0000114 std::map<const Value *, Value*> &ValueMap) {
115 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
116 Value *Op = I->getOperand(op);
117 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
118 if (It != ValueMap.end()) Op = It->second;
119 I->setOperand(op, Op);
120 }
121}
122
Owen Anderson62c84fe2006-08-28 02:09:46 +0000123// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
124// only has one predecessor, and that predecessor only has one successor.
125// Returns the new combined block.
126BasicBlock* LoopUnroll::FoldBlockIntoPredecessor(BasicBlock* BB) {
127 // Merge basic blocks into their predecessor if there is only one distinct
128 // pred, and if there is only one distinct successor of the predecessor, and
129 // if there are no PHI nodes.
130 //
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000131 BasicBlock *OnlyPred = BB->getSinglePredecessor();
132 if (!OnlyPred) return 0;
Owen Anderson62c84fe2006-08-28 02:09:46 +0000133
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000134 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
135 return 0;
136
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000137 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000138
139 // Resolve any PHI nodes at the start of the block. They are all
140 // guaranteed to have exactly one entry if they exist, unless there are
141 // multiple duplicate (but guaranteed to be equal) entries for the
142 // incoming edges. This occurs when there are multiple edges from
143 // OnlyPred to OnlySucc.
144 //
145 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
146 PN->replaceAllUsesWith(PN->getIncomingValue(0));
147 BB->getInstList().pop_front(); // Delete the phi node...
Owen Anderson62c84fe2006-08-28 02:09:46 +0000148 }
149
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000150 // Delete the unconditional branch from the predecessor...
151 OnlyPred->getInstList().pop_back();
Owen Anderson62c84fe2006-08-28 02:09:46 +0000152
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000153 // Move all definitions in the successor to the predecessor...
154 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Owen Anderson62c84fe2006-08-28 02:09:46 +0000155
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000156 // Make all PHI nodes that referred to BB now refer to Pred as their
157 // source...
158 BB->replaceAllUsesWith(OnlyPred);
Owen Anderson62c84fe2006-08-28 02:09:46 +0000159
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000160 std::string OldName = BB->getName();
Owen Anderson62c84fe2006-08-28 02:09:46 +0000161
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000162 // Erase basic block from the function...
163 LI->removeBlock(BB);
164 BB->eraseFromParent();
Owen Anderson62c84fe2006-08-28 02:09:46 +0000165
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000166 // Inherit predecessors name if it exists...
167 if (!OldName.empty() && !OnlyPred->hasName())
168 OnlyPred->setName(OldName);
Owen Anderson62c84fe2006-08-28 02:09:46 +0000169
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000170 return OnlyPred;
Owen Anderson62c84fe2006-08-28 02:09:46 +0000171}
172
Chris Lattner946b2552004-04-18 05:20:17 +0000173bool LoopUnroll::visitLoop(Loop *L) {
174 bool Changed = false;
175
176 // Recurse through all subloops before we process this loop. Copy the loop
177 // list so that the child can update the loop tree if it needs to delete the
178 // loop.
179 std::vector<Loop*> SubLoops(L->begin(), L->end());
180 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
181 Changed |= visitLoop(SubLoops[i]);
182
Owen Andersone001d812006-08-24 21:28:19 +0000183 BasicBlock* Header = L->getHeader();
184 BasicBlock* LatchBlock = L->getLoopLatch();
Chris Lattner946b2552004-04-18 05:20:17 +0000185
Owen Andersone001d812006-08-24 21:28:19 +0000186 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Chris Lattner946b2552004-04-18 05:20:17 +0000187 if (BI == 0) return Changed; // Must end in a conditional branch
188
189 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
190 if (!TripCountC) return Changed; // Must have constant trip count!
191
Reid Spencere0fc4df2006-10-20 07:07:24 +0000192 uint64_t TripCountFull = TripCountC->getZExtValue();
193 if (TripCountFull != TripCountC->getZExtValue() || TripCountFull == 0)
Chris Lattner946b2552004-04-18 05:20:17 +0000194 return Changed; // More than 2^32 iterations???
195
196 unsigned LoopSize = ApproximateLoopSize(L);
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000197 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
198 << "] Loop %" << Header->getName() << " Loop Size = "
199 << LoopSize << " Trip Count = " << TripCountFull << " - ";
Chris Lattner47f395c2005-01-08 19:37:20 +0000200 uint64_t Size = (uint64_t)LoopSize*TripCountFull;
Chris Lattnerc12c9452004-05-13 20:43:31 +0000201 if (Size > UnrollThreshold) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000202 DOUT << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n";
Chris Lattner946b2552004-04-18 05:20:17 +0000203 return Changed;
204 }
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000205 DOUT << "UNROLLING!\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +0000206
Owen Andersone001d812006-08-24 21:28:19 +0000207 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
208
Chris Lattner47f395c2005-01-08 19:37:20 +0000209 unsigned TripCount = (unsigned)TripCountFull;
210
Owen Andersone001d812006-08-24 21:28:19 +0000211 BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
Chris Lattner946b2552004-04-18 05:20:17 +0000212
213 // For the first iteration of the loop, we should use the precloned values for
214 // PHI nodes. Insert associations now.
215 std::map<const Value*, Value*> LastValueMap;
216 std::vector<PHINode*> OrigPHINode;
Owen Andersone001d812006-08-24 21:28:19 +0000217 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Reid Spencer66149462004-09-15 17:06:42 +0000218 PHINode *PN = cast<PHINode>(I);
Chris Lattner946b2552004-04-18 05:20:17 +0000219 OrigPHINode.push_back(PN);
Owen Andersone001d812006-08-24 21:28:19 +0000220 if (Instruction *I =
221 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
222 if (L->contains(I->getParent()))
Chris Lattner946b2552004-04-18 05:20:17 +0000223 LastValueMap[I] = I;
224 }
225
226 // Remove the exit branch from the loop
Owen Andersone001d812006-08-24 21:28:19 +0000227 LatchBlock->getInstList().erase(BI);
228
229 std::vector<BasicBlock*> Headers;
230 std::vector<BasicBlock*> Latches;
231 Headers.push_back(Header);
232 Latches.push_back(LatchBlock);
Chris Lattner946b2552004-04-18 05:20:17 +0000233
234 assert(TripCount != 0 && "Trip count of 0 is impossible!");
235 for (unsigned It = 1; It != TripCount; ++It) {
236 char SuffixBuffer[100];
237 sprintf(SuffixBuffer, ".%d", It);
Owen Andersone001d812006-08-24 21:28:19 +0000238
239 std::vector<BasicBlock*> NewBlocks;
240
241 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
242 E = LoopBlocks.end(); BB != E; ++BB) {
243 std::map<const Value*, Value*> ValueMap;
244 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
245 Header->getParent()->getBasicBlockList().push_back(New);
Chris Lattner946b2552004-04-18 05:20:17 +0000246
Owen Andersone001d812006-08-24 21:28:19 +0000247 // Loop over all of the PHI nodes in the block, changing them to use the
248 // incoming values from the previous block.
249 if (*BB == Header)
250 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
251 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
252 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
253 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
254 if (It > 1 && L->contains(InValI->getParent()))
255 InVal = LastValueMap[InValI];
256 ValueMap[OrigPHINode[i]] = InVal;
257 New->getInstList().erase(NewPHI);
258 }
259
260 // Update our running map of newest clones
261 LastValueMap[*BB] = New;
262 for (std::map<const Value*, Value*>::iterator VI = ValueMap.begin(),
263 VE = ValueMap.end(); VI != VE; ++VI)
264 LastValueMap[VI->first] = VI->second;
265
266 L->addBasicBlockToLoop(New, *LI);
267
268 // Add phi entries for newly created values to all exit blocks except
269 // the successor of the latch block. The successor of the exit block will
270 // be updated specially after unrolling all the way.
271 if (*BB != LatchBlock)
272 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
273 UI != UE; ++UI) {
274 Instruction* UseInst = cast<Instruction>(*UI);
275 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
276 PHINode* phi = cast<PHINode>(UseInst);
277 Value* Incoming = phi->getIncomingValueForBlock(*BB);
278 if (isa<Instruction>(Incoming))
279 Incoming = LastValueMap[Incoming];
280
281 phi->addIncoming(Incoming, New);
282 }
283 }
284
285 // Keep track of new headers and latches as we create them, so that
286 // we can insert the proper branches later.
287 if (*BB == Header)
288 Headers.push_back(New);
289 if (*BB == LatchBlock)
290 Latches.push_back(New);
291
292 NewBlocks.push_back(New);
Chris Lattner946b2552004-04-18 05:20:17 +0000293 }
Owen Andersone001d812006-08-24 21:28:19 +0000294
295 // Remap all instructions in the most recent iteration
296 for (unsigned i = 0; i < NewBlocks.size(); ++i)
297 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
298 E = NewBlocks[i]->end(); I != E; ++I)
Chris Lattner230bcb62004-04-18 17:32:39 +0000299 RemapInstruction(I, LastValueMap);
Chris Lattner230bcb62004-04-18 17:32:39 +0000300 }
Chris Lattner946b2552004-04-18 05:20:17 +0000301
Owen Andersone001d812006-08-24 21:28:19 +0000302
Owen Andersone001d812006-08-24 21:28:19 +0000303
304 // Update PHI nodes that reference the final latch block
305 if (TripCount > 1) {
306 std::set<PHINode*> Users;
307 for (Value::use_iterator UI = LatchBlock->use_begin(),
308 UE = LatchBlock->use_end(); UI != UE; ++UI)
309 if (PHINode* phi = dyn_cast<PHINode>(*UI))
310 Users.insert(phi);
311
312 for (std::set<PHINode*>::iterator SI = Users.begin(), SE = Users.end();
313 SI != SE; ++SI) {
314 Value* InVal = (*SI)->getIncomingValueForBlock(LatchBlock);
315 if (isa<Instruction>(InVal))
316 InVal = LastValueMap[InVal];
317 (*SI)->removeIncomingValue(LatchBlock, false);
Owen Anderson403b95a2006-08-25 22:13:55 +0000318 if (InVal)
319 (*SI)->addIncoming(InVal, cast<BasicBlock>(LastValueMap[LatchBlock]));
Owen Andersone001d812006-08-24 21:28:19 +0000320 }
321 }
Chris Lattner946b2552004-04-18 05:20:17 +0000322
323 // Now loop over the PHI nodes in the original block, setting them to their
324 // incoming values.
325 BasicBlock *Preheader = L->getLoopPreheader();
326 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
327 PHINode *PN = OrigPHINode[i];
328 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
Owen Andersone001d812006-08-24 21:28:19 +0000329 Header->getInstList().erase(PN);
Owen Anderson62c84fe2006-08-28 02:09:46 +0000330 }
331
332 // Insert the branches that link the different iterations together
333 for (unsigned i = 0; i < Latches.size()-1; ++i) {
334 new BranchInst(Headers[i+1], Latches[i]);
335 if(BasicBlock* Fold = FoldBlockIntoPredecessor(Headers[i+1])) {
336 std::replace(Latches.begin(), Latches.end(), Headers[i+1], Fold);
337 std::replace(Headers.begin(), Headers.end(), Headers[i+1], Fold);
338 }
339 }
340
341 // Finally, add an unconditional branch to the block to continue into the exit
342 // block.
343 new BranchInst(LoopExit, Latches[Latches.size()-1]);
344 FoldBlockIntoPredecessor(LoopExit);
345
Chris Lattner946b2552004-04-18 05:20:17 +0000346 // At this point, the code is well formed. We now do a quick sweep over the
347 // inserted code, doing constant propagation and dead code elimination as we
348 // go.
Owen Andersone001d812006-08-24 21:28:19 +0000349 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
350 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
Owen Anderson62c84fe2006-08-28 02:09:46 +0000351 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
Owen Andersone001d812006-08-24 21:28:19 +0000352 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
353 Instruction *Inst = I++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000354
Owen Andersone001d812006-08-24 21:28:19 +0000355 if (isInstructionTriviallyDead(Inst))
356 (*BB)->getInstList().erase(Inst);
357 else if (Constant *C = ConstantFoldInstruction(Inst)) {
358 Inst->replaceAllUsesWith(C);
359 (*BB)->getInstList().erase(Inst);
360 }
Chris Lattner946b2552004-04-18 05:20:17 +0000361 }
Chris Lattner946b2552004-04-18 05:20:17 +0000362
Chris Lattnerf2cc8412004-04-18 05:38:37 +0000363 // Update the loop information for this loop.
364 Loop *Parent = L->getParentLoop();
365
366 // Move all of the basic blocks in the loop into the parent loop.
Owen Andersone001d812006-08-24 21:28:19 +0000367 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
368 E = NewLoopBlocks.end(); BB != E; ++BB)
369 LI->changeLoopFor(*BB, Parent);
Chris Lattnerf2cc8412004-04-18 05:38:37 +0000370
371 // Remove the loop from the parent.
372 if (Parent)
373 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
374 else
375 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
376
Chris Lattner946b2552004-04-18 05:20:17 +0000377 ++NumUnrolled;
378 return true;
379}