1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
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.
18 //===----------------------------------------------------------------------===//
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"
43 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
44 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
49 ("unroll-threshold", cl::init(100), cl::Hidden,
50 cl::desc("The cut-off point for automatic loop unrolling"));
54 ("unroll-count", cl::init(0), cl::Hidden,
55 cl::desc("Use this unroll count for all loops, for testing purposes"));
57 class VISIBILITY_HIDDEN LoopUnroll : public LoopPass {
58 LoopInfo *LI; // The current loop information
60 static char ID; // Pass ID, replacement for typeid
61 LoopUnroll() : LoopPass((intptr_t)&ID) {}
63 /// A magic value for use with the Threshold parameter to indicate
64 /// that the loop unroll should be performed regardless of how much
65 /// code expansion would result.
66 static const unsigned NoThreshold = UINT_MAX;
68 bool runOnLoop(Loop *L, LPPassManager &LPM);
69 bool unrollLoop(Loop *L, unsigned Count, unsigned Threshold);
70 BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB);
72 /// This transformation requires natural loop information & requires that
73 /// loop preheaders be inserted into the CFG...
75 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequiredID(LoopSimplifyID);
77 AU.addRequiredID(LCSSAID);
78 AU.addRequired<LoopInfo>();
79 AU.addPreservedID(LCSSAID);
80 AU.addPreserved<LoopInfo>();
83 char LoopUnroll::ID = 0;
84 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
87 LoopPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
89 /// ApproximateLoopSize - Approximate the size of the loop.
90 static unsigned ApproximateLoopSize(const Loop *L) {
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
106 // TODO: Ignore expressions derived from PHI and constants if inval of phi
107 // is a constant, or if operation is associative. This will get induction
115 // RemapInstruction - Convert the instruction operands from referencing the
116 // current values into those specified by ValueMap.
118 static inline void RemapInstruction(Instruction *I,
119 DenseMap<const Value *, Value*> &ValueMap) {
120 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
121 Value *Op = I->getOperand(op);
122 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
123 if (It != ValueMap.end()) Op = It->second;
124 I->setOperand(op, Op);
128 // FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
129 // only has one predecessor, and that predecessor only has one successor.
130 // Returns the new combined block.
131 BasicBlock *LoopUnroll::FoldBlockIntoPredecessor(BasicBlock *BB) {
132 // Merge basic blocks into their predecessor if there is only one distinct
133 // pred, and if there is only one distinct successor of the predecessor, and
134 // if there are no PHI nodes.
136 BasicBlock *OnlyPred = BB->getSinglePredecessor();
137 if (!OnlyPred) return 0;
139 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
142 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
144 // Resolve any PHI nodes at the start of the block. They are all
145 // guaranteed to have exactly one entry if they exist, unless there are
146 // multiple duplicate (but guaranteed to be equal) entries for the
147 // incoming edges. This occurs when there are multiple edges from
148 // OnlyPred to OnlySucc.
150 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
151 PN->replaceAllUsesWith(PN->getIncomingValue(0));
152 BB->getInstList().pop_front(); // Delete the phi node...
155 // Delete the unconditional branch from the predecessor...
156 OnlyPred->getInstList().pop_back();
158 // Move all definitions in the successor to the predecessor...
159 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
161 // Make all PHI nodes that referred to BB now refer to Pred as their
163 BB->replaceAllUsesWith(OnlyPred);
165 std::string OldName = BB->getName();
167 // Erase basic block from the function...
169 BB->eraseFromParent();
171 // Inherit predecessor's name if it exists...
172 if (!OldName.empty() && !OnlyPred->hasName())
173 OnlyPred->setName(OldName);
178 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
179 LI = &getAnalysis<LoopInfo>();
182 if (!unrollLoop(L, UnrollCount, UnrollThreshold))
185 // Update the loop information for this loop.
186 // If we completely unrolled the loop, remove it from the parent.
187 if (L->getNumBackEdges() == 0)
188 LPM.deleteLoopFromQueue(L);
193 /// Unroll the given loop by UnrollCount, or by a heuristically-determined
194 /// value if Count is zero. If Threshold is not NoThreshold, it is a value
195 /// to limit code size expansion. If the loop size would expand beyond the
196 /// threshold value, unrolling is suppressed. The return value is true if
197 /// any transformations are performed.
199 bool LoopUnroll::unrollLoop(Loop *L, unsigned Count, unsigned Threshold) {
200 assert(L->isLCSSAForm());
202 BasicBlock *Header = L->getHeader();
203 BasicBlock *LatchBlock = L->getLoopLatch();
204 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
206 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
207 << "] Loop %" << Header->getName() << "\n";
209 if (!BI || BI->isUnconditional()) {
210 // The loop-rorate pass can be helpful to avoid this in many cases.
211 DOUT << " Can't unroll; loop not terminated by a conditional branch.\n";
215 // Determine the trip count and/or trip multiple. A TripCount value of zero
216 // is used to mean an unknown trip count. The TripMultiple value is the
217 // greatest known integer multiple of the trip count.
218 unsigned TripCount = 0;
219 unsigned TripMultiple = 1;
220 if (Value *TripCountValue = L->getTripCount()) {
221 if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCountValue)) {
222 // Guard against huge trip counts. This also guards against assertions in
223 // APInt from the use of getZExtValue, below.
224 if (TripCountC->getValue().getActiveBits() <= 32) {
225 TripCount = (unsigned)TripCountC->getZExtValue();
227 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCountValue)) {
228 switch (BO->getOpcode()) {
229 case BinaryOperator::Mul:
230 if (ConstantInt *MultipleC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
231 if (MultipleC->getValue().getActiveBits() <= 32) {
232 TripMultiple = (unsigned)MultipleC->getZExtValue();
241 DOUT << " Trip Count = " << TripCount << "\n";
242 if (TripMultiple != 1)
243 DOUT << " Trip Multiple = " << TripMultiple << "\n";
245 // Automatically select an unroll count.
247 // Conservative heuristic: if we know the trip count, see if we can
248 // completely unroll (subject to the threshold, checked below); otherwise
250 if (TripCount != 0) {
257 // Effectively "DCE" unrolled iterations that are beyond the tripcount
258 // and will never be executed.
259 if (TripCount != 0 && Count > TripCount)
263 assert(TripMultiple > 0);
264 assert(TripCount == 0 || TripCount % TripMultiple == 0);
266 // Enforce the threshold.
267 if (Threshold != NoThreshold) {
268 unsigned LoopSize = ApproximateLoopSize(L);
269 DOUT << " Loop Size = " << LoopSize << "\n";
270 uint64_t Size = (uint64_t)LoopSize*Count;
271 if (TripCount != 1 && Size > Threshold) {
272 DOUT << " TOO LARGE TO UNROLL: "
273 << Size << ">" << Threshold << "\n";
278 // Are we eliminating the loop control altogether?
279 bool CompletelyUnroll = Count == TripCount;
281 // If we know the trip count, we know the multiple...
282 unsigned BreakoutTrip = 0;
283 if (TripCount != 0) {
284 BreakoutTrip = TripCount % Count;
287 // Figure out what multiple to use.
288 BreakoutTrip = TripMultiple =
289 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
292 if (CompletelyUnroll) {
293 DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
294 << " with trip count " << TripCount << "!\n";
296 DOUT << "UNROLLING loop %" << Header->getName()
298 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
299 DOUT << " with a breakout at trip " << BreakoutTrip;
300 } else if (TripMultiple != 1) {
301 DOUT << " with " << TripMultiple << " trips per branch";
306 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
308 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
309 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
311 // For the first iteration of the loop, we should use the precloned values for
312 // PHI nodes. Insert associations now.
313 typedef DenseMap<const Value*, Value*> ValueMapTy;
314 ValueMapTy LastValueMap;
315 std::vector<PHINode*> OrigPHINode;
316 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
317 PHINode *PN = cast<PHINode>(I);
318 OrigPHINode.push_back(PN);
320 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
321 if (L->contains(I->getParent()))
325 std::vector<BasicBlock*> Headers;
326 std::vector<BasicBlock*> Latches;
327 Headers.push_back(Header);
328 Latches.push_back(LatchBlock);
330 for (unsigned It = 1; It != Count; ++It) {
331 char SuffixBuffer[100];
332 sprintf(SuffixBuffer, ".%d", It);
334 std::vector<BasicBlock*> NewBlocks;
336 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
337 E = LoopBlocks.end(); BB != E; ++BB) {
339 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
340 Header->getParent()->getBasicBlockList().push_back(New);
342 // Loop over all of the PHI nodes in the block, changing them to use the
343 // incoming values from the previous block.
345 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
346 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
347 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
348 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
349 if (It > 1 && L->contains(InValI->getParent()))
350 InVal = LastValueMap[InValI];
351 ValueMap[OrigPHINode[i]] = InVal;
352 New->getInstList().erase(NewPHI);
355 // Update our running map of newest clones
356 LastValueMap[*BB] = New;
357 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
359 LastValueMap[VI->first] = VI->second;
361 L->addBasicBlockToLoop(New, *LI);
363 // Add phi entries for newly created values to all exit blocks except
364 // the successor of the latch block. The successor of the exit block will
365 // be updated specially after unrolling all the way.
366 if (*BB != LatchBlock)
367 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
369 Instruction *UseInst = cast<Instruction>(*UI);
370 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
371 PHINode *phi = cast<PHINode>(UseInst);
372 Value *Incoming = phi->getIncomingValueForBlock(*BB);
373 if (isa<Instruction>(Incoming))
374 Incoming = LastValueMap[Incoming];
376 phi->addIncoming(Incoming, New);
380 // Keep track of new headers and latches as we create them, so that
381 // we can insert the proper branches later.
383 Headers.push_back(New);
384 if (*BB == LatchBlock) {
385 Latches.push_back(New);
387 // Also, clear out the new latch's back edge so that it doesn't look
388 // like a new loop, so that it's amenable to being merged with adjacent
390 TerminatorInst *Term = New->getTerminator();
391 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
392 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
393 Term->setSuccessor(!ContinueOnTrue, NULL);
396 NewBlocks.push_back(New);
399 // Remap all instructions in the most recent iteration
400 for (unsigned i = 0; i < NewBlocks.size(); ++i)
401 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
402 E = NewBlocks[i]->end(); I != E; ++I)
403 RemapInstruction(I, LastValueMap);
406 // The latch block exits the loop. If there are any PHI nodes in the
407 // successor blocks, update them to use the appropriate values computed as the
408 // last iteration of the loop.
410 SmallPtrSet<PHINode*, 8> Users;
411 for (Value::use_iterator UI = LatchBlock->use_begin(),
412 UE = LatchBlock->use_end(); UI != UE; ++UI)
413 if (PHINode *phi = dyn_cast<PHINode>(*UI))
416 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
417 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
420 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
421 // If this value was defined in the loop, take the value defined by the
422 // last iteration of the loop.
423 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
424 if (L->contains(InValI->getParent()))
425 InVal = LastValueMap[InVal];
427 PN->addIncoming(InVal, LastIterationBB);
431 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
432 // original block, setting them to their incoming values.
433 if (CompletelyUnroll) {
434 BasicBlock *Preheader = L->getLoopPreheader();
435 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
436 PHINode *PN = OrigPHINode[i];
437 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
438 Header->getInstList().erase(PN);
442 // Now that all the basic blocks for the unrolled iterations are in place,
443 // set up the branches to connect them.
444 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
445 // The original branch was replicated in each unrolled iteration.
446 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
448 // The branch destination.
449 unsigned j = (i + 1) % e;
450 BasicBlock *Dest = Headers[j];
451 bool NeedConditional = true;
453 // For a complete unroll, make the last iteration end with a branch
454 // to the exit block.
455 if (CompletelyUnroll && j == 0) {
457 NeedConditional = false;
460 // If we know the trip count or a multiple of it, we can safely use an
461 // unconditional branch for some iterations.
462 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
463 NeedConditional = false;
466 if (NeedConditional) {
467 // Update the conditional branch's successor for the following
469 Term->setSuccessor(!ContinueOnTrue, Dest);
471 Term->setUnconditionalDest(Dest);
472 // Merge adjacent basic blocks, if possible.
473 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest)) {
474 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
475 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
480 // At this point, the code is well formed. We now do a quick sweep over the
481 // inserted code, doing constant propagation and dead code elimination as we
483 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
484 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
485 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
486 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
487 Instruction *Inst = I++;
489 if (isInstructionTriviallyDead(Inst))
490 (*BB)->getInstList().erase(Inst);
491 else if (Constant *C = ConstantFoldInstruction(Inst)) {
492 Inst->replaceAllUsesWith(C);
493 (*BB)->getInstList().erase(Inst);
497 NumCompletelyUnrolled += CompletelyUnroll;