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/BasicBlock.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Cloning.h"
30 #include "llvm/Transforms/Utils/Local.h"
33 // TODO: Should these be here or in LoopUnroll?
34 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
35 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
37 /// RemapInstruction - Convert the instruction operands from referencing the
38 /// current values into those specified by VMap.
39 static inline void RemapInstruction(Instruction *I,
40 ValueToValueMapTy &VMap) {
41 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
42 Value *Op = I->getOperand(op);
43 ValueToValueMapTy::iterator It = VMap.find(Op);
45 I->setOperand(op, It->second);
48 if (PHINode *PN = dyn_cast<PHINode>(I)) {
49 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
50 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
52 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
57 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
58 /// only has one predecessor, and that predecessor only has one successor.
59 /// The LoopInfo Analysis that is passed will be kept consistent.
60 /// Returns the new combined block.
61 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
63 // Merge basic blocks into their predecessor if there is only one distinct
64 // pred, and if there is only one distinct successor of the predecessor, and
65 // if there are no PHI nodes.
66 BasicBlock *OnlyPred = BB->getSinglePredecessor();
67 if (!OnlyPred) return 0;
69 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
72 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
74 // Resolve any PHI nodes at the start of the block. They are all
75 // guaranteed to have exactly one entry if they exist, unless there are
76 // multiple duplicate (but guaranteed to be equal) entries for the
77 // incoming edges. This occurs when there are multiple edges from
78 // OnlyPred to OnlySucc.
79 FoldSingleEntryPHINodes(BB);
81 // Delete the unconditional branch from the predecessor...
82 OnlyPred->getInstList().pop_back();
84 // Make all PHI nodes that referred to BB now refer to Pred as their
86 BB->replaceAllUsesWith(OnlyPred);
88 // Move all definitions in the successor to the predecessor...
89 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
91 std::string OldName = BB->getName();
93 // Erase basic block from the function...
95 // ScalarEvolution holds references to loop exit blocks.
96 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
97 if (Loop *L = LI->getLoopFor(BB))
101 BB->eraseFromParent();
103 // Inherit predecessor's name if it exists...
104 if (!OldName.empty() && !OnlyPred->hasName())
105 OnlyPred->setName(OldName);
110 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
111 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
112 /// can only fail when the loop's latch block is not terminated by a conditional
113 /// branch instruction. However, if the trip count (and multiple) are not known,
114 /// loop unrolling will mostly produce more code that is no faster.
116 /// TripCount is generally defined as the number of times the loop header
117 /// executes. UnrollLoop relaxes the definition to permit early exits: here
118 /// TripCount is the iteration on which control exits LatchBlock if no early
119 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
120 /// terminates LatchBlock in order to remove unnecesssary instances of the
121 /// test. In other words, control may exit the loop prior to TripCount
122 /// iterations via an early branch, but control may not exit the loop from the
123 /// LatchBlock's terminator prior to TripCount iterations.
125 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
126 /// execute without exiting the loop.
128 /// The LoopInfo Analysis that is passed will be kept consistent.
130 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
131 /// removed from the LoopPassManager as well. LPM can also be NULL.
132 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
133 unsigned TripMultiple, LoopInfo *LI, LPPassManager *LPM) {
134 BasicBlock *Preheader = L->getLoopPreheader();
136 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
140 BasicBlock *LatchBlock = L->getLoopLatch();
142 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
146 BasicBlock *Header = L->getHeader();
147 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
149 if (!BI || BI->isUnconditional()) {
150 // The loop-rotate pass can be helpful to avoid this in many cases.
152 " Can't unroll; loop not terminated by a conditional branch.\n");
156 if (Header->hasAddressTaken()) {
157 // The loop-rotate pass can be helpful to avoid this in many cases.
159 " Won't unroll loop: address of header block is taken.\n");
163 // Notify ScalarEvolution that the loop will be substantially changed,
164 // if not outright eliminated.
165 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>())
169 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
170 if (TripMultiple != 1)
171 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
173 // Effectively "DCE" unrolled iterations that are beyond the tripcount
174 // and will never be executed.
175 if (TripCount != 0 && Count > TripCount)
179 assert(TripMultiple > 0);
180 assert(TripCount == 0 || TripCount % TripMultiple == 0);
182 // Are we eliminating the loop control altogether?
183 bool CompletelyUnroll = Count == TripCount;
185 // If we know the trip count, we know the multiple...
186 unsigned BreakoutTrip = 0;
187 if (TripCount != 0) {
188 BreakoutTrip = TripCount % Count;
191 // Figure out what multiple to use.
192 BreakoutTrip = TripMultiple =
193 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
196 if (CompletelyUnroll) {
197 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
198 << " with trip count " << TripCount << "!\n");
200 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
202 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
203 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
204 } else if (TripMultiple != 1) {
205 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
207 DEBUG(dbgs() << "!\n");
210 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
212 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
213 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
215 // For the first iteration of the loop, we should use the precloned values for
216 // PHI nodes. Insert associations now.
217 ValueToValueMapTy LastValueMap;
218 std::vector<PHINode*> OrigPHINode;
219 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
220 PHINode *PN = cast<PHINode>(I);
221 OrigPHINode.push_back(PN);
223 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
228 std::vector<BasicBlock*> Headers;
229 std::vector<BasicBlock*> Latches;
230 Headers.push_back(Header);
231 Latches.push_back(LatchBlock);
233 for (unsigned It = 1; It != Count; ++It) {
234 std::vector<BasicBlock*> NewBlocks;
236 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
237 E = LoopBlocks.end(); BB != E; ++BB) {
238 ValueToValueMapTy VMap;
239 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
240 Header->getParent()->getBasicBlockList().push_back(New);
242 // Loop over all of the PHI nodes in the block, changing them to use the
243 // incoming values from the previous block.
245 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
246 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
247 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
248 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
249 if (It > 1 && L->contains(InValI))
250 InVal = LastValueMap[InValI];
251 VMap[OrigPHINode[i]] = InVal;
252 New->getInstList().erase(NewPHI);
255 // Update our running map of newest clones
256 LastValueMap[*BB] = New;
257 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
259 LastValueMap[VI->first] = VI->second;
261 L->addBasicBlockToLoop(New, LI->getBase());
263 // Add phi entries for newly created values to all exit blocks except
264 // the successor of the latch block. The successor of the exit block will
265 // be updated specially after unrolling all the way.
266 if (*BB != LatchBlock)
267 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB); SI != SE;
269 if (!L->contains(*SI))
270 for (BasicBlock::iterator BBI = (*SI)->begin();
271 PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
272 Value *Incoming = phi->getIncomingValueForBlock(*BB);
273 phi->addIncoming(Incoming, New);
276 // Keep track of new headers and latches as we create them, so that
277 // we can insert the proper branches later.
279 Headers.push_back(New);
280 if (*BB == LatchBlock) {
281 Latches.push_back(New);
283 // Also, clear out the new latch's back edge so that it doesn't look
284 // like a new loop, so that it's amenable to being merged with adjacent
286 TerminatorInst *Term = New->getTerminator();
287 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
288 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
289 Term->setSuccessor(!ContinueOnTrue, NULL);
292 NewBlocks.push_back(New);
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)
299 ::RemapInstruction(I, LastValueMap);
302 // The latch block exits the loop. If there are any PHI nodes in the
303 // successor blocks, update them to use the appropriate values computed as the
304 // last iteration of the loop.
306 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
307 for (succ_iterator SI = succ_begin(LatchBlock), SE = succ_end(LatchBlock);
309 for (BasicBlock::iterator BBI = (*SI)->begin();
310 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
311 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
312 // If this value was defined in the loop, take the value defined by the
313 // last iteration of the loop.
314 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
315 if (L->contains(InValI))
316 InVal = LastValueMap[InVal];
318 PN->addIncoming(InVal, LastIterationBB);
323 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
324 // original block, setting them to their incoming values.
325 if (CompletelyUnroll) {
326 BasicBlock *Preheader = L->getLoopPreheader();
327 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
328 PHINode *PN = OrigPHINode[i];
329 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
330 Header->getInstList().erase(PN);
334 // Now that all the basic blocks for the unrolled iterations are in place,
335 // set up the branches to connect them.
336 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
337 // The original branch was replicated in each unrolled iteration.
338 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
340 // The branch destination.
341 unsigned j = (i + 1) % e;
342 BasicBlock *Dest = Headers[j];
343 bool NeedConditional = true;
345 // For a complete unroll, make the last iteration end with a branch
346 // to the exit block.
347 if (CompletelyUnroll && j == 0) {
349 NeedConditional = false;
352 // If we know the trip count or a multiple of it, we can safely use an
353 // unconditional branch for some iterations.
354 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
355 NeedConditional = false;
358 if (NeedConditional) {
359 // Update the conditional branch's successor for the following
361 Term->setSuccessor(!ContinueOnTrue, Dest);
363 // Replace the conditional branch with an unconditional one.
364 BranchInst::Create(Dest, Term);
365 Term->eraseFromParent();
369 // Merge adjacent basic blocks, if possible.
370 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
371 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
372 if (Term->isUnconditional()) {
373 BasicBlock *Dest = Term->getSuccessor(0);
374 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM))
375 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
379 // At this point, the code is well formed. We now do a quick sweep over the
380 // inserted code, doing constant propagation and dead code elimination as we
382 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
383 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
384 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
385 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
386 Instruction *Inst = I++;
388 if (isInstructionTriviallyDead(Inst))
389 (*BB)->getInstList().erase(Inst);
390 else if (Value *V = SimplifyInstruction(Inst))
391 if (LI->replacementPreservesLCSSAForm(Inst, V)) {
392 Inst->replaceAllUsesWith(V);
393 (*BB)->getInstList().erase(Inst);
397 NumCompletelyUnrolled += CompletelyUnroll;
399 // Remove the loop from the LoopPassManager if it's completely removed.
400 if (CompletelyUnroll && LPM != NULL)
401 LPM->deleteLoopFromQueue(L);