blob: 71a5955b76b0d8d82b09d9a751872645570f6a55 [file] [log] [blame]
Chris Lattner946b2552004-04-18 05:20:17 +00001//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner946b2552004-04-18 05:20:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner946b2552004-04-18 05:20:17 +00008//===----------------------------------------------------------------------===//
9//
10// This pass implements a simple loop unroller. It works best when loops have
11// been canonicalized by the -indvars pass, allowing it to determine the trip
12// counts of loops easily.
13//
Owen Andersone001d812006-08-24 21:28:19 +000014// This pass will multi-block loops only if they contain no non-unrolled
15// subloops. The process of unrolling can produce extraneous basic blocks
16// linked with unconditional branches. This will be corrected in the future.
Chris Lattner946b2552004-04-18 05:20:17 +000017//
18//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "loop-unroll"
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Constants.h"
23#include "llvm/Function.h"
24#include "llvm/Instructions.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner946b2552004-04-18 05:20:17 +000026#include "llvm/Analysis/LoopInfo.h"
Devang Patel9779e562007-03-07 01:38:05 +000027#include "llvm/Analysis/LoopPass.h"
Chris Lattner946b2552004-04-18 05:20:17 +000028#include "llvm/Transforms/Utils/Cloning.h"
29#include "llvm/Transforms/Utils/Local.h"
Owen Anderson62c84fe2006-08-28 02:09:46 +000030#include "llvm/Support/CFG.h"
Reid Spencer557ab152007-02-05 23:32:05 +000031#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Dan Gohman2980d9d2007-05-11 20:53:41 +000034#include "llvm/Support/MathExtras.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000035#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
Chris Lattner1bfc7ab2007-02-03 00:08:31 +000037#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner6d048a02004-11-22 17:18:36 +000038#include "llvm/IntrinsicInst.h"
Reid Spencerce078332004-10-18 14:38:48 +000039#include <algorithm>
Anton Korobeynikov579f0712008-02-20 11:08:44 +000040#include <climits>
41#include <cstdio>
Chris Lattner946b2552004-04-18 05:20:17 +000042using namespace llvm;
43
Dan Gohman2980d9d2007-05-11 20:53:41 +000044STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
Chris Lattner27406942007-08-02 16:53:43 +000045STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
Chris Lattner946b2552004-04-18 05:20:17 +000046
Chris Lattner79a42ac2006-12-19 21:40:18 +000047namespace {
Chris Lattner946b2552004-04-18 05:20:17 +000048 cl::opt<unsigned>
Dan Gohman2980d9d2007-05-11 20:53:41 +000049 UnrollThreshold
50 ("unroll-threshold", cl::init(100), cl::Hidden,
51 cl::desc("The cut-off point for automatic loop unrolling"));
52
53 cl::opt<unsigned>
54 UnrollCount
55 ("unroll-count", cl::init(0), cl::Hidden,
56 cl::desc("Use this unroll count for all loops, for testing purposes"));
Chris Lattner946b2552004-04-18 05:20:17 +000057
Devang Patel9779e562007-03-07 01:38:05 +000058 class VISIBILITY_HIDDEN LoopUnroll : public LoopPass {
Chris Lattner946b2552004-04-18 05:20:17 +000059 LoopInfo *LI; // The current loop information
60 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000061 static char ID; // Pass ID, replacement for typeid
Dan Gohman2e1f8042007-05-08 15:19:19 +000062 LoopUnroll() : LoopPass((intptr_t)&ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +000063
Dan Gohman2980d9d2007-05-11 20:53:41 +000064 /// A magic value for use with the Threshold parameter to indicate
65 /// that the loop unroll should be performed regardless of how much
66 /// code expansion would result.
67 static const unsigned NoThreshold = UINT_MAX;
68
Devang Patel9779e562007-03-07 01:38:05 +000069 bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman2980d9d2007-05-11 20:53:41 +000070 bool unrollLoop(Loop *L, unsigned Count, unsigned Threshold);
Dan Gohman2e1f8042007-05-08 15:19:19 +000071 BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB);
Chris Lattner946b2552004-04-18 05:20:17 +000072
73 /// This transformation requires natural loop information & requires that
74 /// loop preheaders be inserted into the CFG...
75 ///
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner946b2552004-04-18 05:20:17 +000077 AU.addRequiredID(LoopSimplifyID);
Owen Andersone001d812006-08-24 21:28:19 +000078 AU.addRequiredID(LCSSAID);
Chris Lattner946b2552004-04-18 05:20:17 +000079 AU.addRequired<LoopInfo>();
Owen Andersone001d812006-08-24 21:28:19 +000080 AU.addPreservedID(LCSSAID);
Chris Lattnerf2cc8412004-04-18 05:38:37 +000081 AU.addPreserved<LoopInfo>();
Chris Lattner946b2552004-04-18 05:20:17 +000082 }
83 };
Devang Patel8c78a0b2007-05-03 01:11:54 +000084 char LoopUnroll::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +000085 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
Chris Lattner946b2552004-04-18 05:20:17 +000086}
87
Devang Patel9779e562007-03-07 01:38:05 +000088LoopPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
Chris Lattner946b2552004-04-18 05:20:17 +000089
Dan Gohman49d08a52007-05-08 15:14:19 +000090/// ApproximateLoopSize - Approximate the size of the loop.
Chris Lattner946b2552004-04-18 05:20:17 +000091static unsigned ApproximateLoopSize(const Loop *L) {
92 unsigned Size = 0;
93 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
94 BasicBlock *BB = L->getBlocks()[i];
95 Instruction *Term = BB->getTerminator();
96 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
97 if (isa<PHINode>(I) && BB == L->getHeader()) {
98 // Ignore PHI nodes in the header.
99 } else if (I->hasOneUse() && I->use_back() == Term) {
100 // Ignore instructions only used by the loop terminator.
Reid Spencerde46e482006-11-02 20:25:50 +0000101 } else if (isa<DbgInfoIntrinsic>(I)) {
Jeff Cohen82639852005-04-23 21:38:35 +0000102 // Ignore debug instructions
Devang Patel924ca7f2008-03-17 23:41:20 +0000103 } else if (isa<CallInst>(I)) {
104 if (isa<IntrinsicInst>(I))
105 Size = Size + 3;
106 else
107 Size = Size + 10;
Chris Lattner946b2552004-04-18 05:20:17 +0000108 } else {
109 ++Size;
110 }
111
112 // TODO: Ignore expressions derived from PHI and constants if inval of phi
113 // is a constant, or if operation is associative. This will get induction
114 // variables.
115 }
116 }
117
118 return Size;
119}
120
Misha Brukmanb1c93172005-04-21 23:48:37 +0000121// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner946b2552004-04-18 05:20:17 +0000122// current values into those specified by ValueMap.
123//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000124static inline void RemapInstruction(Instruction *I,
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000125 DenseMap<const Value *, Value*> &ValueMap) {
Chris Lattner946b2552004-04-18 05:20:17 +0000126 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
127 Value *Op = I->getOperand(op);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000128 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
Chris Lattner946b2552004-04-18 05:20:17 +0000129 if (It != ValueMap.end()) Op = It->second;
130 I->setOperand(op, Op);
131 }
132}
133
Owen Anderson62c84fe2006-08-28 02:09:46 +0000134// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
135// only has one predecessor, and that predecessor only has one successor.
136// Returns the new combined block.
Dan Gohman2e1f8042007-05-08 15:19:19 +0000137BasicBlock *LoopUnroll::FoldBlockIntoPredecessor(BasicBlock *BB) {
Owen Anderson62c84fe2006-08-28 02:09:46 +0000138 // Merge basic blocks into their predecessor if there is only one distinct
139 // pred, and if there is only one distinct successor of the predecessor, and
140 // if there are no PHI nodes.
141 //
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000142 BasicBlock *OnlyPred = BB->getSinglePredecessor();
143 if (!OnlyPred) return 0;
Owen Anderson62c84fe2006-08-28 02:09:46 +0000144
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000145 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
146 return 0;
147
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000148 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000149
150 // Resolve any PHI nodes at the start of the block. They are all
151 // guaranteed to have exactly one entry if they exist, unless there are
152 // multiple duplicate (but guaranteed to be equal) entries for the
153 // incoming edges. This occurs when there are multiple edges from
154 // OnlyPred to OnlySucc.
155 //
156 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
157 PN->replaceAllUsesWith(PN->getIncomingValue(0));
158 BB->getInstList().pop_front(); // Delete the phi node...
Owen Anderson62c84fe2006-08-28 02:09:46 +0000159 }
160
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000161 // Delete the unconditional branch from the predecessor...
162 OnlyPred->getInstList().pop_back();
Owen Anderson62c84fe2006-08-28 02:09:46 +0000163
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000164 // Move all definitions in the successor to the predecessor...
165 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Owen Anderson62c84fe2006-08-28 02:09:46 +0000166
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000167 // Make all PHI nodes that referred to BB now refer to Pred as their
168 // source...
169 BB->replaceAllUsesWith(OnlyPred);
Owen Anderson62c84fe2006-08-28 02:09:46 +0000170
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000171 std::string OldName = BB->getName();
Owen Anderson62c84fe2006-08-28 02:09:46 +0000172
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000173 // Erase basic block from the function...
174 LI->removeBlock(BB);
175 BB->eraseFromParent();
Owen Anderson62c84fe2006-08-28 02:09:46 +0000176
Dan Gohman8d40e4d2007-05-14 14:31:17 +0000177 // Inherit predecessor's name if it exists...
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000178 if (!OldName.empty() && !OnlyPred->hasName())
179 OnlyPred->setName(OldName);
Owen Anderson62c84fe2006-08-28 02:09:46 +0000180
Owen Andersona8a2e5c2006-08-29 06:10:56 +0000181 return OnlyPred;
Owen Anderson62c84fe2006-08-28 02:09:46 +0000182}
183
Devang Patel9779e562007-03-07 01:38:05 +0000184bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel9779e562007-03-07 01:38:05 +0000185 LI = &getAnalysis<LoopInfo>();
Chris Lattner946b2552004-04-18 05:20:17 +0000186
Dan Gohman2980d9d2007-05-11 20:53:41 +0000187 // Unroll the loop.
188 if (!unrollLoop(L, UnrollCount, UnrollThreshold))
189 return false;
190
191 // Update the loop information for this loop.
192 // If we completely unrolled the loop, remove it from the parent.
193 if (L->getNumBackEdges() == 0)
194 LPM.deleteLoopFromQueue(L);
195
196 return true;
197}
198
199/// Unroll the given loop by UnrollCount, or by a heuristically-determined
Dan Gohman8d40e4d2007-05-14 14:31:17 +0000200/// value if Count is zero. If Threshold is not NoThreshold, it is a value
201/// to limit code size expansion. If the loop size would expand beyond the
202/// threshold value, unrolling is suppressed. The return value is true if
203/// any transformations are performed.
Dan Gohman2980d9d2007-05-11 20:53:41 +0000204///
205bool LoopUnroll::unrollLoop(Loop *L, unsigned Count, unsigned Threshold) {
206 assert(L->isLCSSAForm());
207
Dan Gohman2e1f8042007-05-08 15:19:19 +0000208 BasicBlock *Header = L->getHeader();
209 BasicBlock *LatchBlock = L->getLoopLatch();
Owen Andersone001d812006-08-24 21:28:19 +0000210 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Chris Lattner946b2552004-04-18 05:20:17 +0000211
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000212 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
Dan Gohman2980d9d2007-05-11 20:53:41 +0000213 << "] Loop %" << Header->getName() << "\n";
214
215 if (!BI || BI->isUnconditional()) {
Wojciech Matyjewicz30e43452008-01-04 20:02:18 +0000216 // The loop-rotate pass can be helpful to avoid this in many cases.
Dan Gohman2980d9d2007-05-11 20:53:41 +0000217 DOUT << " Can't unroll; loop not terminated by a conditional branch.\n";
218 return false;
Chris Lattner946b2552004-04-18 05:20:17 +0000219 }
Dan Gohman2980d9d2007-05-11 20:53:41 +0000220
221 // Determine the trip count and/or trip multiple. A TripCount value of zero
222 // is used to mean an unknown trip count. The TripMultiple value is the
223 // greatest known integer multiple of the trip count.
224 unsigned TripCount = 0;
225 unsigned TripMultiple = 1;
226 if (Value *TripCountValue = L->getTripCount()) {
227 if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCountValue)) {
228 // Guard against huge trip counts. This also guards against assertions in
229 // APInt from the use of getZExtValue, below.
230 if (TripCountC->getValue().getActiveBits() <= 32) {
231 TripCount = (unsigned)TripCountC->getZExtValue();
232 }
233 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCountValue)) {
234 switch (BO->getOpcode()) {
235 case BinaryOperator::Mul:
236 if (ConstantInt *MultipleC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
237 if (MultipleC->getValue().getActiveBits() <= 32) {
238 TripMultiple = (unsigned)MultipleC->getZExtValue();
239 }
240 }
241 break;
242 default: break;
243 }
244 }
245 }
246 if (TripCount != 0)
247 DOUT << " Trip Count = " << TripCount << "\n";
248 if (TripMultiple != 1)
249 DOUT << " Trip Multiple = " << TripMultiple << "\n";
250
251 // Automatically select an unroll count.
252 if (Count == 0) {
253 // Conservative heuristic: if we know the trip count, see if we can
254 // completely unroll (subject to the threshold, checked below); otherwise
255 // don't unroll.
256 if (TripCount != 0) {
257 Count = TripCount;
258 } else {
259 return false;
260 }
261 }
262
263 // Effectively "DCE" unrolled iterations that are beyond the tripcount
264 // and will never be executed.
265 if (TripCount != 0 && Count > TripCount)
266 Count = TripCount;
267
268 assert(Count > 0);
269 assert(TripMultiple > 0);
270 assert(TripCount == 0 || TripCount % TripMultiple == 0);
271
272 // Enforce the threshold.
273 if (Threshold != NoThreshold) {
274 unsigned LoopSize = ApproximateLoopSize(L);
275 DOUT << " Loop Size = " << LoopSize << "\n";
276 uint64_t Size = (uint64_t)LoopSize*Count;
277 if (TripCount != 1 && Size > Threshold) {
278 DOUT << " TOO LARGE TO UNROLL: "
279 << Size << ">" << Threshold << "\n";
280 return false;
281 }
282 }
283
284 // Are we eliminating the loop control altogether?
285 bool CompletelyUnroll = Count == TripCount;
286
287 // If we know the trip count, we know the multiple...
288 unsigned BreakoutTrip = 0;
289 if (TripCount != 0) {
290 BreakoutTrip = TripCount % Count;
291 TripMultiple = 0;
292 } else {
293 // Figure out what multiple to use.
294 BreakoutTrip = TripMultiple =
295 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
296 }
297
298 if (CompletelyUnroll) {
299 DOUT << "COMPLETELY UNROLLING loop %" << Header->getName()
300 << " with trip count " << TripCount << "!\n";
301 } else {
302 DOUT << "UNROLLING loop %" << Header->getName()
303 << " by " << Count;
304 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
305 DOUT << " with a breakout at trip " << BreakoutTrip;
306 } else if (TripMultiple != 1) {
307 DOUT << " with " << TripMultiple << " trips per branch";
308 }
309 DOUT << "!\n";
310 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000311
Owen Andersone001d812006-08-24 21:28:19 +0000312 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
313
Dan Gohman2980d9d2007-05-11 20:53:41 +0000314 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
315 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
Chris Lattner946b2552004-04-18 05:20:17 +0000316
317 // For the first iteration of the loop, we should use the precloned values for
318 // PHI nodes. Insert associations now.
Chris Lattner1077d2a2007-05-05 18:49:57 +0000319 typedef DenseMap<const Value*, Value*> ValueMapTy;
320 ValueMapTy LastValueMap;
Chris Lattner946b2552004-04-18 05:20:17 +0000321 std::vector<PHINode*> OrigPHINode;
Owen Andersone001d812006-08-24 21:28:19 +0000322 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Reid Spencer66149462004-09-15 17:06:42 +0000323 PHINode *PN = cast<PHINode>(I);
Chris Lattner946b2552004-04-18 05:20:17 +0000324 OrigPHINode.push_back(PN);
Owen Andersone001d812006-08-24 21:28:19 +0000325 if (Instruction *I =
326 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
327 if (L->contains(I->getParent()))
Chris Lattner946b2552004-04-18 05:20:17 +0000328 LastValueMap[I] = I;
329 }
330
Owen Andersone001d812006-08-24 21:28:19 +0000331 std::vector<BasicBlock*> Headers;
332 std::vector<BasicBlock*> Latches;
333 Headers.push_back(Header);
334 Latches.push_back(LatchBlock);
Chris Lattner946b2552004-04-18 05:20:17 +0000335
Dan Gohman2980d9d2007-05-11 20:53:41 +0000336 for (unsigned It = 1; It != Count; ++It) {
Chris Lattner946b2552004-04-18 05:20:17 +0000337 char SuffixBuffer[100];
338 sprintf(SuffixBuffer, ".%d", It);
Owen Andersone001d812006-08-24 21:28:19 +0000339
340 std::vector<BasicBlock*> NewBlocks;
341
342 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
343 E = LoopBlocks.end(); BB != E; ++BB) {
Chris Lattner1077d2a2007-05-05 18:49:57 +0000344 ValueMapTy ValueMap;
Owen Andersone001d812006-08-24 21:28:19 +0000345 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
346 Header->getParent()->getBasicBlockList().push_back(New);
Chris Lattner946b2552004-04-18 05:20:17 +0000347
Owen Andersone001d812006-08-24 21:28:19 +0000348 // Loop over all of the PHI nodes in the block, changing them to use the
349 // incoming values from the previous block.
350 if (*BB == Header)
351 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
352 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
353 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
354 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
355 if (It > 1 && L->contains(InValI->getParent()))
356 InVal = LastValueMap[InValI];
357 ValueMap[OrigPHINode[i]] = InVal;
358 New->getInstList().erase(NewPHI);
359 }
360
361 // Update our running map of newest clones
362 LastValueMap[*BB] = New;
Chris Lattner1077d2a2007-05-05 18:49:57 +0000363 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
364 VI != VE; ++VI)
Owen Andersone001d812006-08-24 21:28:19 +0000365 LastValueMap[VI->first] = VI->second;
366
Owen Andersonb0dd27e2007-11-27 03:43:35 +0000367 L->addBasicBlockToLoop(New, LI->getBase());
Owen Andersone001d812006-08-24 21:28:19 +0000368
369 // Add phi entries for newly created values to all exit blocks except
370 // the successor of the latch block. The successor of the exit block will
371 // be updated specially after unrolling all the way.
372 if (*BB != LatchBlock)
373 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
Nick Lewyckyefb16f72008-01-27 18:35:00 +0000374 UI != UE;) {
Dan Gohman2e1f8042007-05-08 15:19:19 +0000375 Instruction *UseInst = cast<Instruction>(*UI);
Nick Lewyckyefb16f72008-01-27 18:35:00 +0000376 ++UI;
Owen Andersone001d812006-08-24 21:28:19 +0000377 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
Dan Gohman2e1f8042007-05-08 15:19:19 +0000378 PHINode *phi = cast<PHINode>(UseInst);
379 Value *Incoming = phi->getIncomingValueForBlock(*BB);
Owen Andersone001d812006-08-24 21:28:19 +0000380 phi->addIncoming(Incoming, New);
381 }
382 }
383
384 // Keep track of new headers and latches as we create them, so that
385 // we can insert the proper branches later.
386 if (*BB == Header)
387 Headers.push_back(New);
Dan Gohman2980d9d2007-05-11 20:53:41 +0000388 if (*BB == LatchBlock) {
Owen Andersone001d812006-08-24 21:28:19 +0000389 Latches.push_back(New);
390
Dan Gohman2980d9d2007-05-11 20:53:41 +0000391 // Also, clear out the new latch's back edge so that it doesn't look
392 // like a new loop, so that it's amenable to being merged with adjacent
393 // blocks later on.
394 TerminatorInst *Term = New->getTerminator();
395 assert(L->contains(Term->getSuccessor(!ContinueOnTrue)));
396 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit);
397 Term->setSuccessor(!ContinueOnTrue, NULL);
398 }
399
Owen Andersone001d812006-08-24 21:28:19 +0000400 NewBlocks.push_back(New);
Chris Lattner946b2552004-04-18 05:20:17 +0000401 }
Owen Andersone001d812006-08-24 21:28:19 +0000402
403 // Remap all instructions in the most recent iteration
Nick Lewycky11fc6f82008-03-09 05:24:34 +0000404 for (unsigned i = 0; i < NewBlocks.size(); ++i) {
405 BasicBlock *NB = NewBlocks[i];
406 if (BasicBlock *UnwindDest = NB->getUnwindDest())
407 NB->setUnwindDest(cast<BasicBlock>(LastValueMap[UnwindDest]));
408
409 for (BasicBlock::iterator I = NB->begin(), E = NB->end(); I != E; ++I)
Chris Lattner230bcb62004-04-18 17:32:39 +0000410 RemapInstruction(I, LastValueMap);
Nick Lewycky11fc6f82008-03-09 05:24:34 +0000411 }
Chris Lattner230bcb62004-04-18 17:32:39 +0000412 }
Owen Andersone001d812006-08-24 21:28:19 +0000413
Chris Lattner1077d2a2007-05-05 18:49:57 +0000414 // The latch block exits the loop. If there are any PHI nodes in the
415 // successor blocks, update them to use the appropriate values computed as the
416 // last iteration of the loop.
Dan Gohman2980d9d2007-05-11 20:53:41 +0000417 if (Count != 1) {
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000418 SmallPtrSet<PHINode*, 8> Users;
Owen Andersone001d812006-08-24 21:28:19 +0000419 for (Value::use_iterator UI = LatchBlock->use_begin(),
420 UE = LatchBlock->use_end(); UI != UE; ++UI)
Dan Gohman2e1f8042007-05-08 15:19:19 +0000421 if (PHINode *phi = dyn_cast<PHINode>(*UI))
Owen Andersone001d812006-08-24 21:28:19 +0000422 Users.insert(phi);
Chris Lattner1077d2a2007-05-05 18:49:57 +0000423
424 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000425 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
Owen Andersone001d812006-08-24 21:28:19 +0000426 SI != SE; ++SI) {
Chris Lattner57d89a52007-05-05 18:36:36 +0000427 PHINode *PN = *SI;
Chris Lattner1077d2a2007-05-05 18:49:57 +0000428 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
429 // If this value was defined in the loop, take the value defined by the
430 // last iteration of the loop.
431 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
432 if (L->contains(InValI->getParent()))
433 InVal = LastValueMap[InVal];
Devang Patelabdff3f2007-04-16 23:03:45 +0000434 }
Chris Lattner1077d2a2007-05-05 18:49:57 +0000435 PN->addIncoming(InVal, LastIterationBB);
Owen Andersone001d812006-08-24 21:28:19 +0000436 }
437 }
Chris Lattner946b2552004-04-18 05:20:17 +0000438
Dan Gohman2980d9d2007-05-11 20:53:41 +0000439 // Now, if we're doing complete unrolling, loop over the PHI nodes in the
440 // original block, setting them to their incoming values.
441 if (CompletelyUnroll) {
442 BasicBlock *Preheader = L->getLoopPreheader();
443 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
444 PHINode *PN = OrigPHINode[i];
445 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
446 Header->getInstList().erase(PN);
Owen Anderson62c84fe2006-08-28 02:09:46 +0000447 }
448 }
Dan Gohman2980d9d2007-05-11 20:53:41 +0000449
450 // Now that all the basic blocks for the unrolled iterations are in place,
451 // set up the branches to connect them.
452 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
453 // The original branch was replicated in each unrolled iteration.
454 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
455
456 // The branch destination.
457 unsigned j = (i + 1) % e;
458 BasicBlock *Dest = Headers[j];
459 bool NeedConditional = true;
460
461 // For a complete unroll, make the last iteration end with a branch
462 // to the exit block.
463 if (CompletelyUnroll && j == 0) {
464 Dest = LoopExit;
465 NeedConditional = false;
466 }
467
468 // If we know the trip count or a multiple of it, we can safely use an
469 // unconditional branch for some iterations.
470 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
471 NeedConditional = false;
472 }
473
474 if (NeedConditional) {
475 // Update the conditional branch's successor for the following
476 // iteration.
477 Term->setSuccessor(!ContinueOnTrue, Dest);
478 } else {
479 Term->setUnconditionalDest(Dest);
480 // Merge adjacent basic blocks, if possible.
481 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest)) {
482 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
483 std::replace(Headers.begin(), Headers.end(), Dest, Fold);
484 }
485 }
486 }
Owen Anderson62c84fe2006-08-28 02:09:46 +0000487
Chris Lattner946b2552004-04-18 05:20:17 +0000488 // At this point, the code is well formed. We now do a quick sweep over the
489 // inserted code, doing constant propagation and dead code elimination as we
490 // go.
Owen Andersone001d812006-08-24 21:28:19 +0000491 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
492 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
Owen Anderson62c84fe2006-08-28 02:09:46 +0000493 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
Owen Andersone001d812006-08-24 21:28:19 +0000494 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
495 Instruction *Inst = I++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000496
Owen Andersone001d812006-08-24 21:28:19 +0000497 if (isInstructionTriviallyDead(Inst))
498 (*BB)->getInstList().erase(Inst);
499 else if (Constant *C = ConstantFoldInstruction(Inst)) {
500 Inst->replaceAllUsesWith(C);
501 (*BB)->getInstList().erase(Inst);
502 }
Chris Lattner946b2552004-04-18 05:20:17 +0000503 }
Chris Lattner946b2552004-04-18 05:20:17 +0000504
Dan Gohman2980d9d2007-05-11 20:53:41 +0000505 NumCompletelyUnrolled += CompletelyUnroll;
Chris Lattner946b2552004-04-18 05:20:17 +0000506 ++NumUnrolled;
507 return true;
508}