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/LoopIterator.h"
25 #include "llvm/Analysis/LoopPass.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Cloning.h"
31 #include "llvm/Transforms/Utils/Local.h"
34 // TODO: Should these be here or in LoopUnroll?
35 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
36 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
38 /// RemapInstruction - Convert the instruction operands from referencing the
39 /// current values into those specified by VMap.
40 static inline void RemapInstruction(Instruction *I,
41 ValueToValueMapTy &VMap) {
42 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
43 Value *Op = I->getOperand(op);
44 ValueToValueMapTy::iterator It = VMap.find(Op);
46 I->setOperand(op, It->second);
49 if (PHINode *PN = dyn_cast<PHINode>(I)) {
50 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
51 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
53 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
58 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
59 /// only has one predecessor, and that predecessor only has one successor.
60 /// The LoopInfo Analysis that is passed will be kept consistent.
61 /// Returns the new combined block.
62 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
64 // Merge basic blocks into their predecessor if there is only one distinct
65 // pred, and if there is only one distinct successor of the predecessor, and
66 // if there are no PHI nodes.
67 BasicBlock *OnlyPred = BB->getSinglePredecessor();
68 if (!OnlyPred) return 0;
70 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
73 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
75 // Resolve any PHI nodes at the start of the block. They are all
76 // guaranteed to have exactly one entry if they exist, unless there are
77 // multiple duplicate (but guaranteed to be equal) entries for the
78 // incoming edges. This occurs when there are multiple edges from
79 // OnlyPred to OnlySucc.
80 FoldSingleEntryPHINodes(BB);
82 // Delete the unconditional branch from the predecessor...
83 OnlyPred->getInstList().pop_back();
85 // Make all PHI nodes that referred to BB now refer to Pred as their
87 BB->replaceAllUsesWith(OnlyPred);
89 // Move all definitions in the successor to the predecessor...
90 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
92 std::string OldName = BB->getName();
94 // Erase basic block from the function...
96 // ScalarEvolution holds references to loop exit blocks.
97 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
98 if (Loop *L = LI->getLoopFor(BB))
102 BB->eraseFromParent();
104 // Inherit predecessor's name if it exists...
105 if (!OldName.empty() && !OnlyPred->hasName())
106 OnlyPred->setName(OldName);
111 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
112 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
113 /// can only fail when the loop's latch block is not terminated by a conditional
114 /// branch instruction. However, if the trip count (and multiple) are not known,
115 /// loop unrolling will mostly produce more code that is no faster.
117 /// TripCount is generally defined as the number of times the loop header
118 /// executes. UnrollLoop relaxes the definition to permit early exits: here
119 /// TripCount is the iteration on which control exits LatchBlock if no early
120 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
121 /// terminates LatchBlock in order to remove unnecesssary instances of the
122 /// test. In other words, control may exit the loop prior to TripCount
123 /// iterations via an early branch, but control may not exit the loop from the
124 /// LatchBlock's terminator prior to TripCount iterations.
126 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
127 /// execute without exiting the loop.
129 /// The LoopInfo Analysis that is passed will be kept consistent.
131 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
132 /// removed from the LoopPassManager as well. LPM can also be NULL.
133 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
134 unsigned TripMultiple, LoopInfo *LI, LPPassManager *LPM) {
135 BasicBlock *Preheader = L->getLoopPreheader();
137 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
141 BasicBlock *LatchBlock = L->getLoopLatch();
143 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
147 BasicBlock *Header = L->getHeader();
148 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
150 if (!BI || BI->isUnconditional()) {
151 // The loop-rotate pass can be helpful to avoid this in many cases.
153 " Can't unroll; loop not terminated by a conditional branch.\n");
157 if (Header->hasAddressTaken()) {
158 // The loop-rotate pass can be helpful to avoid this in many cases.
160 " Won't unroll loop: address of header block is taken.\n");
164 // Notify ScalarEvolution that the loop will be substantially changed,
165 // if not outright eliminated.
166 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>())
170 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
171 if (TripMultiple != 1)
172 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
174 // Effectively "DCE" unrolled iterations that are beyond the tripcount
175 // and will never be executed.
176 if (TripCount != 0 && Count > TripCount)
180 assert(TripMultiple > 0);
181 assert(TripCount == 0 || TripCount % TripMultiple == 0);
183 // Are we eliminating the loop control altogether?
184 bool CompletelyUnroll = Count == TripCount;
186 // If we know the trip count, we know the multiple...
187 unsigned BreakoutTrip = 0;
188 if (TripCount != 0) {
189 BreakoutTrip = TripCount % Count;
192 // Figure out what multiple to use.
193 BreakoutTrip = TripMultiple =
194 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
197 if (CompletelyUnroll) {
198 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
199 << " with trip count " << TripCount << "!\n");
201 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
203 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
204 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
205 } else if (TripMultiple != 1) {
206 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
208 DEBUG(dbgs() << "!\n");
211 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
213 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
214 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
216 // For the first iteration of the loop, we should use the precloned values for
217 // PHI nodes. Insert associations now.
218 ValueToValueMapTy LastValueMap;
219 std::vector<PHINode*> OrigPHINode;
220 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
221 OrigPHINode.push_back(cast<PHINode>(I));
224 std::vector<BasicBlock*> Headers;
225 std::vector<BasicBlock*> Latches;
226 Headers.push_back(Header);
227 Latches.push_back(LatchBlock);
229 // The current on-the-fly SSA update requires blocks to be processed in
230 // reverse postorder so that LastValueMap contains the correct value at each
232 LoopBlocksDFS DFS(L);
235 // Stash the DFS iterators before adding blocks to the loop.
236 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
237 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
239 for (unsigned It = 1; It != Count; ++It) {
240 std::vector<BasicBlock*> NewBlocks;
242 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
243 ValueToValueMapTy VMap;
244 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
245 Header->getParent()->getBasicBlockList().push_back(New);
247 // Loop over all of the PHI nodes in the block, changing them to use the
248 // incoming values from the previous block.
250 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
251 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
252 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
253 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
254 if (It > 1 && L->contains(InValI))
255 InVal = LastValueMap[InValI];
256 VMap[OrigPHINode[i]] = InVal;
257 New->getInstList().erase(NewPHI);
260 // Update our running map of newest clones
261 LastValueMap[*BB] = New;
262 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
264 LastValueMap[VI->first] = VI->second;
266 L->addBasicBlockToLoop(New, LI->getBase());
268 // Add phi entries for newly created values to all exit blocks.
269 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
271 if (L->contains(*SI))
273 for (BasicBlock::iterator BBI = (*SI)->begin();
274 PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
275 Value *Incoming = phi->getIncomingValueForBlock(*BB);
276 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
277 if (It != LastValueMap.end())
278 Incoming = It->second;
279 phi->addIncoming(Incoming, New);
282 // Keep track of new headers and latches as we create them, so that
283 // we can insert the proper branches later.
285 Headers.push_back(New);
286 if (*BB == LatchBlock)
287 Latches.push_back(New);
289 NewBlocks.push_back(New);
292 // Remap all instructions in the most recent iteration
293 for (unsigned i = 0; i < NewBlocks.size(); ++i)
294 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
295 E = NewBlocks[i]->end(); I != E; ++I)
296 ::RemapInstruction(I, LastValueMap);
299 // Loop over the PHI nodes in the original block, setting incoming values.
300 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
301 PHINode *PN = OrigPHINode[i];
302 if (CompletelyUnroll) {
303 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
304 Header->getInstList().erase(PN);
306 else if (Count > 1) {
307 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
308 // If this value was defined in the loop, take the value defined by the
309 // last iteration of the loop.
310 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
311 if (L->contains(InValI))
312 InVal = LastValueMap[InVal];
314 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
315 PN->addIncoming(InVal, Latches.back());
319 // Now that all the basic blocks for the unrolled iterations are in place,
320 // set up the branches to connect them.
321 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
322 // The original branch was replicated in each unrolled iteration.
323 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
325 // The branch destination.
326 unsigned j = (i + 1) % e;
327 BasicBlock *Dest = Headers[j];
328 bool NeedConditional = true;
330 // For a complete unroll, make the last iteration end with a branch
331 // to the exit block.
332 if (CompletelyUnroll && j == 0) {
334 NeedConditional = false;
337 // If we know the trip count or a multiple of it, we can safely use an
338 // unconditional branch for some iterations.
339 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
340 NeedConditional = false;
343 if (NeedConditional) {
344 // Update the conditional branch's successor for the following
346 Term->setSuccessor(!ContinueOnTrue, Dest);
348 // Remove phi operands at this loop exit
349 if (Dest != LoopExit) {
350 BasicBlock *BB = Latches[i];
351 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
353 if (*SI == Headers[i])
355 for (BasicBlock::iterator BBI = (*SI)->begin();
356 PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
357 Phi->removeIncomingValue(BB, false);
361 // Replace the conditional branch with an unconditional one.
362 BranchInst::Create(Dest, Term);
363 Term->eraseFromParent();
367 // Merge adjacent basic blocks, if possible.
368 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
369 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
370 if (Term->isUnconditional()) {
371 BasicBlock *Dest = Term->getSuccessor(0);
372 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM))
373 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
377 // At this point, the code is well formed. We now do a quick sweep over the
378 // inserted code, doing constant propagation and dead code elimination as we
380 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
381 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
382 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
383 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
384 Instruction *Inst = I++;
386 if (isInstructionTriviallyDead(Inst))
387 (*BB)->getInstList().erase(Inst);
388 else if (Value *V = SimplifyInstruction(Inst))
389 if (LI->replacementPreservesLCSSAForm(Inst, V)) {
390 Inst->replaceAllUsesWith(V);
391 (*BB)->getInstList().erase(Inst);
395 NumCompletelyUnrolled += CompletelyUnroll;
397 // Remove the loop from the LoopPassManager if it's completely removed.
398 if (CompletelyUnroll && LPM != NULL)
399 LPM->deleteLoopFromQueue(L);