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 // It works best when loops have been canonicalized by the -indvars pass,
15 // allowing it to determine the trip counts of loops easily.
17 // The process of unrolling can produce extraneous basic blocks linked with
18 // unconditional branches. This will be corrected in the future.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "loop-unroll"
22 #include "llvm/Transforms/Utils/UnrollLoop.h"
23 #include "llvm/BasicBlock.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/LoopPass.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"
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 ValueMap.
42 static inline void RemapInstruction(Instruction *I,
43 DenseMap<const Value *, Value*> &ValueMap) {
44 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
45 Value *Op = I->getOperand(op);
46 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
47 if (It != ValueMap.end())
48 I->setOperand(op, It->second);
52 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
53 /// only has one predecessor, and that predecessor only has one successor.
54 /// The LoopInfo Analysis that is passed will be kept consistent.
55 /// Returns the new combined block.
56 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI) {
57 // Merge basic blocks into their predecessor if there is only one distinct
58 // pred, and if there is only one distinct successor of the predecessor, and
59 // if there are no PHI nodes.
60 BasicBlock *OnlyPred = BB->getSinglePredecessor();
61 if (!OnlyPred) return 0;
63 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
66 DEBUG(errs() << "Merging: " << *BB << "into: " << *OnlyPred);
68 // Resolve any PHI nodes at the start of the block. They are all
69 // guaranteed to have exactly one entry if they exist, unless there are
70 // multiple duplicate (but guaranteed to be equal) entries for the
71 // incoming edges. This occurs when there are multiple edges from
72 // OnlyPred to OnlySucc.
73 FoldSingleEntryPHINodes(BB);
75 // Delete the unconditional branch from the predecessor...
76 OnlyPred->getInstList().pop_back();
78 // Move all definitions in the successor to the predecessor...
79 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
81 // Make all PHI nodes that referred to BB now refer to Pred as their
83 BB->replaceAllUsesWith(OnlyPred);
85 std::string OldName = BB->getName();
87 // Erase basic block from the function...
89 BB->eraseFromParent();
91 // Inherit predecessor's name if it exists...
92 if (!OldName.empty() && !OnlyPred->hasName())
93 OnlyPred->setName(OldName);
98 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
99 /// if unrolling was succesful, or false if the loop was unmodified. Unrolling
100 /// can only fail when the loop's latch block is not terminated by a conditional
101 /// branch instruction. However, if the trip count (and multiple) are not known,
102 /// loop unrolling will mostly produce more code that is no faster.
104 /// The LoopInfo Analysis that is passed will be kept consistent.
106 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
107 /// removed from the LoopPassManager as well. LPM can also be NULL.
108 bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {
109 assert(L->isLCSSAForm());
111 BasicBlock *Preheader = L->getLoopPreheader();
113 DEBUG(errs() << " Can't unroll; loop preheader-insertion failed.\n");
117 BasicBlock *LatchBlock = L->getLoopLatch();
119 DEBUG(errs() << " Can't unroll; loop exit-block-insertion failed.\n");
123 BasicBlock *Header = L->getHeader();
124 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
126 if (!BI || BI->isUnconditional()) {
127 // The loop-rotate pass can be helpful to avoid this in many cases.
129 " Can't unroll; loop not terminated by a conditional branch.\n");
134 unsigned TripCount = L->getSmallConstantTripCount();
135 // Find trip multiple if count is not available
136 unsigned TripMultiple = 1;
138 TripMultiple = L->getSmallConstantTripMultiple();
141 DEBUG(errs() << " Trip Count = " << TripCount << "\n");
142 if (TripMultiple != 1)
143 DEBUG(errs() << " Trip Multiple = " << TripMultiple << "\n");
145 // Effectively "DCE" unrolled iterations that are beyond the tripcount
146 // and will never be executed.
147 if (TripCount != 0 && Count > TripCount)
151 assert(TripMultiple > 0);
152 assert(TripCount == 0 || TripCount % TripMultiple == 0);
154 // Are we eliminating the loop control altogether?
155 bool CompletelyUnroll = Count == TripCount;
157 // If we know the trip count, we know the multiple...
158 unsigned BreakoutTrip = 0;
159 if (TripCount != 0) {
160 BreakoutTrip = TripCount % Count;
163 // Figure out what multiple to use.
164 BreakoutTrip = TripMultiple =
165 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
168 if (CompletelyUnroll) {
169 DEBUG(errs() << "COMPLETELY UNROLLING loop %" << Header->getName()
170 << " with trip count " << TripCount << "!\n");
172 DEBUG(errs() << "UNROLLING loop %" << Header->getName()
174 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
175 DEBUG(errs() << " with a breakout at trip " << BreakoutTrip);
176 } else if (TripMultiple != 1) {
177 DEBUG(errs() << " with " << TripMultiple << " trips per branch");
179 DEBUG(errs() << "!\n");
182 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
184 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
185 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
187 // For the first iteration of the loop, we should use the precloned values for
188 // PHI nodes. Insert associations now.
189 typedef DenseMap<const Value*, Value*> ValueMapTy;
190 ValueMapTy LastValueMap;
191 std::vector<PHINode*> OrigPHINode;
192 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
193 PHINode *PN = cast<PHINode>(I);
194 OrigPHINode.push_back(PN);
196 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
197 if (L->contains(I->getParent()))
201 std::vector<BasicBlock*> Headers;
202 std::vector<BasicBlock*> Latches;
203 Headers.push_back(Header);
204 Latches.push_back(LatchBlock);
206 for (unsigned It = 1; It != Count; ++It) {
207 char SuffixBuffer[100];
208 sprintf(SuffixBuffer, ".%d", It);
210 std::vector<BasicBlock*> NewBlocks;
212 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
213 E = LoopBlocks.end(); BB != E; ++BB) {
215 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
216 Header->getParent()->getBasicBlockList().push_back(New);
218 // Loop over all of the PHI nodes in the block, changing them to use the
219 // incoming values from the previous block.
221 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
222 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
223 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
224 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
225 if (It > 1 && L->contains(InValI->getParent()))
226 InVal = LastValueMap[InValI];
227 ValueMap[OrigPHINode[i]] = InVal;
228 New->getInstList().erase(NewPHI);
231 // Update our running map of newest clones
232 LastValueMap[*BB] = New;
233 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
235 LastValueMap[VI->first] = VI->second;
237 L->addBasicBlockToLoop(New, LI->getBase());
239 // Add phi entries for newly created values to all exit blocks except
240 // the successor of the latch block. The successor of the exit block will
241 // be updated specially after unrolling all the way.
242 if (*BB != LatchBlock)
243 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
245 Instruction *UseInst = cast<Instruction>(*UI);
247 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
248 PHINode *phi = cast<PHINode>(UseInst);
249 Value *Incoming = phi->getIncomingValueForBlock(*BB);
250 phi->addIncoming(Incoming, New);
254 // Keep track of new headers and latches as we create them, so that
255 // we can insert the proper branches later.
257 Headers.push_back(New);
258 if (*BB == LatchBlock) {
259 Latches.push_back(New);
261 // Also, clear out the new latch's back edge so that it doesn't look
262 // like a new loop, so that it's amenable to being merged with adjacent
264 TerminatorInst *Term = New->getTerminator();
265 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
266 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
267 Term->setSuccessor(!ContinueOnTrue, NULL);
270 NewBlocks.push_back(New);
273 // Remap all instructions in the most recent iteration
274 for (unsigned i = 0; i < NewBlocks.size(); ++i)
275 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
276 E = NewBlocks[i]->end(); I != E; ++I)
277 RemapInstruction(I, LastValueMap);
280 // The latch block exits the loop. If there are any PHI nodes in the
281 // successor blocks, update them to use the appropriate values computed as the
282 // last iteration of the loop.
284 SmallPtrSet<PHINode*, 8> Users;
285 for (Value::use_iterator UI = LatchBlock->use_begin(),
286 UE = LatchBlock->use_end(); UI != UE; ++UI)
287 if (PHINode *phi = dyn_cast<PHINode>(*UI))
290 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
291 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
294 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
295 // If this value was defined in the loop, take the value defined by the
296 // last iteration of the loop.
297 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
298 if (L->contains(InValI->getParent()))
299 InVal = LastValueMap[InVal];
301 PN->addIncoming(InVal, LastIterationBB);
305 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
306 // original block, setting them to their incoming values.
307 if (CompletelyUnroll) {
308 BasicBlock *Preheader = L->getLoopPreheader();
309 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
310 PHINode *PN = OrigPHINode[i];
311 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
312 Header->getInstList().erase(PN);
316 // Now that all the basic blocks for the unrolled iterations are in place,
317 // set up the branches to connect them.
318 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
319 // The original branch was replicated in each unrolled iteration.
320 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
322 // The branch destination.
323 unsigned j = (i + 1) % e;
324 BasicBlock *Dest = Headers[j];
325 bool NeedConditional = true;
327 // For a complete unroll, make the last iteration end with a branch
328 // to the exit block.
329 if (CompletelyUnroll && j == 0) {
331 NeedConditional = false;
334 // If we know the trip count or a multiple of it, we can safely use an
335 // unconditional branch for some iterations.
336 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
337 NeedConditional = false;
340 if (NeedConditional) {
341 // Update the conditional branch's successor for the following
343 Term->setSuccessor(!ContinueOnTrue, Dest);
345 Term->setUnconditionalDest(Dest);
346 // Merge adjacent basic blocks, if possible.
347 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) {
348 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
349 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
354 // At this point, the code is well formed. We now do a quick sweep over the
355 // inserted code, doing constant propagation and dead code elimination as we
357 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
358 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
359 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
360 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
361 Instruction *Inst = I++;
363 if (isInstructionTriviallyDead(Inst))
364 (*BB)->getInstList().erase(Inst);
365 else if (Constant *C = ConstantFoldInstruction(Inst)) {
366 Inst->replaceAllUsesWith(C);
367 (*BB)->getInstList().erase(Inst);
371 NumCompletelyUnrolled += CompletelyUnroll;
373 // Remove the loop from the LoopPassManager if it's completely removed.
374 if (CompletelyUnroll && LPM != NULL)
375 LPM->deleteLoopFromQueue(L);
377 // If we didn't completely unroll the loop, it should still be in LCSSA form.
378 if (!CompletelyUnroll)
379 assert(L->isLCSSAForm());