blob: 5a40a09580571bf02ed591e959a3f0dfbbe8067c [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//
Dan Gohman45b31972008-05-14 00:24:14 +000014// The process of unrolling can produce extraneous basic blocks linked with
15// unconditional branches. This will be corrected in the future.
Chris Lattnerb298db72011-01-11 08:00:40 +000016//
Dan Gohman45b31972008-05-14 00:24:14 +000017//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "loop-unroll"
20#include "llvm/Transforms/Utils/UnrollLoop.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/ADT/Statistic.h"
Duncan Sandsb6133d12010-11-23 20:26:33 +000023#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohman45b31972008-05-14 00:24:14 +000024#include "llvm/Analysis/LoopPass.h"
Dan Gohman572365e2010-07-26 18:02:06 +000025#include "llvm/Analysis/ScalarEvolution.h"
Dan Gohman45b31972008-05-14 00:24:14 +000026#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000027#include "llvm/Support/raw_ostream.h"
Chris Lattner29874e02008-12-03 19:44:02 +000028#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman45b31972008-05-14 00:24:14 +000029#include "llvm/Transforms/Utils/Cloning.h"
30#include "llvm/Transforms/Utils/Local.h"
Dan Gohman45b31972008-05-14 00:24:14 +000031using namespace llvm;
32
Chris Lattner29874e02008-12-03 19:44:02 +000033// TODO: Should these be here or in LoopUnroll?
Dan Gohman45b31972008-05-14 00:24:14 +000034STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
Chris Lattnerb298db72011-01-11 08:00:40 +000035STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
Dan Gohman45b31972008-05-14 00:24:14 +000036
37/// RemapInstruction - Convert the instruction operands from referencing the
Devang Patel29d3dd82010-06-23 23:55:51 +000038/// current values into those specified by VMap.
Dan Gohman45b31972008-05-14 00:24:14 +000039static inline void RemapInstruction(Instruction *I,
Rafael Espindola1ed219a2010-10-13 01:36:30 +000040 ValueToValueMapTy &VMap) {
Dan Gohman45b31972008-05-14 00:24:14 +000041 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
42 Value *Op = I->getOperand(op);
Rafael Espindola1ed219a2010-10-13 01:36:30 +000043 ValueToValueMapTy::iterator It = VMap.find(Op);
Devang Patel29d3dd82010-06-23 23:55:51 +000044 if (It != VMap.end())
Dan Gohmanb56c9662009-10-31 14:46:50 +000045 I->setOperand(op, It->second);
Dan Gohman45b31972008-05-14 00:24:14 +000046 }
Jay Foad95c3e482011-06-23 09:09:15 +000047
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));
51 if (It != VMap.end())
52 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
53 }
54 }
Dan Gohman45b31972008-05-14 00:24:14 +000055}
56
Dan Gohman438b5832009-10-31 17:33:01 +000057/// 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.
Andrew Trick1009c322011-08-03 18:32:11 +000061static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
62 LPPassManager *LPM) {
Dan Gohman438b5832009-10-31 17:33:01 +000063 // 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;
68
69 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
70 return 0;
71
David Greenea9ad9c22010-01-05 01:26:41 +000072 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
Dan Gohman438b5832009-10-31 17:33:01 +000073
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);
80
81 // Delete the unconditional branch from the predecessor...
82 OnlyPred->getInstList().pop_back();
83
Dan Gohman438b5832009-10-31 17:33:01 +000084 // Make all PHI nodes that referred to BB now refer to Pred as their
85 // source...
86 BB->replaceAllUsesWith(OnlyPred);
87
Jay Foad95c3e482011-06-23 09:09:15 +000088 // Move all definitions in the successor to the predecessor...
89 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
90
Dan Gohman438b5832009-10-31 17:33:01 +000091 std::string OldName = BB->getName();
92
93 // Erase basic block from the function...
Andrew Trick1009c322011-08-03 18:32:11 +000094
95 // ScalarEvolution holds references to loop exit blocks.
96 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
97 if (Loop *L = LI->getLoopFor(BB))
98 SE->forgetLoop(L);
99 }
Dan Gohman438b5832009-10-31 17:33:01 +0000100 LI->removeBlock(BB);
101 BB->eraseFromParent();
102
103 // Inherit predecessor's name if it exists...
104 if (!OldName.empty() && !OnlyPred->hasName())
105 OnlyPred->setName(OldName);
106
107 return OnlyPred;
108}
109
Dan Gohman45b31972008-05-14 00:24:14 +0000110/// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
Chris Lattnerf5ebfb02011-02-18 04:25:21 +0000111/// if unrolling was successful, or false if the loop was unmodified. Unrolling
Dan Gohman45b31972008-05-14 00:24:14 +0000112/// 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.
115///
Andrew Trick478849e2011-07-25 22:17:47 +0000116/// 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.
124///
125/// Similarly, TripMultiple divides the number of times that the LatchBlock may
126/// execute without exiting the loop.
127///
Dan Gohman45b31972008-05-14 00:24:14 +0000128/// The LoopInfo Analysis that is passed will be kept consistent.
129///
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.
Andrew Trick2045ce12011-07-23 00:33:05 +0000132bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
133 unsigned TripMultiple, LoopInfo *LI, LPPassManager *LPM) {
Dan Gohman692ad8d2009-11-05 19:44:06 +0000134 BasicBlock *Preheader = L->getLoopPreheader();
135 if (!Preheader) {
David Greenea9ad9c22010-01-05 01:26:41 +0000136 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
Dan Gohman692ad8d2009-11-05 19:44:06 +0000137 return false;
138 }
139
Dan Gohman45b31972008-05-14 00:24:14 +0000140 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman692ad8d2009-11-05 19:44:06 +0000141 if (!LatchBlock) {
David Greenea9ad9c22010-01-05 01:26:41 +0000142 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
Dan Gohman692ad8d2009-11-05 19:44:06 +0000143 return false;
144 }
145
146 BasicBlock *Header = L->getHeader();
Dan Gohman45b31972008-05-14 00:24:14 +0000147 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Andrew Trickba033772011-07-23 00:29:16 +0000148
Dan Gohman45b31972008-05-14 00:24:14 +0000149 if (!BI || BI->isUnconditional()) {
150 // The loop-rotate pass can be helpful to avoid this in many cases.
David Greenea9ad9c22010-01-05 01:26:41 +0000151 DEBUG(dbgs() <<
Chris Lattnerbdff5482009-08-23 04:37:46 +0000152 " Can't unroll; loop not terminated by a conditional branch.\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000153 return false;
154 }
Andrew Trickba033772011-07-23 00:29:16 +0000155
Chris Lattnerf5ebfb02011-02-18 04:25:21 +0000156 if (Header->hasAddressTaken()) {
157 // The loop-rotate pass can be helpful to avoid this in many cases.
158 DEBUG(dbgs() <<
159 " Won't unroll loop: address of header block is taken.\n");
160 return false;
161 }
Dan Gohman45b31972008-05-14 00:24:14 +0000162
Dan Gohman572365e2010-07-26 18:02:06 +0000163 // Notify ScalarEvolution that the loop will be substantially changed,
164 // if not outright eliminated.
165 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>())
166 SE->forgetLoop(L);
167
Dan Gohman45b31972008-05-14 00:24:14 +0000168 if (TripCount != 0)
David Greenea9ad9c22010-01-05 01:26:41 +0000169 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000170 if (TripMultiple != 1)
David Greenea9ad9c22010-01-05 01:26:41 +0000171 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000172
173 // Effectively "DCE" unrolled iterations that are beyond the tripcount
174 // and will never be executed.
175 if (TripCount != 0 && Count > TripCount)
176 Count = TripCount;
177
178 assert(Count > 0);
179 assert(TripMultiple > 0);
180 assert(TripCount == 0 || TripCount % TripMultiple == 0);
181
182 // Are we eliminating the loop control altogether?
183 bool CompletelyUnroll = Count == TripCount;
184
185 // If we know the trip count, we know the multiple...
186 unsigned BreakoutTrip = 0;
187 if (TripCount != 0) {
188 BreakoutTrip = TripCount % Count;
189 TripMultiple = 0;
190 } else {
191 // Figure out what multiple to use.
192 BreakoutTrip = TripMultiple =
193 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
194 }
195
196 if (CompletelyUnroll) {
David Greenea9ad9c22010-01-05 01:26:41 +0000197 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000198 << " with trip count " << TripCount << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000199 } else {
David Greenea9ad9c22010-01-05 01:26:41 +0000200 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000201 << " by " << Count);
Dan Gohman45b31972008-05-14 00:24:14 +0000202 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
David Greenea9ad9c22010-01-05 01:26:41 +0000203 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
Dan Gohman45b31972008-05-14 00:24:14 +0000204 } else if (TripMultiple != 1) {
David Greenea9ad9c22010-01-05 01:26:41 +0000205 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
Dan Gohman45b31972008-05-14 00:24:14 +0000206 }
David Greenea9ad9c22010-01-05 01:26:41 +0000207 DEBUG(dbgs() << "!\n");
Dan Gohman45b31972008-05-14 00:24:14 +0000208 }
209
210 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
211
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000212 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
Dan Gohman45b31972008-05-14 00:24:14 +0000213 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
214
215 // For the first iteration of the loop, we should use the precloned values for
216 // PHI nodes. Insert associations now.
Devang Patel39430842010-04-20 22:24:18 +0000217 ValueToValueMapTy LastValueMap;
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000218 std::vector<PHINode*> OrigPHINode;
Dan Gohman45b31972008-05-14 00:24:14 +0000219 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
220 PHINode *PN = cast<PHINode>(I);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000221 OrigPHINode.push_back(PN);
Andrew Trickba033772011-07-23 00:29:16 +0000222 if (Instruction *I =
Dan Gohman45b31972008-05-14 00:24:14 +0000223 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
Dan Gohman92329c72009-12-18 01:24:09 +0000224 if (L->contains(I))
Dan Gohman45b31972008-05-14 00:24:14 +0000225 LastValueMap[I] = I;
226 }
227
228 std::vector<BasicBlock*> Headers;
229 std::vector<BasicBlock*> Latches;
230 Headers.push_back(Header);
231 Latches.push_back(LatchBlock);
232
233 for (unsigned It = 1; It != Count; ++It) {
Dan Gohman45b31972008-05-14 00:24:14 +0000234 std::vector<BasicBlock*> NewBlocks;
Andrew Trickba033772011-07-23 00:29:16 +0000235
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000236 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
237 E = LoopBlocks.end(); BB != E; ++BB) {
Devang Patel29d3dd82010-06-23 23:55:51 +0000238 ValueToValueMapTy VMap;
239 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000240 Header->getParent()->getBasicBlockList().push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000241
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000242 // Loop over all of the PHI nodes in the block, changing them to use the
243 // incoming values from the previous block.
244 if (*BB == Header)
245 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
Devang Patel29d3dd82010-06-23 23:55:51 +0000246 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
Dan Gohman45b31972008-05-14 00:24:14 +0000247 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
248 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
Dan Gohman92329c72009-12-18 01:24:09 +0000249 if (It > 1 && L->contains(InValI))
Dan Gohman45b31972008-05-14 00:24:14 +0000250 InVal = LastValueMap[InValI];
Devang Patel29d3dd82010-06-23 23:55:51 +0000251 VMap[OrigPHINode[i]] = InVal;
Dan Gohman45b31972008-05-14 00:24:14 +0000252 New->getInstList().erase(NewPHI);
253 }
254
255 // Update our running map of newest clones
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000256 LastValueMap[*BB] = New;
Devang Patel29d3dd82010-06-23 23:55:51 +0000257 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
Dan Gohman45b31972008-05-14 00:24:14 +0000258 VI != VE; ++VI)
259 LastValueMap[VI->first] = VI->second;
260
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000261 L->addBasicBlockToLoop(New, LI->getBase());
262
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)
Jay Foad95c3e482011-06-23 09:09:15 +0000267 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB); SI != SE;
268 ++SI)
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);
274 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000275
276 // Keep track of new headers and latches as we create them, so that
277 // we can insert the proper branches later.
278 if (*BB == Header)
279 Headers.push_back(New);
280 if (*BB == LatchBlock) {
281 Latches.push_back(New);
282
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
285 // blocks later on.
286 TerminatorInst *Term = New->getTerminator();
287 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
288 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
289 Term->setSuccessor(!ContinueOnTrue, NULL);
Dan Gohman45b31972008-05-14 00:24:14 +0000290 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000291
292 NewBlocks.push_back(New);
Dan Gohman45b31972008-05-14 00:24:14 +0000293 }
Andrew Trickba033772011-07-23 00:29:16 +0000294
Dan Gohman45b31972008-05-14 00:24:14 +0000295 // Remap all instructions in the most recent iteration
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000296 for (unsigned i = 0; i < NewBlocks.size(); ++i)
Dan Gohman45b31972008-05-14 00:24:14 +0000297 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
298 E = NewBlocks[i]->end(); I != E; ++I)
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000299 ::RemapInstruction(I, LastValueMap);
Dan Gohman45b31972008-05-14 00:24:14 +0000300 }
Andrew Trickba033772011-07-23 00:29:16 +0000301
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000302 // 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.
305 if (Count != 1) {
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000306 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
Jay Foad95c3e482011-06-23 09:09:15 +0000307 for (succ_iterator SI = succ_begin(LatchBlock), SE = succ_end(LatchBlock);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000308 SI != SE; ++SI) {
Jay Foad95c3e482011-06-23 09:09:15 +0000309 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];
317 }
318 PN->addIncoming(InVal, LastIterationBB);
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000319 }
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000320 }
321 }
322
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);
331 }
332 }
Dan Gohman45b31972008-05-14 00:24:14 +0000333
334 // Now that all the basic blocks for the unrolled iterations are in place,
335 // set up the branches to connect them.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000336 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
Dan Gohman45b31972008-05-14 00:24:14 +0000337 // The original branch was replicated in each unrolled iteration.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000338 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
Dan Gohman45b31972008-05-14 00:24:14 +0000339
340 // The branch destination.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000341 unsigned j = (i + 1) % e;
342 BasicBlock *Dest = Headers[j];
Dan Gohman45b31972008-05-14 00:24:14 +0000343 bool NeedConditional = true;
344
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000345 // For a complete unroll, make the last iteration end with a branch
346 // to the exit block.
347 if (CompletelyUnroll && j == 0) {
Dan Gohman45b31972008-05-14 00:24:14 +0000348 Dest = LoopExit;
349 NeedConditional = false;
350 }
351
352 // If we know the trip count or a multiple of it, we can safely use an
353 // unconditional branch for some iterations.
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000354 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
Dan Gohman45b31972008-05-14 00:24:14 +0000355 NeedConditional = false;
356 }
357
358 if (NeedConditional) {
359 // Update the conditional branch's successor for the following
360 // iteration.
361 Term->setSuccessor(!ContinueOnTrue, Dest);
362 } else {
Jay Foad8f9ffbd2011-01-07 20:25:56 +0000363 // Replace the conditional branch with an unconditional one.
364 BranchInst::Create(Dest, Term);
365 Term->eraseFromParent();
Jay Foadcd35e092011-06-21 10:33:19 +0000366 }
367 }
368
Jay Foad95c3e482011-06-23 09:09:15 +0000369 // 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);
Andrew Trick1009c322011-08-03 18:32:11 +0000374 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM))
Jay Foad95c3e482011-06-23 09:09:15 +0000375 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
376 }
377 }
Andrew Trickba033772011-07-23 00:29:16 +0000378
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000379 // 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
381 // go.
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; ) {
Dan Gohman45b31972008-05-14 00:24:14 +0000386 Instruction *Inst = I++;
387
388 if (isInstructionTriviallyDead(Inst))
Dan Gohman8dbe7f82008-06-24 20:44:42 +0000389 (*BB)->getInstList().erase(Inst);
Duncan Sandsb6133d12010-11-23 20:26:33 +0000390 else if (Value *V = SimplifyInstruction(Inst))
391 if (LI->replacementPreservesLCSSAForm(Inst, V)) {
392 Inst->replaceAllUsesWith(V);
393 (*BB)->getInstList().erase(Inst);
394 }
Dan Gohman45b31972008-05-14 00:24:14 +0000395 }
Dan Gohman45b31972008-05-14 00:24:14 +0000396
397 NumCompletelyUnrolled += CompletelyUnroll;
398 ++NumUnrolled;
399 // Remove the loop from the LoopPassManager if it's completely removed.
400 if (CompletelyUnroll && LPM != NULL)
401 LPM->deleteLoopFromQueue(L);
402
Dan Gohman45b31972008-05-14 00:24:14 +0000403 return true;
404}