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 #include "llvm/Transforms/Utils/UnrollLoop.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/LoopIterator.h"
25 #include "llvm/Analysis/LoopPass.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Utils/LoopUtils.h"
38 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
41 #define DEBUG_TYPE "loop-unroll"
43 // TODO: Should these be here or in LoopUnroll?
44 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
45 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
47 /// RemapInstruction - Convert the instruction operands from referencing the
48 /// current values into those specified by VMap.
49 static inline void RemapInstruction(Instruction *I,
50 ValueToValueMapTy &VMap) {
51 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
52 Value *Op = I->getOperand(op);
53 ValueToValueMapTy::iterator It = VMap.find(Op);
55 I->setOperand(op, It->second);
58 if (PHINode *PN = dyn_cast<PHINode>(I)) {
59 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
60 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
62 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
67 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
68 /// only has one predecessor, and that predecessor only has one successor.
69 /// The LoopInfo Analysis that is passed will be kept consistent. If folding is
70 /// successful references to the containing loop must be removed from
71 /// ScalarEvolution by calling ScalarEvolution::forgetLoop because SE may have
72 /// references to the eliminated BB. The argument ForgottenLoops contains a set
73 /// of loops that have already been forgotten to prevent redundant, expensive
74 /// calls to ScalarEvolution::forgetLoop. Returns the new combined block.
76 FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI, LPPassManager *LPM,
77 SmallPtrSetImpl<Loop *> &ForgottenLoops) {
78 // Merge basic blocks into their predecessor if there is only one distinct
79 // pred, and if there is only one distinct successor of the predecessor, and
80 // if there are no PHI nodes.
81 BasicBlock *OnlyPred = BB->getSinglePredecessor();
82 if (!OnlyPred) return nullptr;
84 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
87 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
89 // Resolve any PHI nodes at the start of the block. They are all
90 // guaranteed to have exactly one entry if they exist, unless there are
91 // multiple duplicate (but guaranteed to be equal) entries for the
92 // incoming edges. This occurs when there are multiple edges from
93 // OnlyPred to OnlySucc.
94 FoldSingleEntryPHINodes(BB);
96 // Delete the unconditional branch from the predecessor...
97 OnlyPred->getInstList().pop_back();
99 // Make all PHI nodes that referred to BB now refer to Pred as their
101 BB->replaceAllUsesWith(OnlyPred);
103 // Move all definitions in the successor to the predecessor...
104 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
106 // OldName will be valid until erased.
107 StringRef OldName = BB->getName();
109 // Erase basic block from the function...
111 // ScalarEvolution holds references to loop exit blocks.
114 LPM->getAnalysisIfAvailable<ScalarEvolutionWrapperPass>()) {
115 if (Loop *L = LI->getLoopFor(BB)) {
116 if (ForgottenLoops.insert(L).second)
117 SEWP->getSE().forgetLoop(L);
123 // Inherit predecessor's name if it exists...
124 if (!OldName.empty() && !OnlyPred->hasName())
125 OnlyPred->setName(OldName);
127 BB->eraseFromParent();
132 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
133 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
134 /// can only fail when the loop's latch block is not terminated by a conditional
135 /// branch instruction. However, if the trip count (and multiple) are not known,
136 /// loop unrolling will mostly produce more code that is no faster.
138 /// TripCount is generally defined as the number of times the loop header
139 /// executes. UnrollLoop relaxes the definition to permit early exits: here
140 /// TripCount is the iteration on which control exits LatchBlock if no early
141 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
142 /// terminates LatchBlock in order to remove unnecesssary instances of the
143 /// test. In other words, control may exit the loop prior to TripCount
144 /// iterations via an early branch, but control may not exit the loop from the
145 /// LatchBlock's terminator prior to TripCount iterations.
147 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
148 /// execute without exiting the loop.
150 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
151 /// have a runtime (i.e. not compile time constant) trip count. Unrolling these
152 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
153 /// iterations before branching into the unrolled loop. UnrollLoop will not
154 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
155 /// AllowExpensiveTripCount is false.
157 /// The LoopInfo Analysis that is passed will be kept consistent.
159 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
160 /// removed from the LoopPassManager as well. LPM can also be NULL.
162 /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
163 /// available from the Pass it must also preserve those analyses.
164 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
165 bool AllowRuntime, bool AllowExpensiveTripCount,
166 unsigned TripMultiple, LoopInfo *LI, Pass *PP,
167 LPPassManager *LPM, AssumptionCache *AC) {
168 BasicBlock *Preheader = L->getLoopPreheader();
170 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
174 BasicBlock *LatchBlock = L->getLoopLatch();
176 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
180 // Loops with indirectbr cannot be cloned.
181 if (!L->isSafeToClone()) {
182 DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
186 BasicBlock *Header = L->getHeader();
187 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
189 if (!BI || BI->isUnconditional()) {
190 // The loop-rotate pass can be helpful to avoid this in many cases.
192 " Can't unroll; loop not terminated by a conditional branch.\n");
196 if (Header->hasAddressTaken()) {
197 // The loop-rotate pass can be helpful to avoid this in many cases.
199 " Won't unroll loop: address of header block is taken.\n");
204 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
205 if (TripMultiple != 1)
206 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
208 // Effectively "DCE" unrolled iterations that are beyond the tripcount
209 // and will never be executed.
210 if (TripCount != 0 && Count > TripCount)
213 // Don't enter the unroll code if there is nothing to do. This way we don't
214 // need to support "partial unrolling by 1".
215 if (TripCount == 0 && Count < 2)
219 assert(TripMultiple > 0);
220 assert(TripCount == 0 || TripCount % TripMultiple == 0);
222 // Are we eliminating the loop control altogether?
223 bool CompletelyUnroll = Count == TripCount;
225 // We assume a run-time trip count if the compiler cannot
226 // figure out the loop trip count and the unroll-runtime
227 // flag is specified.
228 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
230 if (RuntimeTripCount &&
231 !UnrollRuntimeLoopProlog(L, Count, AllowExpensiveTripCount, LI, LPM))
234 // Notify ScalarEvolution that the loop will be substantially changed,
235 // if not outright eliminated.
237 PP ? PP->getAnalysisIfAvailable<ScalarEvolutionWrapperPass>() : nullptr;
238 ScalarEvolution *SE = SEWP ? &SEWP->getSE() : nullptr;
242 // If we know the trip count, we know the multiple...
243 unsigned BreakoutTrip = 0;
244 if (TripCount != 0) {
245 BreakoutTrip = TripCount % Count;
248 // Figure out what multiple to use.
249 BreakoutTrip = TripMultiple =
250 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
253 // Report the unrolling decision.
254 DebugLoc LoopLoc = L->getStartLoc();
255 Function *F = Header->getParent();
256 LLVMContext &Ctx = F->getContext();
258 if (CompletelyUnroll) {
259 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
260 << " with trip count " << TripCount << "!\n");
261 emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
262 Twine("completely unrolled loop with ") +
263 Twine(TripCount) + " iterations");
265 auto EmitDiag = [&](const Twine &T) {
266 emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
267 "unrolled loop by a factor of " + Twine(Count) +
271 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
273 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
274 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
275 EmitDiag(" with a breakout at trip " + Twine(BreakoutTrip));
276 } else if (TripMultiple != 1) {
277 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
278 EmitDiag(" with " + Twine(TripMultiple) + " trips per branch");
279 } else if (RuntimeTripCount) {
280 DEBUG(dbgs() << " with run-time trip count");
281 EmitDiag(" with run-time trip count");
283 DEBUG(dbgs() << "!\n");
286 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
287 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
289 // For the first iteration of the loop, we should use the precloned values for
290 // PHI nodes. Insert associations now.
291 ValueToValueMapTy LastValueMap;
292 std::vector<PHINode*> OrigPHINode;
293 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
294 OrigPHINode.push_back(cast<PHINode>(I));
297 std::vector<BasicBlock*> Headers;
298 std::vector<BasicBlock*> Latches;
299 Headers.push_back(Header);
300 Latches.push_back(LatchBlock);
302 // The current on-the-fly SSA update requires blocks to be processed in
303 // reverse postorder so that LastValueMap contains the correct value at each
305 LoopBlocksDFS DFS(L);
308 // Stash the DFS iterators before adding blocks to the loop.
309 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
310 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
312 for (unsigned It = 1; It != Count; ++It) {
313 std::vector<BasicBlock*> NewBlocks;
314 SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
317 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
318 ValueToValueMapTy VMap;
319 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
320 Header->getParent()->getBasicBlockList().push_back(New);
322 // Tell LI about New.
324 assert(LI->getLoopFor(*BB) == L && "Header should not be in a sub-loop");
325 L->addBasicBlockToLoop(New, *LI);
327 // Figure out which loop New is in.
328 const Loop *OldLoop = LI->getLoopFor(*BB);
329 assert(OldLoop && "Should (at least) be in the loop being unrolled!");
331 Loop *&NewLoop = NewLoops[OldLoop];
333 // Found a new sub-loop.
334 assert(*BB == OldLoop->getHeader() &&
335 "Header should be first in RPO");
337 Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
338 assert(NewLoopParent &&
339 "Expected parent loop before sub-loop in RPO");
341 NewLoopParent->addChildLoop(NewLoop);
343 // Forget the old loop, since its inputs may have changed.
345 SE->forgetLoop(OldLoop);
347 NewLoop->addBasicBlockToLoop(New, *LI);
351 // Loop over all of the PHI nodes in the block, changing them to use
352 // the incoming values from the previous block.
353 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
354 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
355 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
356 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
357 if (It > 1 && L->contains(InValI))
358 InVal = LastValueMap[InValI];
359 VMap[OrigPHINode[i]] = InVal;
360 New->getInstList().erase(NewPHI);
363 // Update our running map of newest clones
364 LastValueMap[*BB] = New;
365 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
367 LastValueMap[VI->first] = VI->second;
369 // Add phi entries for newly created values to all exit blocks.
370 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
372 if (L->contains(*SI))
374 for (BasicBlock::iterator BBI = (*SI)->begin();
375 PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
376 Value *Incoming = phi->getIncomingValueForBlock(*BB);
377 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
378 if (It != LastValueMap.end())
379 Incoming = It->second;
380 phi->addIncoming(Incoming, New);
383 // Keep track of new headers and latches as we create them, so that
384 // we can insert the proper branches later.
386 Headers.push_back(New);
387 if (*BB == LatchBlock)
388 Latches.push_back(New);
390 NewBlocks.push_back(New);
393 // Remap all instructions in the most recent iteration
394 for (unsigned i = 0; i < NewBlocks.size(); ++i)
395 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
396 E = NewBlocks[i]->end(); I != E; ++I)
397 ::RemapInstruction(I, LastValueMap);
400 // Loop over the PHI nodes in the original block, setting incoming values.
401 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
402 PHINode *PN = OrigPHINode[i];
403 if (CompletelyUnroll) {
404 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
405 Header->getInstList().erase(PN);
407 else if (Count > 1) {
408 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
409 // If this value was defined in the loop, take the value defined by the
410 // last iteration of the loop.
411 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
412 if (L->contains(InValI))
413 InVal = LastValueMap[InVal];
415 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
416 PN->addIncoming(InVal, Latches.back());
420 // Now that all the basic blocks for the unrolled iterations are in place,
421 // set up the branches to connect them.
422 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
423 // The original branch was replicated in each unrolled iteration.
424 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
426 // The branch destination.
427 unsigned j = (i + 1) % e;
428 BasicBlock *Dest = Headers[j];
429 bool NeedConditional = true;
431 if (RuntimeTripCount && j != 0) {
432 NeedConditional = false;
435 // For a complete unroll, make the last iteration end with a branch
436 // to the exit block.
437 if (CompletelyUnroll && j == 0) {
439 NeedConditional = false;
442 // If we know the trip count or a multiple of it, we can safely use an
443 // unconditional branch for some iterations.
444 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
445 NeedConditional = false;
448 if (NeedConditional) {
449 // Update the conditional branch's successor for the following
451 Term->setSuccessor(!ContinueOnTrue, Dest);
453 // Remove phi operands at this loop exit
454 if (Dest != LoopExit) {
455 BasicBlock *BB = Latches[i];
456 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
458 if (*SI == Headers[i])
460 for (BasicBlock::iterator BBI = (*SI)->begin();
461 PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
462 Phi->removeIncomingValue(BB, false);
466 // Replace the conditional branch with an unconditional one.
467 BranchInst::Create(Dest, Term);
468 Term->eraseFromParent();
472 // Merge adjacent basic blocks, if possible.
473 SmallPtrSet<Loop *, 4> ForgottenLoops;
474 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
475 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
476 if (Term->isUnconditional()) {
477 BasicBlock *Dest = Term->getSuccessor(0);
478 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM,
480 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
484 // FIXME: We could register any cloned assumptions instead of clearing the
485 // whole function's cache.
488 DominatorTree *DT = nullptr;
490 // FIXME: Reconstruct dom info, because it is not preserved properly.
491 // Incrementally updating domtree after loop unrolling would be easy.
492 if (DominatorTreeWrapperPass *DTWP =
493 PP->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
494 DT = &DTWP->getDomTree();
495 DT->recalculate(*L->getHeader()->getParent());
498 // Simplify any new induction variables in the partially unrolled loop.
499 if (SE && !CompletelyUnroll) {
500 SmallVector<WeakVH, 16> DeadInsts;
501 simplifyLoopIVs(L, SE, LPM, DeadInsts);
503 // Aggressively clean up dead instructions that simplifyLoopIVs already
504 // identified. Any remaining should be cleaned up below.
505 while (!DeadInsts.empty())
506 if (Instruction *Inst =
507 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
508 RecursivelyDeleteTriviallyDeadInstructions(Inst);
511 // At this point, the code is well formed. We now do a quick sweep over the
512 // inserted code, doing constant propagation and dead code elimination as we
514 const DataLayout &DL = Header->getModule()->getDataLayout();
515 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
516 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
517 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
518 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
519 Instruction *Inst = I++;
521 if (isInstructionTriviallyDead(Inst))
522 (*BB)->getInstList().erase(Inst);
523 else if (Value *V = SimplifyInstruction(Inst, DL))
524 if (LI->replacementPreservesLCSSAForm(Inst, V)) {
525 Inst->replaceAllUsesWith(V);
526 (*BB)->getInstList().erase(Inst);
530 NumCompletelyUnrolled += CompletelyUnroll;
533 Loop *OuterL = L->getParentLoop();
534 // Remove the loop from the LoopPassManager if it's completely removed.
535 if (CompletelyUnroll && LPM != nullptr)
536 LPM->deleteLoopFromQueue(L);
538 // If we have a pass and a DominatorTree we should re-simplify impacted loops
539 // to ensure subsequent analyses can rely on this form. We want to simplify
540 // at least one layer outside of the loop that was unrolled so that any
541 // changes to the parent loop exposed by the unrolling are considered.
543 if (!OuterL && !CompletelyUnroll)
546 simplifyLoop(OuterL, DT, LI, PP, SE, AC);
548 // LCSSA must be performed on the outermost affected loop. The unrolled
549 // loop's last loop latch is guaranteed to be in the outermost loop after
550 // deleteLoopFromQueue updates LoopInfo.
551 Loop *LatchLoop = LI->getLoopFor(Latches.back());
552 if (!OuterL->contains(LatchLoop))
553 while (OuterL->getParentLoop() != LatchLoop)
554 OuterL = OuterL->getParentLoop();
556 formLCSSARecursively(*OuterL, *DT, LI, SE);
563 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
564 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
565 /// such metadata node exists, then nullptr is returned.
566 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
567 // First operand should refer to the loop id itself.
568 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
569 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
571 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
572 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
576 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
580 if (Name.equals(S->getString()))