blob: 6b2c5916d1f2d546045577d179f195b501343837 [file] [log] [blame]
Dan Gohman45b31972008-05-14 00:24:14 +00001//===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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
12// unrolling.
13//
14// It works best when loops have been canonicalized by the -indvars pass,
15// allowing it to determine the trip counts of loops easily.
16//
17// The process of unrolling can produce extraneous basic blocks linked with
18// unconditional branches. This will be corrected in the future.
19//===----------------------------------------------------------------------===//
20
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"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000028#include "llvm/Support/raw_ostream.h"
Chris Lattner29874e02008-12-03 19:44:02 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman45b31972008-05-14 00:24:14 +000030#include "llvm/Transforms/Utils/Cloning.h"
31#include "llvm/Transforms/Utils/Local.h"
Duncan Sands4520dd22008-10-08 07:23:46 +000032#include <cstdio>
Dan Gohman45b31972008-05-14 00:24:14 +000033
34using namespace llvm;
35
Chris Lattner29874e02008-12-03 19:44:02 +000036// TODO: Should these be here or in LoopUnroll?
Dan Gohman45b31972008-05-14 00:24:14 +000037STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
38STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
39
40/// RemapInstruction - Convert the instruction operands from referencing the
41/// current values into those specified by ValueMap.
42static 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);
Dan Gohmanb56c9662009-10-31 14:46:50 +000047 if (It != ValueMap.end())
48 I->setOperand(op, It->second);
Dan Gohman45b31972008-05-14 00:24:14 +000049 }
50}
51
Dan Gohman438b5832009-10-31 17:33:01 +000052/// 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.
56static 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;
62
63 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
64 return 0;
65
66 DEBUG(errs() << "Merging: " << *BB << "into: " << *OnlyPred);
67
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);
74
75 // Delete the unconditional branch from the predecessor...
76 OnlyPred->getInstList().pop_back();
77
78 // Move all definitions in the successor to the predecessor...
79 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
80
81 // Make all PHI nodes that referred to BB now refer to Pred as their
82 // source...
83 BB->replaceAllUsesWith(OnlyPred);
84
85 std::string OldName = BB->getName();
86
87 // Erase basic block from the function...
88 LI->removeBlock(BB);
89 BB->eraseFromParent();
90
91 // Inherit predecessor's name if it exists...
92 if (!OldName.empty() && !OnlyPred->hasName())
93 OnlyPred->setName(OldName);
94
95 return OnlyPred;
96}
97
Dan Gohman45b31972008-05-14 00:24:14 +000098/// 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.
103///
104/// The LoopInfo Analysis that is passed will be kept consistent.
105///
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.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000108bool llvm::UnrollLoop(Loop *L, unsigned Count, LoopInfo* LI, LPPassManager* LPM) {
Dan Gohman45b31972008-05-14 00:24:14 +0000109 assert(L->isLCSSAForm());
110
Dan Gohman692ad8d2009-11-05 19:44:06 +0000111 BasicBlock *Preheader = L->getLoopPreheader();
112 if (!Preheader) {
113 DEBUG(errs() << " Can't unroll; loop preheader-insertion failed.\n");
114 return false;
115 }
116
Dan Gohman45b31972008-05-14 00:24:14 +0000117 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman692ad8d2009-11-05 19:44:06 +0000118 if (!LatchBlock) {
119 DEBUG(errs() << " Can't unroll; loop exit-block-insertion failed.\n");
120 return false;
121 }
122
123 BasicBlock *Header = L->getHeader();
Dan Gohman45b31972008-05-14 00:24:14 +0000124 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000125
Dan Gohman45b31972008-05-14 00:24:14 +0000126 if (!BI || BI->isUnconditional()) {
127 // The loop-rotate pass can be helpful to avoid this in many cases.
Chris Lattnerbdff5482009-08-23 04:37:46 +0000128 DEBUG(errs() <<
129 " Can't unroll; loop not terminated by a conditional branch.\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000130 return false;
131 }
132
133 // Find trip count
134 unsigned TripCount = L->getSmallConstantTripCount();
135 // Find trip multiple if count is not available
136 unsigned TripMultiple = 1;
137 if (TripCount == 0)
138 TripMultiple = L->getSmallConstantTripMultiple();
139
140 if (TripCount != 0)
Chris Lattnerbdff5482009-08-23 04:37:46 +0000141 DEBUG(errs() << " Trip Count = " << TripCount << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000142 if (TripMultiple != 1)
Chris Lattnerbdff5482009-08-23 04:37:46 +0000143 DEBUG(errs() << " Trip Multiple = " << TripMultiple << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000144
145 // Effectively "DCE" unrolled iterations that are beyond the tripcount
146 // and will never be executed.
147 if (TripCount != 0 && Count > TripCount)
148 Count = TripCount;
149
150 assert(Count > 0);
151 assert(TripMultiple > 0);
152 assert(TripCount == 0 || TripCount % TripMultiple == 0);
153
154 // Are we eliminating the loop control altogether?
155 bool CompletelyUnroll = Count == TripCount;
156
157 // If we know the trip count, we know the multiple...
158 unsigned BreakoutTrip = 0;
159 if (TripCount != 0) {
160 BreakoutTrip = TripCount % Count;
161 TripMultiple = 0;
162 } else {
163 // Figure out what multiple to use.
164 BreakoutTrip = TripMultiple =
165 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
166 }
167
168 if (CompletelyUnroll) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000169 DEBUG(errs() << "COMPLETELY UNROLLING loop %" << Header->getName()
170 << " with trip count " << TripCount << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000171 } else {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000172 DEBUG(errs() << "UNROLLING loop %" << Header->getName()
173 << " by " << Count);
Dan Gohman45b31972008-05-14 00:24:14 +0000174 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000175 DEBUG(errs() << " with a breakout at trip " << BreakoutTrip);
Dan Gohman45b31972008-05-14 00:24:14 +0000176 } else if (TripMultiple != 1) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000177 DEBUG(errs() << " with " << TripMultiple << " trips per branch");
Dan Gohman45b31972008-05-14 00:24:14 +0000178 }
Chris Lattnerbdff5482009-08-23 04:37:46 +0000179 DEBUG(errs() << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000180 }
181
182 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
183
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000184 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
Dan Gohman45b31972008-05-14 00:24:14 +0000185 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
186
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;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000191 std::vector<PHINode*> OrigPHINode;
Dan Gohman45b31972008-05-14 00:24:14 +0000192 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
193 PHINode *PN = cast<PHINode>(I);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000194 OrigPHINode.push_back(PN);
Dan Gohman45b31972008-05-14 00:24:14 +0000195 if (Instruction *I =
196 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
Dan Gohman92329c72009-12-18 01:24:09 +0000197 if (L->contains(I))
Dan Gohman45b31972008-05-14 00:24:14 +0000198 LastValueMap[I] = I;
199 }
200
201 std::vector<BasicBlock*> Headers;
202 std::vector<BasicBlock*> Latches;
203 Headers.push_back(Header);
204 Latches.push_back(LatchBlock);
205
206 for (unsigned It = 1; It != Count; ++It) {
207 char SuffixBuffer[100];
208 sprintf(SuffixBuffer, ".%d", It);
209
210 std::vector<BasicBlock*> NewBlocks;
211
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000212 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
213 E = LoopBlocks.end(); BB != E; ++BB) {
Dan Gohman45b31972008-05-14 00:24:14 +0000214 ValueMapTy ValueMap;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000215 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
216 Header->getParent()->getBasicBlockList().push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000217
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000218 // Loop over all of the PHI nodes in the block, changing them to use the
219 // incoming values from the previous block.
220 if (*BB == Header)
221 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
222 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
Dan Gohman45b31972008-05-14 00:24:14 +0000223 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
224 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
Dan Gohman92329c72009-12-18 01:24:09 +0000225 if (It > 1 && L->contains(InValI))
Dan Gohman45b31972008-05-14 00:24:14 +0000226 InVal = LastValueMap[InValI];
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000227 ValueMap[OrigPHINode[i]] = InVal;
Dan Gohman45b31972008-05-14 00:24:14 +0000228 New->getInstList().erase(NewPHI);
229 }
230
231 // Update our running map of newest clones
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000232 LastValueMap[*BB] = New;
Dan Gohman45b31972008-05-14 00:24:14 +0000233 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
234 VI != VE; ++VI)
235 LastValueMap[VI->first] = VI->second;
236
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000237 L->addBasicBlockToLoop(New, LI->getBase());
238
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();
244 UI != UE;) {
245 Instruction *UseInst = cast<Instruction>(*UI);
246 ++UI;
Dan Gohman92329c72009-12-18 01:24:09 +0000247 if (isa<PHINode>(UseInst) && !L->contains(UseInst)) {
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000248 PHINode *phi = cast<PHINode>(UseInst);
249 Value *Incoming = phi->getIncomingValueForBlock(*BB);
250 phi->addIncoming(Incoming, New);
251 }
Dan Gohman45b31972008-05-14 00:24:14 +0000252 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000253
254 // Keep track of new headers and latches as we create them, so that
255 // we can insert the proper branches later.
256 if (*BB == Header)
257 Headers.push_back(New);
258 if (*BB == LatchBlock) {
259 Latches.push_back(New);
260
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
263 // blocks later on.
264 TerminatorInst *Term = New->getTerminator();
265 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
266 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
267 Term->setSuccessor(!ContinueOnTrue, NULL);
Dan Gohman45b31972008-05-14 00:24:14 +0000268 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000269
270 NewBlocks.push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000271 }
272
273 // Remap all instructions in the most recent iteration
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000274 for (unsigned i = 0; i < NewBlocks.size(); ++i)
Dan Gohman45b31972008-05-14 00:24:14 +0000275 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
276 E = NewBlocks[i]->end(); I != E; ++I)
277 RemapInstruction(I, LastValueMap);
278 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000279
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.
283 if (Count != 1) {
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))
288 Users.insert(phi);
289
290 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
291 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
292 SI != SE; ++SI) {
293 PHINode *PN = *SI;
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)) {
Dan Gohman92329c72009-12-18 01:24:09 +0000298 if (L->contains(InValI))
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000299 InVal = LastValueMap[InVal];
300 }
301 PN->addIncoming(InVal, LastIterationBB);
302 }
303 }
304
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);
313 }
314 }
Dan Gohman45b31972008-05-14 00:24:14 +0000315
316 // Now that all the basic blocks for the unrolled iterations are in place,
317 // set up the branches to connect them.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000318 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
Dan Gohman45b31972008-05-14 00:24:14 +0000319 // The original branch was replicated in each unrolled iteration.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000320 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
Dan Gohman45b31972008-05-14 00:24:14 +0000321
322 // The branch destination.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000323 unsigned j = (i + 1) % e;
324 BasicBlock *Dest = Headers[j];
Dan Gohman45b31972008-05-14 00:24:14 +0000325 bool NeedConditional = true;
326
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000327 // For a complete unroll, make the last iteration end with a branch
328 // to the exit block.
329 if (CompletelyUnroll && j == 0) {
Dan Gohman45b31972008-05-14 00:24:14 +0000330 Dest = LoopExit;
331 NeedConditional = false;
332 }
333
334 // If we know the trip count or a multiple of it, we can safely use an
335 // unconditional branch for some iterations.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000336 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000337 NeedConditional = false;
338 }
339
340 if (NeedConditional) {
341 // Update the conditional branch's successor for the following
342 // iteration.
343 Term->setSuccessor(!ContinueOnTrue, Dest);
344 } else {
345 Term->setUnconditionalDest(Dest);
346 // Merge adjacent basic blocks, if possible.
Dan Gohman438b5832009-10-31 17:33:01 +0000347 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000348 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
349 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
350 }
351 }
352 }
353
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000354 // 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
356 // go.
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; ) {
Dan Gohman45b31972008-05-14 00:24:14 +0000361 Instruction *Inst = I++;
362
363 if (isInstructionTriviallyDead(Inst))
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000364 (*BB)->getInstList().erase(Inst);
Chris Lattner7b550cc2009-11-06 04:27:31 +0000365 else if (Constant *C = ConstantFoldInstruction(Inst)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000366 Inst->replaceAllUsesWith(C);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000367 (*BB)->getInstList().erase(Inst);
Dan Gohman45b31972008-05-14 00:24:14 +0000368 }
369 }
Dan Gohman45b31972008-05-14 00:24:14 +0000370
371 NumCompletelyUnrolled += CompletelyUnroll;
372 ++NumUnrolled;
373 // Remove the loop from the LoopPassManager if it's completely removed.
374 if (CompletelyUnroll && LPM != NULL)
375 LPM->deleteLoopFromQueue(L);
376
377 // If we didn't completely unroll the loop, it should still be in LCSSA form.
378 if (!CompletelyUnroll)
379 assert(L->isLCSSAForm());
380
381 return true;
382}