blob: d32997020433a56759a3eaa8214bb17a51f5e43d [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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 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.
17//
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/ConstantFolding.h"
26#include "llvm/Analysis/LoopInfo.h"
27#include "llvm/Analysis/LoopPass.h"
28#include "llvm/Transforms/Utils/Cloning.h"
29#include "llvm/Transforms/Utils/Local.h"
30#include "llvm/Support/CFG.h"
31#include "llvm/Support/Compiler.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/MathExtras.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallPtrSet.h"
38#include "llvm/IntrinsicInst.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include <algorithm>
Anton Korobeynikov357a27d2008-02-20 11:08:44 +000040#include <climits>
41#include <cstdio>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042using namespace llvm;
43
44STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
Chris Lattner03dc7d72007-08-02 16:53:43 +000045STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046
Dan Gohman089efff2008-05-13 00:00:25 +000047static cl::opt<unsigned>
48UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
49 cl::desc("The cut-off point for automatic loop unrolling"));
50
51static cl::opt<unsigned>
52UnrollCount("unroll-count", cl::init(0), cl::Hidden,
53 cl::desc("Use this unroll count for all loops, for testing purposes"));
54
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 class VISIBILITY_HIDDEN LoopUnroll : public LoopPass {
57 LoopInfo *LI; // The current loop information
58 public:
59 static char ID; // Pass ID, replacement for typeid
60 LoopUnroll() : LoopPass((intptr_t)&ID) {}
61
62 /// A magic value for use with the Threshold parameter to indicate
63 /// that the loop unroll should be performed regardless of how much
64 /// code expansion would result.
65 static const unsigned NoThreshold = UINT_MAX;
66
67 bool runOnLoop(Loop *L, LPPassManager &LPM);
68 bool unrollLoop(Loop *L, unsigned Count, unsigned Threshold);
69 BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB);
70
71 /// This transformation requires natural loop information & requires that
72 /// loop preheaders be inserted into the CFG...
73 ///
74 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequiredID(LoopSimplifyID);
76 AU.addRequiredID(LCSSAID);
77 AU.addRequired<LoopInfo>();
78 AU.addPreservedID(LCSSAID);
79 AU.addPreserved<LoopInfo>();
80 }
81 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082}
83
Dan Gohman089efff2008-05-13 00:00:25 +000084char LoopUnroll::ID = 0;
85static RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087LoopPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
88
89/// ApproximateLoopSize - Approximate the size of the loop.
90static unsigned ApproximateLoopSize(const Loop *L) {
91 unsigned Size = 0;
92 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
93 BasicBlock *BB = L->getBlocks()[i];
94 Instruction *Term = BB->getTerminator();
95 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
96 if (isa<PHINode>(I) && BB == L->getHeader()) {
97 // Ignore PHI nodes in the header.
98 } else if (I->hasOneUse() && I->use_back() == Term) {
99 // Ignore instructions only used by the loop terminator.
100 } else if (isa<DbgInfoIntrinsic>(I)) {
101 // Ignore debug instructions
Devang Pateleb485232008-03-17 23:41:20 +0000102 } else if (isa<CallInst>(I)) {
Devang Patel86ad6a22008-03-19 23:05:52 +0000103 // Estimate size overhead introduced by call instructions which
104 // is higher than other instructions. Here 3 and 10 are magic
105 // numbers that help one isolated test case from PR2067 without
106 // negatively impacting measured benchmarks.
Devang Pateleb485232008-03-17 23:41:20 +0000107 if (isa<IntrinsicInst>(I))
108 Size = Size + 3;
109 else
110 Size = Size + 10;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111 } else {
112 ++Size;
113 }
114
115 // TODO: Ignore expressions derived from PHI and constants if inval of phi
116 // is a constant, or if operation is associative. This will get induction
117 // variables.
118 }
119 }
120
121 return Size;
122}
123
124// RemapInstruction - Convert the instruction operands from referencing the
125// current values into those specified by ValueMap.
126//
127static inline void RemapInstruction(Instruction *I,
128 DenseMap<const Value *, Value*> &ValueMap) {
129 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
130 Value *Op = I->getOperand(op);
131 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
132 if (It != ValueMap.end()) Op = It->second;
133 I->setOperand(op, Op);
134 }
135}
136
137// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
138// only has one predecessor, and that predecessor only has one successor.
139// Returns the new combined block.
140BasicBlock *LoopUnroll::FoldBlockIntoPredecessor(BasicBlock *BB) {
141 // Merge basic blocks into their predecessor if there is only one distinct
142 // pred, and if there is only one distinct successor of the predecessor, and
143 // if there are no PHI nodes.
144 //
145 BasicBlock *OnlyPred = BB->getSinglePredecessor();
146 if (!OnlyPred) return 0;
147
148 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
149 return 0;
150
151 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
152
153 // Resolve any PHI nodes at the start of the block. They are all
154 // guaranteed to have exactly one entry if they exist, unless there are
155 // multiple duplicate (but guaranteed to be equal) entries for the
156 // incoming edges. This occurs when there are multiple edges from
157 // OnlyPred to OnlySucc.
158 //
159 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
160 PN->replaceAllUsesWith(PN->getIncomingValue(0));
161 BB->getInstList().pop_front(); // Delete the phi node...
162 }
163
164 // Delete the unconditional branch from the predecessor...
165 OnlyPred->getInstList().pop_back();
166
167 // Move all definitions in the successor to the predecessor...
168 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
169
170 // Make all PHI nodes that referred to BB now refer to Pred as their
171 // source...
172 BB->replaceAllUsesWith(OnlyPred);
173
174 std::string OldName = BB->getName();
175
176 // Erase basic block from the function...
177 LI->removeBlock(BB);
178 BB->eraseFromParent();
179
180 // Inherit predecessor's name if it exists...
Owen Andersonab567f82008-04-14 17:38:21 +0000181 if (!OldName.empty() && !OnlyPred->hasName())
182 OnlyPred->setName(OldName);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183
184 return OnlyPred;
185}
186
187bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
188 LI = &getAnalysis<LoopInfo>();
189
190 // Unroll the loop.
191 if (!unrollLoop(L, UnrollCount, UnrollThreshold))
192 return false;
193
194 // Update the loop information for this loop.
195 // If we completely unrolled the loop, remove it from the parent.
196 if (L->getNumBackEdges() == 0)
197 LPM.deleteLoopFromQueue(L);
198
199 return true;
200}
201
202/// Unroll the given loop by UnrollCount, or by a heuristically-determined
203/// value if Count is zero. If Threshold is not NoThreshold, it is a value
204/// to limit code size expansion. If the loop size would expand beyond the
205/// threshold value, unrolling is suppressed. The return value is true if
206/// any transformations are performed.
207///
208bool LoopUnroll::unrollLoop(Loop *L, unsigned Count, unsigned Threshold) {
209 assert(L->isLCSSAForm());
210
211 BasicBlock *Header = L->getHeader();
212 BasicBlock *LatchBlock = L->getLoopLatch();
213 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
214
215 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
216 << "] Loop %" << Header->getName() << "\n";
217
218 if (!BI || BI->isUnconditional()) {
Wojciech Matyjewicz9df2f202008-01-04 20:02:18 +0000219 // The loop-rotate pass can be helpful to avoid this in many cases.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 DOUT << " Can't unroll; loop not terminated by a conditional branch.\n";
221 return false;
222 }
223
224 // Determine the trip count and/or trip multiple. A TripCount value of zero
225 // is used to mean an unknown trip count. The TripMultiple value is the
226 // greatest known integer multiple of the trip count.
227 unsigned TripCount = 0;
228 unsigned TripMultiple = 1;
229 if (Value *TripCountValue = L->getTripCount()) {
230 if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCountValue)) {
231 // Guard against huge trip counts. This also guards against assertions in
232 // APInt from the use of getZExtValue, below.
233 if (TripCountC->getValue().getActiveBits() <= 32) {
234 TripCount = (unsigned)TripCountC->getZExtValue();
235 }
236 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCountValue)) {
237 switch (BO->getOpcode()) {
238 case BinaryOperator::Mul:
239 if (ConstantInt *MultipleC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
240 if (MultipleC->getValue().getActiveBits() <= 32) {
241 TripMultiple = (unsigned)MultipleC->getZExtValue();
242 }
243 }
244 break;
245 default: break;
246 }
247 }
248 }
249 if (TripCount != 0)
250 DOUT << " Trip Count = " << TripCount << "\n";
251 if (TripMultiple != 1)
252 DOUT << " Trip Multiple = " << TripMultiple << "\n";
253
254 // Automatically select an unroll count.
255 if (Count == 0) {
256 // Conservative heuristic: if we know the trip count, see if we can
257 // completely unroll (subject to the threshold, checked below); otherwise
258 // don't unroll.
259 if (TripCount != 0) {
260 Count = TripCount;
261 } else {
262 return false;
263 }
264 }
265
266 // Effectively "DCE" unrolled iterations that are beyond the tripcount
267 // and will never be executed.
268 if (TripCount != 0 && Count > TripCount)
269 Count = TripCount;
270
271 assert(Count > 0);
272 assert(TripMultiple > 0);
273 assert(TripCount == 0 || TripCount % TripMultiple == 0);
274
275 // Enforce the threshold.
276 if (Threshold != NoThreshold) {
277 unsigned LoopSize = ApproximateLoopSize(L);
278 DOUT << " Loop Size = " << LoopSize << "\n";
279 uint64_t Size = (uint64_t)LoopSize*Count;
280 if (TripCount != 1 && Size > Threshold) {
281 DOUT << " TOO LARGE TO UNROLL: "
282 << Size << ">" << Threshold << "\n";
283 return false;
284 }
285 }
286
287 // Are we eliminating the loop control altogether?
288 bool CompletelyUnroll = Count == TripCount;
289
290 // If we know the trip count, we know the multiple...
291 unsigned BreakoutTrip = 0;
292 if (TripCount != 0) {
293 BreakoutTrip = TripCount % Count;
294 TripMultiple = 0;
295 } else {
296 // Figure out what multiple to use.
297 BreakoutTrip = TripMultiple =
298 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
299 }
300
301 if (CompletelyUnroll) {
302 DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
303 << " with trip count " << TripCount << "!\n";
304 } else {
305 DOUT << "UNROLLING loop %" << Header->getName()
306 << " by " << Count;
307 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
308 DOUT << " with a breakout at trip " << BreakoutTrip;
309 } else if (TripMultiple != 1) {
310 DOUT << " with " << TripMultiple << " trips per branch";
311 }
312 DOUT << "!\n";
313 }
314
315 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
316
317 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
318 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
319
320 // For the first iteration of the loop, we should use the precloned values for
321 // PHI nodes. Insert associations now.
322 typedef DenseMap<const Value*, Value*> ValueMapTy;
323 ValueMapTy LastValueMap;
324 std::vector<PHINode*> OrigPHINode;
325 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
326 PHINode *PN = cast<PHINode>(I);
327 OrigPHINode.push_back(PN);
328 if (Instruction *I =
329 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
330 if (L->contains(I->getParent()))
331 LastValueMap[I] = I;
332 }
333
334 std::vector<BasicBlock*> Headers;
335 std::vector<BasicBlock*> Latches;
336 Headers.push_back(Header);
337 Latches.push_back(LatchBlock);
338
339 for (unsigned It = 1; It != Count; ++It) {
340 char SuffixBuffer[100];
341 sprintf(SuffixBuffer, ".%d", It);
342
343 std::vector<BasicBlock*> NewBlocks;
344
345 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
346 E = LoopBlocks.end(); BB != E; ++BB) {
347 ValueMapTy ValueMap;
348 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
349 Header->getParent()->getBasicBlockList().push_back(New);
350
351 // Loop over all of the PHI nodes in the block, changing them to use the
352 // incoming values from the previous block.
353 if (*BB == Header)
354 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
355 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
356 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
357 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
358 if (It > 1 && L->contains(InValI->getParent()))
359 InVal = LastValueMap[InValI];
360 ValueMap[OrigPHINode[i]] = InVal;
361 New->getInstList().erase(NewPHI);
362 }
363
364 // Update our running map of newest clones
365 LastValueMap[*BB] = New;
366 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
367 VI != VE; ++VI)
368 LastValueMap[VI->first] = VI->second;
369
Owen Andersonca0b9d42007-11-27 03:43:35 +0000370 L->addBasicBlockToLoop(New, LI->getBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371
372 // Add phi entries for newly created values to all exit blocks except
373 // the successor of the latch block. The successor of the exit block will
374 // be updated specially after unrolling all the way.
375 if (*BB != LatchBlock)
376 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
Nick Lewyckyf8104c52008-01-27 18:35:00 +0000377 UI != UE;) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 Instruction *UseInst = cast<Instruction>(*UI);
Nick Lewyckyf8104c52008-01-27 18:35:00 +0000379 ++UI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
381 PHINode *phi = cast<PHINode>(UseInst);
382 Value *Incoming = phi->getIncomingValueForBlock(*BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383 phi->addIncoming(Incoming, New);
384 }
385 }
386
387 // Keep track of new headers and latches as we create them, so that
388 // we can insert the proper branches later.
389 if (*BB == Header)
390 Headers.push_back(New);
391 if (*BB == LatchBlock) {
392 Latches.push_back(New);
393
394 // Also, clear out the new latch's back edge so that it doesn't look
395 // like a new loop, so that it's amenable to being merged with adjacent
396 // blocks later on.
397 TerminatorInst *Term = New->getTerminator();
398 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
399 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
400 Term->setSuccessor(!ContinueOnTrue, NULL);
401 }
402
403 NewBlocks.push_back(New);
404 }
405
406 // Remap all instructions in the most recent iteration
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +0000407 for (unsigned i = 0; i < NewBlocks.size(); ++i)
408 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
409 E = NewBlocks[i]->end(); I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410 RemapInstruction(I, LastValueMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 }
412
413 // The latch block exits the loop. If there are any PHI nodes in the
414 // successor blocks, update them to use the appropriate values computed as the
415 // last iteration of the loop.
416 if (Count != 1) {
417 SmallPtrSet<PHINode*, 8> Users;
418 for (Value::use_iterator UI = LatchBlock->use_begin(),
419 UE = LatchBlock->use_end(); UI != UE; ++UI)
420 if (PHINode *phi = dyn_cast<PHINode>(*UI))
421 Users.insert(phi);
422
423 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
424 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
425 SI != SE; ++SI) {
426 PHINode *PN = *SI;
427 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
428 // If this value was defined in the loop, take the value defined by the
429 // last iteration of the loop.
430 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
431 if (L->contains(InValI->getParent()))
432 InVal = LastValueMap[InVal];
433 }
434 PN->addIncoming(InVal, LastIterationBB);
435 }
436 }
437
438 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
439 // original block, setting them to their incoming values.
440 if (CompletelyUnroll) {
441 BasicBlock *Preheader = L->getLoopPreheader();
442 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
443 PHINode *PN = OrigPHINode[i];
444 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
445 Header->getInstList().erase(PN);
446 }
447 }
448
449 // Now that all the basic blocks for the unrolled iterations are in place,
450 // set up the branches to connect them.
451 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
452 // The original branch was replicated in each unrolled iteration.
453 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
454
455 // The branch destination.
456 unsigned j = (i + 1) % e;
457 BasicBlock *Dest = Headers[j];
458 bool NeedConditional = true;
459
460 // For a complete unroll, make the last iteration end with a branch
461 // to the exit block.
462 if (CompletelyUnroll && j == 0) {
463 Dest = LoopExit;
464 NeedConditional = false;
465 }
466
467 // If we know the trip count or a multiple of it, we can safely use an
468 // unconditional branch for some iterations.
469 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
470 NeedConditional = false;
471 }
472
473 if (NeedConditional) {
474 // Update the conditional branch's successor for the following
475 // iteration.
476 Term->setSuccessor(!ContinueOnTrue, Dest);
477 } else {
478 Term->setUnconditionalDest(Dest);
479 // Merge adjacent basic blocks, if possible.
480 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest)) {
481 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
482 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
483 }
484 }
485 }
486
487 // At this point, the code is well formed. We now do a quick sweep over the
488 // inserted code, doing constant propagation and dead code elimination as we
489 // go.
490 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
491 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
492 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
493 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
494 Instruction *Inst = I++;
495
496 if (isInstructionTriviallyDead(Inst))
497 (*BB)->getInstList().erase(Inst);
498 else if (Constant *C = ConstantFoldInstruction(Inst)) {
499 Inst->replaceAllUsesWith(C);
500 (*BB)->getInstList().erase(Inst);
501 }
502 }
503
504 NumCompletelyUnrolled += CompletelyUnroll;
505 ++NumUnrolled;
506 return true;
507}