blob: 7eeb1527ad401c9b187832224a18f944d3061890 [file] [log] [blame]
Devang Patelc4625da2007-04-07 01:25:15 +00001//===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Devang Patelc4625da2007-04-07 01:25:15 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Rotation Pass.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel32231332007-04-09 16:11:48 +000014#define DEBUG_TYPE "loop-rotate"
Devang Patelc4625da2007-04-07 01:25:15 +000015#include "llvm/Transforms/Scalar.h"
16#include "llvm/Function.h"
Devang Patel3fc178f2011-02-14 23:03:23 +000017#include "llvm/IntrinsicInst.h"
Chris Lattnerd9e07972011-01-02 07:35:53 +000018#include "llvm/Analysis/CodeMetrics.h"
Chris Lattnerd9ec3572011-01-08 08:24:46 +000019#include "llvm/Analysis/LoopPass.h"
20#include "llvm/Analysis/InstructionSimplify.h"
Devang Patel990e8662007-07-11 23:47:28 +000021#include "llvm/Analysis/ScalarEvolution.h"
Andrew Trickf6629ab2012-02-14 00:00:23 +000022#include "llvm/Analysis/ValueTracking.h"
Devang Patelc4625da2007-04-07 01:25:15 +000023#include "llvm/Transforms/Utils/Local.h"
Devang Patel990e8662007-07-11 23:47:28 +000024#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohmane6e37b92009-10-24 23:19:52 +000025#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ccb3652011-01-08 07:21:31 +000026#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelc4625da2007-04-07 01:25:15 +000027#include "llvm/Support/Debug.h"
28#include "llvm/ADT/Statistic.h"
Devang Patelc4625da2007-04-07 01:25:15 +000029using namespace llvm;
30
31#define MAX_HEADER_SIZE 16
32
33STATISTIC(NumRotated, "Number of loops rotated");
34namespace {
35
Chris Lattner3e8b6632009-09-02 06:11:42 +000036 class LoopRotate : public LoopPass {
Devang Patelc4625da2007-04-07 01:25:15 +000037 public:
Devang Patel19974732007-05-03 01:11:54 +000038 static char ID; // Pass ID, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000039 LoopRotate() : LoopPass(ID) {
40 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
41 }
Devang Patel794fd752007-05-01 21:15:47 +000042
Devang Patel32231332007-04-09 16:11:48 +000043 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000044 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman1e381fc2010-07-16 17:58:45 +000045 AU.addPreserved<DominatorTree>();
Dan Gohman1e381fc2010-07-16 17:58:45 +000046 AU.addRequired<LoopInfo>();
47 AU.addPreserved<LoopInfo>();
Devang Patel9d9b2042008-02-15 01:24:49 +000048 AU.addRequiredID(LoopSimplifyID);
49 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000050 AU.addRequiredID(LCSSAID);
51 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000052 AU.addPreserved<ScalarEvolution>();
Devang Patelc4625da2007-04-07 01:25:15 +000053 }
54
Chris Lattnera1ae0c72011-01-08 18:55:50 +000055 bool runOnLoop(Loop *L, LPPassManager &LPM);
Andrew Trickf6629ab2012-02-14 00:00:23 +000056 void simplifyLoopLatch(Loop *L);
Chris Lattner4aefc9b2011-01-08 17:48:33 +000057 bool rotateLoop(Loop *L);
Andrew Trickc3a825b2012-02-14 00:00:19 +000058
Devang Patelc4625da2007-04-07 01:25:15 +000059 private:
Chris Lattner012ca942011-01-08 17:38:45 +000060 LoopInfo *LI;
Devang Patelc4625da2007-04-07 01:25:15 +000061 };
Devang Patelc4625da2007-04-07 01:25:15 +000062}
Andrew Trickc3a825b2012-02-14 00:00:19 +000063
Dan Gohman844731a2008-05-13 00:00:25 +000064char LoopRotate::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000065INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +000066INITIALIZE_PASS_DEPENDENCY(LoopInfo)
67INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
68INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +000069INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelc4625da2007-04-07 01:25:15 +000070
Daniel Dunbar394f0442008-10-22 23:32:42 +000071Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +000072
Devang Patel32231332007-04-09 16:11:48 +000073/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +000074/// the loop is rotated at least once.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000075bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner012ca942011-01-08 17:38:45 +000076 LI = &getAnalysis<LoopInfo>();
Devang Patel990e8662007-07-11 23:47:28 +000077
Andrew Trickf6629ab2012-02-14 00:00:23 +000078 // Simplify the loop latch before attempting to rotate the header
79 // upward. Rotation may not be needed if the loop tail can be folded into the
80 // loop exit.
81 simplifyLoopLatch(L);
82
Devang Patelc4625da2007-04-07 01:25:15 +000083 // One loop can be rotated multiple times.
Chris Lattner012ca942011-01-08 17:38:45 +000084 bool MadeChange = false;
Chris Lattner4aefc9b2011-01-08 17:48:33 +000085 while (rotateLoop(L))
Chris Lattner012ca942011-01-08 17:38:45 +000086 MadeChange = true;
Devang Patelc4625da2007-04-07 01:25:15 +000087
Chris Lattner012ca942011-01-08 17:38:45 +000088 return MadeChange;
Devang Patelc4625da2007-04-07 01:25:15 +000089}
90
Chris Lattner64c24db2011-01-08 19:26:33 +000091/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
92/// old header into the preheader. If there were uses of the values produced by
93/// these instruction that were outside of the loop, we have to insert PHI nodes
94/// to merge the two values. Do this now.
95static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
96 BasicBlock *OrigPreheader,
97 ValueToValueMapTy &ValueMap) {
98 // Remove PHI node entries that are no longer live.
99 BasicBlock::iterator I, E = OrigHeader->end();
100 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
101 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Trickc3a825b2012-02-14 00:00:19 +0000102
Chris Lattner64c24db2011-01-08 19:26:33 +0000103 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
104 // as necessary.
105 SSAUpdater SSA;
106 for (I = OrigHeader->begin(); I != E; ++I) {
107 Value *OrigHeaderVal = I;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000108
Chris Lattner64c24db2011-01-08 19:26:33 +0000109 // If there are no uses of the value (e.g. because it returns void), there
110 // is nothing to rewrite.
111 if (OrigHeaderVal->use_empty())
112 continue;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000113
Chris Lattner64c24db2011-01-08 19:26:33 +0000114 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
115
116 // The value now exits in two versions: the initial value in the preheader
117 // and the loop "next" value in the original header.
118 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
119 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
120 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000121
Chris Lattner64c24db2011-01-08 19:26:33 +0000122 // Visit each use of the OrigHeader instruction.
123 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
124 UE = OrigHeaderVal->use_end(); UI != UE; ) {
125 // Grab the use before incrementing the iterator.
126 Use &U = UI.getUse();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000127
Chris Lattner64c24db2011-01-08 19:26:33 +0000128 // Increment the iterator before removing the use from the list.
129 ++UI;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000130
Chris Lattner64c24db2011-01-08 19:26:33 +0000131 // SSAUpdater can't handle a non-PHI use in the same block as an
132 // earlier def. We can easily handle those cases manually.
133 Instruction *UserInst = cast<Instruction>(U.getUser());
134 if (!isa<PHINode>(UserInst)) {
135 BasicBlock *UserBB = UserInst->getParent();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000136
Chris Lattner64c24db2011-01-08 19:26:33 +0000137 // The original users in the OrigHeader are already using the
138 // original definitions.
139 if (UserBB == OrigHeader)
140 continue;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000141
Chris Lattner64c24db2011-01-08 19:26:33 +0000142 // Users in the OrigPreHeader need to use the value to which the
143 // original definitions are mapped.
144 if (UserBB == OrigPreheader) {
145 U = OrigPreHeaderVal;
146 continue;
147 }
148 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000149
Chris Lattner64c24db2011-01-08 19:26:33 +0000150 // Anything else can be handled by SSAUpdater.
151 SSA.RewriteUse(U);
152 }
153 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000154}
Chris Lattner64c24db2011-01-08 19:26:33 +0000155
Andrew Trickf6629ab2012-02-14 00:00:23 +0000156/// Determine whether the instructions in this range my be safely and cheaply
157/// speculated. This is not an important enough situation to develop complex
158/// heuristics. We handle a single arithmetic instruction along with any type
159/// conversions.
160static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
161 BasicBlock::iterator End) {
162 bool seenIncrement = false;
163 for (BasicBlock::iterator I = Begin; I != End; ++I) {
164
165 if (!isSafeToSpeculativelyExecute(I))
166 return false;
167
168 if (isa<DbgInfoIntrinsic>(I))
169 continue;
170
171 switch (I->getOpcode()) {
172 default:
173 return false;
174 case Instruction::GetElementPtr:
175 // GEPs are cheap if all indices are constant.
176 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
177 return false;
178 // fall-thru to increment case
179 case Instruction::Add:
180 case Instruction::Sub:
181 case Instruction::And:
182 case Instruction::Or:
183 case Instruction::Xor:
184 case Instruction::Shl:
185 case Instruction::LShr:
186 case Instruction::AShr:
187 if (seenIncrement)
188 return false;
189 seenIncrement = true;
190 break;
191 case Instruction::Trunc:
192 case Instruction::ZExt:
193 case Instruction::SExt:
194 // ignore type conversions
195 break;
196 }
197 }
198 return true;
199}
200
201/// Fold the loop tail into the loop exit by speculating the loop tail
202/// instructions. Typically, this is a single post-increment. In the case of a
203/// simple 2-block loop, hoisting the increment can be much better than
204/// duplicating the entire loop header. In the cast of loops with early exits,
205/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
206/// canonical form so downstream passes can handle it.
207///
208/// I don't believe this invalidates SCEV.
209void LoopRotate::simplifyLoopLatch(Loop *L) {
210 BasicBlock *Latch = L->getLoopLatch();
211 if (!Latch || Latch->hasAddressTaken())
212 return;
213
214 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
215 if (!Jmp || !Jmp->isUnconditional())
216 return;
217
218 BasicBlock *LastExit = Latch->getSinglePredecessor();
219 if (!LastExit || !L->isLoopExiting(LastExit))
220 return;
221
222 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
223 if (!BI)
224 return;
225
226 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
227 return;
228
229 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
230 << LastExit->getName() << "\n");
231
232 // Hoist the instructions from Latch into LastExit.
233 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
234
235 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
236 BasicBlock *Header = Jmp->getSuccessor(0);
237 assert(Header == L->getHeader() && "expected a backward branch");
238
239 // Remove Latch from the CFG so that LastExit becomes the new Latch.
240 BI->setSuccessor(FallThruPath, Header);
241 Latch->replaceSuccessorsPhiUsesWith(LastExit);
242 Jmp->eraseFromParent();
243
244 // Nuke the Latch block.
245 assert(Latch->empty() && "unable to evacuate Latch");
246 LI->removeBlock(Latch);
247 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
248 DT->eraseNode(Latch);
249 Latch->eraseFromParent();
250}
251
Dan Gohman23d9d272007-05-11 21:10:54 +0000252/// Rotate loop LP. Return true if the loop is rotated.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000253bool LoopRotate::rotateLoop(Loop *L) {
Dan Gohmancc4e6052009-06-25 00:22:44 +0000254 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000255 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000256 return false;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000257
Chris Lattner2aa69082011-01-08 18:06:22 +0000258 BasicBlock *OrigHeader = L->getHeader();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000259
Chris Lattner2aa69082011-01-08 18:06:22 +0000260 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
261 if (BI == 0 || BI->isUnconditional())
262 return false;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000263
Dan Gohmancc4e6052009-06-25 00:22:44 +0000264 // If the loop header is not one of the loop exiting blocks then
265 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000266 // suitable for loop rotation transformations.
Dan Gohman32663b72009-10-24 23:34:26 +0000267 if (!L->isLoopExiting(OrigHeader))
Devang Patelc4625da2007-04-07 01:25:15 +0000268 return false;
269
Andrew Trickc3a825b2012-02-14 00:00:19 +0000270 // Updating PHInodes in loops with multiple exits adds complexity.
Devang Patel32231332007-04-09 16:11:48 +0000271 // Keep it simple, and restrict loop rotation to loops with one exit only.
272 // In future, lift this restriction and support for multiple exits if
273 // required.
Devang Patelb7211a22007-08-21 00:31:24 +0000274 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelc4625da2007-04-07 01:25:15 +0000275 L->getExitBlocks(ExitBlocks);
276 if (ExitBlocks.size() > 1)
277 return false;
278
Chris Lattnerd9e07972011-01-02 07:35:53 +0000279 // Check size of original header and reject loop if it is very big.
280 {
281 CodeMetrics Metrics;
282 Metrics.analyzeBasicBlock(OrigHeader);
283 if (Metrics.NumInsts > MAX_HEADER_SIZE)
284 return false;
Devang Patel3f43a702009-03-06 03:51:30 +0000285 }
286
Devang Patel990e8662007-07-11 23:47:28 +0000287 // Now, this loop is suitable for rotation.
Chris Lattner64c24db2011-01-08 19:26:33 +0000288 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattner2aa69082011-01-08 18:06:22 +0000289 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000290
Chris Lattnerf5bf4642011-04-09 07:25:58 +0000291 // If the loop could not be converted to canonical form, it must have an
292 // indirectbr in it, just give up.
293 if (OrigPreheader == 0 || OrigLatch == 0)
294 return false;
Devang Patel990e8662007-07-11 23:47:28 +0000295
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000296 // Anything ScalarEvolution may know about this loop or the PHI nodes
297 // in its header will soon be invalidated.
298 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman4c7279a2009-10-31 15:04:55 +0000299 SE->forgetLoop(L);
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000300
Devang Patelc4625da2007-04-07 01:25:15 +0000301 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000302 // that is inside loop. Header's other successor is outside the
303 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000304 BasicBlock *Exit = BI->getSuccessor(0);
305 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel32231332007-04-09 16:11:48 +0000306 if (L->contains(Exit))
307 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000308 assert(NewHeader && "Unable to determine new loop header");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000309 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel32231332007-04-09 16:11:48 +0000310 "Unable to determine loop header and exit blocks");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000311
Dan Gohmancc4e6052009-06-25 00:22:44 +0000312 // This code assumes that the new header has exactly one predecessor.
313 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000314 assert(NewHeader->getSinglePredecessor() &&
315 "New header doesn't have one pred!");
316 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000317
Dan Gohmane6e37b92009-10-24 23:19:52 +0000318 // Begin by walking OrigHeader and populating ValueMap with an entry for
319 // each Instruction.
Devang Patel32231332007-04-09 16:11:48 +0000320 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner6ccb3652011-01-08 07:21:31 +0000321 ValueToValueMapTy ValueMap;
Devang Patele9881542007-04-09 19:04:21 +0000322
Dan Gohmane6e37b92009-10-24 23:19:52 +0000323 // For PHI nodes, the value available in OldPreHeader is just the
324 // incoming value from OldPreHeader.
325 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foadc1371202011-06-20 14:18:48 +0000326 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000327
Chris Lattner50fb4692010-09-06 01:10:22 +0000328 // For the rest of the instructions, either hoist to the OrigPreheader if
329 // possible or create a clone in the OldPreHeader if not.
Chris Lattner64c24db2011-01-08 19:26:33 +0000330 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattner50fb4692010-09-06 01:10:22 +0000331 while (I != E) {
332 Instruction *Inst = I++;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000333
Chris Lattner50fb4692010-09-06 01:10:22 +0000334 // If the instruction's operands are invariant and it doesn't read or write
335 // memory, then it is safe to hoist. Doing this doesn't change the order of
336 // execution in the preheader, but does prevent the instruction from
337 // executing in each iteration of the loop. This means it is safe to hoist
338 // something that might trap, but isn't safe to hoist something that reads
339 // memory (without proving that the loop doesn't write).
340 if (L->hasLoopInvariantOperands(Inst) &&
341 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedman5e6162e2012-02-16 00:41:10 +0000342 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
343 !isa<AllocaInst>(Inst)) {
Chris Lattner50fb4692010-09-06 01:10:22 +0000344 Inst->moveBefore(LoopEntryBranch);
345 continue;
346 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000347
Chris Lattner50fb4692010-09-06 01:10:22 +0000348 // Otherwise, create a duplicate of the instruction.
349 Instruction *C = Inst->clone();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000350
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000351 // Eagerly remap the operands of the instruction.
352 RemapInstruction(C, ValueMap,
353 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000354
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000355 // With the operands remapped, see if the instruction constant folds or is
356 // otherwise simplifyable. This commonly occurs because the entry from PHI
357 // nodes allows icmps and other instructions to fold.
Chris Lattner012ca942011-01-08 17:38:45 +0000358 Value *V = SimplifyInstruction(C);
359 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000360 // If so, then delete the temporary instruction and stick the folded value
361 // in the map.
362 delete C;
363 ValueMap[Inst] = V;
364 } else {
365 // Otherwise, stick the new instruction into the new block!
366 C->setName(Inst->getName());
367 C->insertBefore(LoopEntryBranch);
368 ValueMap[Inst] = C;
369 }
Devang Patelc4625da2007-04-07 01:25:15 +0000370 }
371
Dan Gohmane6e37b92009-10-24 23:19:52 +0000372 // Along with all the other instructions, we just cloned OrigHeader's
373 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
374 // successors by duplicating their incoming values for OrigHeader.
375 TerminatorInst *TI = OrigHeader->getTerminator();
376 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
377 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
378 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner64c24db2011-01-08 19:26:33 +0000379 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000380
Dan Gohmane6e37b92009-10-24 23:19:52 +0000381 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
382 // OrigPreHeader's old terminator (the original branch into the loop), and
383 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
384 LoopEntryBranch->eraseFromParent();
Devang Patelc4625da2007-04-07 01:25:15 +0000385
Chris Lattner64c24db2011-01-08 19:26:33 +0000386 // If there were any uses of instructions in the duplicated block outside the
387 // loop, update them, inserting PHI nodes as required
388 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelc4625da2007-04-07 01:25:15 +0000389
Dan Gohmane6e37b92009-10-24 23:19:52 +0000390 // NewHeader is now the header of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000391 L->moveToHeader(NewHeader);
Chris Lattner883401a2011-01-08 19:10:28 +0000392 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelc4625da2007-04-07 01:25:15 +0000393
Andrew Trickc3a825b2012-02-14 00:00:19 +0000394
Chris Lattner5d373702011-01-08 19:59:06 +0000395 // At this point, we've finished our major CFG changes. As part of cloning
396 // the loop into the preheader we've simplified instructions and the
397 // duplicated conditional branch may now be branching on a constant. If it is
398 // branching on a constant and if that constant means that we enter the loop,
399 // then we fold away the cond branch to an uncond branch. This simplifies the
400 // loop in cases important for nested loops, and it also means we don't have
401 // to split as many edges.
402 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
403 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
404 if (!isa<ConstantInt>(PHBI->getCondition()) ||
405 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
406 != NewHeader) {
407 // The conditional branch can't be folded, handle the general case.
408 // Update DominatorTree to reflect the CFG change we just made. Then split
409 // edges as necessary to preserve LoopSimplify form.
410 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
411 // Since OrigPreheader now has the conditional branch to Exit block, it is
412 // the dominator of Exit.
413 DT->changeImmediateDominator(Exit, OrigPreheader);
414 DT->changeImmediateDominator(NewHeader, OrigPreheader);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000415
Chris Lattner5d373702011-01-08 19:59:06 +0000416 // Update OrigHeader to be dominated by the new header block.
417 DT->changeImmediateDominator(OrigHeader, OrigLatch);
418 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000419
Chris Lattner5d373702011-01-08 19:59:06 +0000420 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotema94d6e82012-07-24 10:51:42 +0000421 // thus is not a preheader anymore.
422 // Split the edge to form a real preheader.
Chris Lattner5d373702011-01-08 19:59:06 +0000423 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
424 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000425
Nadav Rotema94d6e82012-07-24 10:51:42 +0000426 // Preserve canonical loop form, which means that 'Exit' should have only
427 // one predecessor.
Chris Lattner5d373702011-01-08 19:59:06 +0000428 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
429 ExitSplit->moveBefore(Exit);
430 } else {
431 // We can fold the conditional branch in the preheader, this makes things
432 // simpler. The first step is to remove the extra edge to the Exit block.
433 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelbd5426a2011-04-29 20:38:55 +0000434 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
435 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner5d373702011-01-08 19:59:06 +0000436 PHBI->eraseFromParent();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000437
Chris Lattner5d373702011-01-08 19:59:06 +0000438 // With our CFG finalized, update DomTree if it is available.
439 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
440 // Update OrigHeader to be dominated by the new header block.
441 DT->changeImmediateDominator(NewHeader, OrigPreheader);
442 DT->changeImmediateDominator(OrigHeader, OrigLatch);
443 }
Devang Patel990e8662007-07-11 23:47:28 +0000444 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000445
Chris Lattner5d373702011-01-08 19:59:06 +0000446 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner0e4a1542011-01-08 18:52:51 +0000447 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000448
Chris Lattner93767fd2011-01-11 07:47:59 +0000449 // Now that the CFG and DomTree are in a consistent state again, try to merge
450 // the OrigHeader block into OrigLatch. This will succeed if they are
451 // connected by an unconditional branch. This is just a cleanup so the
452 // emitted code isn't too gross in this common case.
453 MergeBlockIntoPredecessor(OrigHeader, this);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000454
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000455 ++NumRotated;
456 return true;
Devang Patel5464b962007-04-09 20:19:46 +0000457}
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000458