1 //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements some loop unrolling utilities. It does not define any
11 // actual pass or policy, but provides a single function to perform loop
14 // The process of unrolling can produce extraneous basic blocks linked with
15 // unconditional branches. This will be corrected in the future.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "loop-unroll"
20 #include "llvm/Transforms/Utils/UnrollLoop.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/LoopIterator.h"
24 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Cloning.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
36 // TODO: Should these be here or in LoopUnroll?
37 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
38 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
40 /// RemapInstruction - Convert the instruction operands from referencing the
41 /// current values into those specified by VMap.
42 static inline void RemapInstruction(Instruction *I,
43 ValueToValueMapTy &VMap) {
44 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
45 Value *Op = I->getOperand(op);
46 ValueToValueMapTy::iterator It = VMap.find(Op);
48 I->setOperand(op, It->second);
51 if (PHINode *PN = dyn_cast<PHINode>(I)) {
52 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
53 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
55 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
60 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
61 /// only has one predecessor, and that predecessor only has one successor.
62 /// The LoopInfo Analysis that is passed will be kept consistent.
63 /// Returns the new combined block.
64 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
66 // Merge basic blocks into their predecessor if there is only one distinct
67 // pred, and if there is only one distinct successor of the predecessor, and
68 // if there are no PHI nodes.
69 BasicBlock *OnlyPred = BB->getSinglePredecessor();
70 if (!OnlyPred) return 0;
72 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
75 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
77 // Resolve any PHI nodes at the start of the block. They are all
78 // guaranteed to have exactly one entry if they exist, unless there are
79 // multiple duplicate (but guaranteed to be equal) entries for the
80 // incoming edges. This occurs when there are multiple edges from
81 // OnlyPred to OnlySucc.
82 FoldSingleEntryPHINodes(BB);
84 // Delete the unconditional branch from the predecessor...
85 OnlyPred->getInstList().pop_back();
87 // Make all PHI nodes that referred to BB now refer to Pred as their
89 BB->replaceAllUsesWith(OnlyPred);
91 // Move all definitions in the successor to the predecessor...
92 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
94 // OldName will be valid until erased.
95 StringRef OldName = BB->getName();
97 // Erase basic block from the function...
99 // ScalarEvolution holds references to loop exit blocks.
101 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
102 if (Loop *L = LI->getLoopFor(BB))
108 // Inherit predecessor's name if it exists...
109 if (!OldName.empty() && !OnlyPred->hasName())
110 OnlyPred->setName(OldName);
112 BB->eraseFromParent();
117 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
118 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
119 /// can only fail when the loop's latch block is not terminated by a conditional
120 /// branch instruction. However, if the trip count (and multiple) are not known,
121 /// loop unrolling will mostly produce more code that is no faster.
123 /// TripCount is generally defined as the number of times the loop header
124 /// executes. UnrollLoop relaxes the definition to permit early exits: here
125 /// TripCount is the iteration on which control exits LatchBlock if no early
126 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
127 /// terminates LatchBlock in order to remove unnecesssary instances of the
128 /// test. In other words, control may exit the loop prior to TripCount
129 /// iterations via an early branch, but control may not exit the loop from the
130 /// LatchBlock's terminator prior to TripCount iterations.
132 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
133 /// execute without exiting the loop.
135 /// The LoopInfo Analysis that is passed will be kept consistent.
137 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
138 /// removed from the LoopPassManager as well. LPM can also be NULL.
140 /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
141 /// available it must also preserve those analyses.
142 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
143 bool AllowRuntime, unsigned TripMultiple,
144 LoopInfo *LI, LPPassManager *LPM) {
145 BasicBlock *Preheader = L->getLoopPreheader();
147 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
151 BasicBlock *LatchBlock = L->getLoopLatch();
153 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
157 // Loops with indirectbr cannot be cloned.
158 if (!L->isSafeToClone()) {
159 DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
163 BasicBlock *Header = L->getHeader();
164 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
166 if (!BI || BI->isUnconditional()) {
167 // The loop-rotate pass can be helpful to avoid this in many cases.
169 " Can't unroll; loop not terminated by a conditional branch.\n");
173 if (Header->hasAddressTaken()) {
174 // The loop-rotate pass can be helpful to avoid this in many cases.
176 " Won't unroll loop: address of header block is taken.\n");
181 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
182 if (TripMultiple != 1)
183 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
185 // Effectively "DCE" unrolled iterations that are beyond the tripcount
186 // and will never be executed.
187 if (TripCount != 0 && Count > TripCount)
190 // Don't enter the unroll code if there is nothing to do. This way we don't
191 // need to support "partial unrolling by 1".
192 if (TripCount == 0 && Count < 2)
196 assert(TripMultiple > 0);
197 assert(TripCount == 0 || TripCount % TripMultiple == 0);
199 // Are we eliminating the loop control altogether?
200 bool CompletelyUnroll = Count == TripCount;
202 // We assume a run-time trip count if the compiler cannot
203 // figure out the loop trip count and the unroll-runtime
204 // flag is specified.
205 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
207 if (RuntimeTripCount && !UnrollRuntimeLoopProlog(L, Count, LI, LPM))
210 // Notify ScalarEvolution that the loop will be substantially changed,
211 // if not outright eliminated.
213 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
218 // If we know the trip count, we know the multiple...
219 unsigned BreakoutTrip = 0;
220 if (TripCount != 0) {
221 BreakoutTrip = TripCount % Count;
224 // Figure out what multiple to use.
225 BreakoutTrip = TripMultiple =
226 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
229 if (CompletelyUnroll) {
230 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
231 << " with trip count " << TripCount << "!\n");
233 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
235 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
236 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
237 } else if (TripMultiple != 1) {
238 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
239 } else if (RuntimeTripCount) {
240 DEBUG(dbgs() << " with run-time trip count");
242 DEBUG(dbgs() << "!\n");
245 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
246 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
248 // For the first iteration of the loop, we should use the precloned values for
249 // PHI nodes. Insert associations now.
250 ValueToValueMapTy LastValueMap;
251 std::vector<PHINode*> OrigPHINode;
252 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
253 OrigPHINode.push_back(cast<PHINode>(I));
256 std::vector<BasicBlock*> Headers;
257 std::vector<BasicBlock*> Latches;
258 Headers.push_back(Header);
259 Latches.push_back(LatchBlock);
261 // The current on-the-fly SSA update requires blocks to be processed in
262 // reverse postorder so that LastValueMap contains the correct value at each
264 LoopBlocksDFS DFS(L);
267 // Stash the DFS iterators before adding blocks to the loop.
268 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
269 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
271 for (unsigned It = 1; It != Count; ++It) {
272 std::vector<BasicBlock*> NewBlocks;
274 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
275 ValueToValueMapTy VMap;
276 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
277 Header->getParent()->getBasicBlockList().push_back(New);
279 // Loop over all of the PHI nodes in the block, changing them to use the
280 // incoming values from the previous block.
282 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
283 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
284 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
285 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
286 if (It > 1 && L->contains(InValI))
287 InVal = LastValueMap[InValI];
288 VMap[OrigPHINode[i]] = InVal;
289 New->getInstList().erase(NewPHI);
292 // Update our running map of newest clones
293 LastValueMap[*BB] = New;
294 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
296 LastValueMap[VI->first] = VI->second;
298 L->addBasicBlockToLoop(New, LI->getBase());
300 // Add phi entries for newly created values to all exit blocks.
301 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
303 if (L->contains(*SI))
305 for (BasicBlock::iterator BBI = (*SI)->begin();
306 PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
307 Value *Incoming = phi->getIncomingValueForBlock(*BB);
308 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
309 if (It != LastValueMap.end())
310 Incoming = It->second;
311 phi->addIncoming(Incoming, New);
314 // Keep track of new headers and latches as we create them, so that
315 // we can insert the proper branches later.
317 Headers.push_back(New);
318 if (*BB == LatchBlock)
319 Latches.push_back(New);
321 NewBlocks.push_back(New);
324 // Remap all instructions in the most recent iteration
325 for (unsigned i = 0; i < NewBlocks.size(); ++i)
326 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
327 E = NewBlocks[i]->end(); I != E; ++I)
328 ::RemapInstruction(I, LastValueMap);
331 // Loop over the PHI nodes in the original block, setting incoming values.
332 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
333 PHINode *PN = OrigPHINode[i];
334 if (CompletelyUnroll) {
335 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
336 Header->getInstList().erase(PN);
338 else if (Count > 1) {
339 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
340 // If this value was defined in the loop, take the value defined by the
341 // last iteration of the loop.
342 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
343 if (L->contains(InValI))
344 InVal = LastValueMap[InVal];
346 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
347 PN->addIncoming(InVal, Latches.back());
351 // Now that all the basic blocks for the unrolled iterations are in place,
352 // set up the branches to connect them.
353 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
354 // The original branch was replicated in each unrolled iteration.
355 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
357 // The branch destination.
358 unsigned j = (i + 1) % e;
359 BasicBlock *Dest = Headers[j];
360 bool NeedConditional = true;
362 if (RuntimeTripCount && j != 0) {
363 NeedConditional = false;
366 // For a complete unroll, make the last iteration end with a branch
367 // to the exit block.
368 if (CompletelyUnroll && j == 0) {
370 NeedConditional = false;
373 // If we know the trip count or a multiple of it, we can safely use an
374 // unconditional branch for some iterations.
375 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
376 NeedConditional = false;
379 if (NeedConditional) {
380 // Update the conditional branch's successor for the following
382 Term->setSuccessor(!ContinueOnTrue, Dest);
384 // Remove phi operands at this loop exit
385 if (Dest != LoopExit) {
386 BasicBlock *BB = Latches[i];
387 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
389 if (*SI == Headers[i])
391 for (BasicBlock::iterator BBI = (*SI)->begin();
392 PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
393 Phi->removeIncomingValue(BB, false);
397 // Replace the conditional branch with an unconditional one.
398 BranchInst::Create(Dest, Term);
399 Term->eraseFromParent();
403 // Merge adjacent basic blocks, if possible.
404 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
405 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
406 if (Term->isUnconditional()) {
407 BasicBlock *Dest = Term->getSuccessor(0);
408 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM))
409 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
414 // FIXME: Reconstruct dom info, because it is not preserved properly.
415 // Incrementally updating domtree after loop unrolling would be easy.
416 if (DominatorTree *DT = LPM->getAnalysisIfAvailable<DominatorTree>())
417 DT->runOnFunction(*L->getHeader()->getParent());
419 // Simplify any new induction variables in the partially unrolled loop.
420 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
421 if (SE && !CompletelyUnroll) {
422 SmallVector<WeakVH, 16> DeadInsts;
423 simplifyLoopIVs(L, SE, LPM, DeadInsts);
425 // Aggressively clean up dead instructions that simplifyLoopIVs already
426 // identified. Any remaining should be cleaned up below.
427 while (!DeadInsts.empty())
428 if (Instruction *Inst =
429 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
430 RecursivelyDeleteTriviallyDeadInstructions(Inst);
433 // At this point, the code is well formed. We now do a quick sweep over the
434 // inserted code, doing constant propagation and dead code elimination as we
436 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
437 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
438 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
439 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
440 Instruction *Inst = I++;
442 if (isInstructionTriviallyDead(Inst))
443 (*BB)->getInstList().erase(Inst);
444 else if (Value *V = SimplifyInstruction(Inst))
445 if (LI->replacementPreservesLCSSAForm(Inst, V)) {
446 Inst->replaceAllUsesWith(V);
447 (*BB)->getInstList().erase(Inst);
451 NumCompletelyUnrolled += CompletelyUnroll;
453 // Remove the loop from the LoopPassManager if it's completely removed.
454 if (CompletelyUnroll && LPM != NULL)
455 LPM->deleteLoopFromQueue(L);