blob: abe07aa9d34d4287f2c9c37043a8845a6e151ec4 [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"
Benjamin Kramerd70846e2012-08-30 15:39:42 +000027#include "llvm/Support/CFG.h"
Devang Patelc4625da2007-04-07 01:25:15 +000028#include "llvm/Support/Debug.h"
29#include "llvm/ADT/Statistic.h"
Devang Patelc4625da2007-04-07 01:25:15 +000030using namespace llvm;
31
32#define MAX_HEADER_SIZE 16
33
34STATISTIC(NumRotated, "Number of loops rotated");
35namespace {
36
Chris Lattner3e8b6632009-09-02 06:11:42 +000037 class LoopRotate : public LoopPass {
Devang Patelc4625da2007-04-07 01:25:15 +000038 public:
Devang Patel19974732007-05-03 01:11:54 +000039 static char ID; // Pass ID, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000040 LoopRotate() : LoopPass(ID) {
41 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
42 }
Devang Patel794fd752007-05-01 21:15:47 +000043
Devang Patel32231332007-04-09 16:11:48 +000044 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000045 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman1e381fc2010-07-16 17:58:45 +000046 AU.addPreserved<DominatorTree>();
Dan Gohman1e381fc2010-07-16 17:58:45 +000047 AU.addRequired<LoopInfo>();
48 AU.addPreserved<LoopInfo>();
Devang Patel9d9b2042008-02-15 01:24:49 +000049 AU.addRequiredID(LoopSimplifyID);
50 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000051 AU.addRequiredID(LCSSAID);
52 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000053 AU.addPreserved<ScalarEvolution>();
Devang Patelc4625da2007-04-07 01:25:15 +000054 }
55
Chris Lattnera1ae0c72011-01-08 18:55:50 +000056 bool runOnLoop(Loop *L, LPPassManager &LPM);
Andrew Trickf6629ab2012-02-14 00:00:23 +000057 void simplifyLoopLatch(Loop *L);
Chris Lattner4aefc9b2011-01-08 17:48:33 +000058 bool rotateLoop(Loop *L);
Andrew Trickc3a825b2012-02-14 00:00:19 +000059
Devang Patelc4625da2007-04-07 01:25:15 +000060 private:
Chris Lattner012ca942011-01-08 17:38:45 +000061 LoopInfo *LI;
Devang Patelc4625da2007-04-07 01:25:15 +000062 };
Devang Patelc4625da2007-04-07 01:25:15 +000063}
Andrew Trickc3a825b2012-02-14 00:00:19 +000064
Dan Gohman844731a2008-05-13 00:00:25 +000065char LoopRotate::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000066INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +000067INITIALIZE_PASS_DEPENDENCY(LoopInfo)
68INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
69INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson2ab36d32010-10-12 19:48:12 +000070INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelc4625da2007-04-07 01:25:15 +000071
Daniel Dunbar394f0442008-10-22 23:32:42 +000072Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +000073
Devang Patel32231332007-04-09 16:11:48 +000074/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +000075/// the loop is rotated at least once.
Chris Lattner4aefc9b2011-01-08 17:48:33 +000076bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner012ca942011-01-08 17:38:45 +000077 LI = &getAnalysis<LoopInfo>();
Devang Patel990e8662007-07-11 23:47:28 +000078
Andrew Trickf6629ab2012-02-14 00:00:23 +000079 // Simplify the loop latch before attempting to rotate the header
80 // upward. Rotation may not be needed if the loop tail can be folded into the
81 // loop exit.
82 simplifyLoopLatch(L);
83
Devang Patelc4625da2007-04-07 01:25:15 +000084 // One loop can be rotated multiple times.
Chris Lattner012ca942011-01-08 17:38:45 +000085 bool MadeChange = false;
Chris Lattner4aefc9b2011-01-08 17:48:33 +000086 while (rotateLoop(L))
Chris Lattner012ca942011-01-08 17:38:45 +000087 MadeChange = true;
Devang Patelc4625da2007-04-07 01:25:15 +000088
Chris Lattner012ca942011-01-08 17:38:45 +000089 return MadeChange;
Devang Patelc4625da2007-04-07 01:25:15 +000090}
91
Chris Lattner64c24db2011-01-08 19:26:33 +000092/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
93/// old header into the preheader. If there were uses of the values produced by
94/// these instruction that were outside of the loop, we have to insert PHI nodes
95/// to merge the two values. Do this now.
96static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
97 BasicBlock *OrigPreheader,
98 ValueToValueMapTy &ValueMap) {
99 // Remove PHI node entries that are no longer live.
100 BasicBlock::iterator I, E = OrigHeader->end();
101 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
102 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Trickc3a825b2012-02-14 00:00:19 +0000103
Chris Lattner64c24db2011-01-08 19:26:33 +0000104 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
105 // as necessary.
106 SSAUpdater SSA;
107 for (I = OrigHeader->begin(); I != E; ++I) {
108 Value *OrigHeaderVal = I;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000109
Chris Lattner64c24db2011-01-08 19:26:33 +0000110 // If there are no uses of the value (e.g. because it returns void), there
111 // is nothing to rewrite.
112 if (OrigHeaderVal->use_empty())
113 continue;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000114
Chris Lattner64c24db2011-01-08 19:26:33 +0000115 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
116
117 // The value now exits in two versions: the initial value in the preheader
118 // and the loop "next" value in the original header.
119 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
120 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
121 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000122
Chris Lattner64c24db2011-01-08 19:26:33 +0000123 // Visit each use of the OrigHeader instruction.
124 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
125 UE = OrigHeaderVal->use_end(); UI != UE; ) {
126 // Grab the use before incrementing the iterator.
127 Use &U = UI.getUse();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000128
Chris Lattner64c24db2011-01-08 19:26:33 +0000129 // Increment the iterator before removing the use from the list.
130 ++UI;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000131
Chris Lattner64c24db2011-01-08 19:26:33 +0000132 // SSAUpdater can't handle a non-PHI use in the same block as an
133 // earlier def. We can easily handle those cases manually.
134 Instruction *UserInst = cast<Instruction>(U.getUser());
135 if (!isa<PHINode>(UserInst)) {
136 BasicBlock *UserBB = UserInst->getParent();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000137
Chris Lattner64c24db2011-01-08 19:26:33 +0000138 // The original users in the OrigHeader are already using the
139 // original definitions.
140 if (UserBB == OrigHeader)
141 continue;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000142
Chris Lattner64c24db2011-01-08 19:26:33 +0000143 // Users in the OrigPreHeader need to use the value to which the
144 // original definitions are mapped.
145 if (UserBB == OrigPreheader) {
146 U = OrigPreHeaderVal;
147 continue;
148 }
149 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000150
Chris Lattner64c24db2011-01-08 19:26:33 +0000151 // Anything else can be handled by SSAUpdater.
152 SSA.RewriteUse(U);
153 }
154 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000155}
Chris Lattner64c24db2011-01-08 19:26:33 +0000156
Andrew Trickf6629ab2012-02-14 00:00:23 +0000157/// Determine whether the instructions in this range my be safely and cheaply
158/// speculated. This is not an important enough situation to develop complex
159/// heuristics. We handle a single arithmetic instruction along with any type
160/// conversions.
161static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
162 BasicBlock::iterator End) {
163 bool seenIncrement = false;
164 for (BasicBlock::iterator I = Begin; I != End; ++I) {
165
166 if (!isSafeToSpeculativelyExecute(I))
167 return false;
168
169 if (isa<DbgInfoIntrinsic>(I))
170 continue;
171
172 switch (I->getOpcode()) {
173 default:
174 return false;
175 case Instruction::GetElementPtr:
176 // GEPs are cheap if all indices are constant.
177 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
178 return false;
179 // fall-thru to increment case
180 case Instruction::Add:
181 case Instruction::Sub:
182 case Instruction::And:
183 case Instruction::Or:
184 case Instruction::Xor:
185 case Instruction::Shl:
186 case Instruction::LShr:
187 case Instruction::AShr:
188 if (seenIncrement)
189 return false;
190 seenIncrement = true;
191 break;
192 case Instruction::Trunc:
193 case Instruction::ZExt:
194 case Instruction::SExt:
195 // ignore type conversions
196 break;
197 }
198 }
199 return true;
200}
201
202/// Fold the loop tail into the loop exit by speculating the loop tail
203/// instructions. Typically, this is a single post-increment. In the case of a
204/// simple 2-block loop, hoisting the increment can be much better than
205/// duplicating the entire loop header. In the cast of loops with early exits,
206/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
207/// canonical form so downstream passes can handle it.
208///
209/// I don't believe this invalidates SCEV.
210void LoopRotate::simplifyLoopLatch(Loop *L) {
211 BasicBlock *Latch = L->getLoopLatch();
212 if (!Latch || Latch->hasAddressTaken())
213 return;
214
215 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
216 if (!Jmp || !Jmp->isUnconditional())
217 return;
218
219 BasicBlock *LastExit = Latch->getSinglePredecessor();
220 if (!LastExit || !L->isLoopExiting(LastExit))
221 return;
222
223 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
224 if (!BI)
225 return;
226
227 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
228 return;
229
230 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
231 << LastExit->getName() << "\n");
232
233 // Hoist the instructions from Latch into LastExit.
234 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
235
236 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
237 BasicBlock *Header = Jmp->getSuccessor(0);
238 assert(Header == L->getHeader() && "expected a backward branch");
239
240 // Remove Latch from the CFG so that LastExit becomes the new Latch.
241 BI->setSuccessor(FallThruPath, Header);
242 Latch->replaceSuccessorsPhiUsesWith(LastExit);
243 Jmp->eraseFromParent();
244
245 // Nuke the Latch block.
246 assert(Latch->empty() && "unable to evacuate Latch");
247 LI->removeBlock(Latch);
248 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
249 DT->eraseNode(Latch);
250 Latch->eraseFromParent();
251}
252
Dan Gohman23d9d272007-05-11 21:10:54 +0000253/// Rotate loop LP. Return true if the loop is rotated.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000254bool LoopRotate::rotateLoop(Loop *L) {
Dan Gohmancc4e6052009-06-25 00:22:44 +0000255 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000256 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000257 return false;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000258
Chris Lattner2aa69082011-01-08 18:06:22 +0000259 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000260 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000261
Chris Lattner2aa69082011-01-08 18:06:22 +0000262 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
263 if (BI == 0 || BI->isUnconditional())
264 return false;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000265
Dan Gohmancc4e6052009-06-25 00:22:44 +0000266 // If the loop header is not one of the loop exiting blocks then
267 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000268 // suitable for loop rotation transformations.
Dan Gohman32663b72009-10-24 23:34:26 +0000269 if (!L->isLoopExiting(OrigHeader))
Devang Patelc4625da2007-04-07 01:25:15 +0000270 return false;
271
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000272 // If the loop latch already contains a branch that leaves the loop then the
273 // loop is already rotated.
274 if (OrigLatch == 0 || L->isLoopExiting(OrigLatch))
Devang Patelc4625da2007-04-07 01:25:15 +0000275 return false;
276
Chris Lattnerd9e07972011-01-02 07:35:53 +0000277 // Check size of original header and reject loop if it is very big.
278 {
279 CodeMetrics Metrics;
280 Metrics.analyzeBasicBlock(OrigHeader);
281 if (Metrics.NumInsts > MAX_HEADER_SIZE)
282 return false;
Devang Patel3f43a702009-03-06 03:51:30 +0000283 }
284
Devang Patel990e8662007-07-11 23:47:28 +0000285 // Now, this loop is suitable for rotation.
Chris Lattner64c24db2011-01-08 19:26:33 +0000286 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000287
Chris Lattnerf5bf4642011-04-09 07:25:58 +0000288 // If the loop could not be converted to canonical form, it must have an
289 // indirectbr in it, just give up.
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000290 if (OrigPreheader == 0)
Chris Lattnerf5bf4642011-04-09 07:25:58 +0000291 return false;
Devang Patel990e8662007-07-11 23:47:28 +0000292
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000293 // Anything ScalarEvolution may know about this loop or the PHI nodes
294 // in its header will soon be invalidated.
295 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman4c7279a2009-10-31 15:04:55 +0000296 SE->forgetLoop(L);
Dan Gohmane6fe67b2009-09-27 15:37:03 +0000297
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000298 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
299
Devang Patelc4625da2007-04-07 01:25:15 +0000300 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000301 // that is inside loop. Header's other successor is outside the
302 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner4aefc9b2011-01-08 17:48:33 +0000303 BasicBlock *Exit = BI->getSuccessor(0);
304 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel32231332007-04-09 16:11:48 +0000305 if (L->contains(Exit))
306 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000307 assert(NewHeader && "Unable to determine new loop header");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000308 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel32231332007-04-09 16:11:48 +0000309 "Unable to determine loop header and exit blocks");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000310
Dan Gohmancc4e6052009-06-25 00:22:44 +0000311 // This code assumes that the new header has exactly one predecessor.
312 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000313 assert(NewHeader->getSinglePredecessor() &&
314 "New header doesn't have one pred!");
315 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000316
Dan Gohmane6e37b92009-10-24 23:19:52 +0000317 // Begin by walking OrigHeader and populating ValueMap with an entry for
318 // each Instruction.
Devang Patel32231332007-04-09 16:11:48 +0000319 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner6ccb3652011-01-08 07:21:31 +0000320 ValueToValueMapTy ValueMap;
Devang Patele9881542007-04-09 19:04:21 +0000321
Dan Gohmane6e37b92009-10-24 23:19:52 +0000322 // For PHI nodes, the value available in OldPreHeader is just the
323 // incoming value from OldPreHeader.
324 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foadc1371202011-06-20 14:18:48 +0000325 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000326
Chris Lattner50fb4692010-09-06 01:10:22 +0000327 // For the rest of the instructions, either hoist to the OrigPreheader if
328 // possible or create a clone in the OldPreHeader if not.
Chris Lattner64c24db2011-01-08 19:26:33 +0000329 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattner50fb4692010-09-06 01:10:22 +0000330 while (I != E) {
331 Instruction *Inst = I++;
Andrew Trickc3a825b2012-02-14 00:00:19 +0000332
Chris Lattner50fb4692010-09-06 01:10:22 +0000333 // If the instruction's operands are invariant and it doesn't read or write
334 // memory, then it is safe to hoist. Doing this doesn't change the order of
335 // execution in the preheader, but does prevent the instruction from
336 // executing in each iteration of the loop. This means it is safe to hoist
337 // something that might trap, but isn't safe to hoist something that reads
338 // memory (without proving that the loop doesn't write).
339 if (L->hasLoopInvariantOperands(Inst) &&
340 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedman5e6162e2012-02-16 00:41:10 +0000341 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
342 !isa<AllocaInst>(Inst)) {
Chris Lattner50fb4692010-09-06 01:10:22 +0000343 Inst->moveBefore(LoopEntryBranch);
344 continue;
345 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000346
Chris Lattner50fb4692010-09-06 01:10:22 +0000347 // Otherwise, create a duplicate of the instruction.
348 Instruction *C = Inst->clone();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000349
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000350 // Eagerly remap the operands of the instruction.
351 RemapInstruction(C, ValueMap,
352 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000353
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000354 // With the operands remapped, see if the instruction constant folds or is
355 // otherwise simplifyable. This commonly occurs because the entry from PHI
356 // nodes allows icmps and other instructions to fold.
Chris Lattner012ca942011-01-08 17:38:45 +0000357 Value *V = SimplifyInstruction(C);
358 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattnerd9ec3572011-01-08 08:24:46 +0000359 // If so, then delete the temporary instruction and stick the folded value
360 // in the map.
361 delete C;
362 ValueMap[Inst] = V;
363 } else {
364 // Otherwise, stick the new instruction into the new block!
365 C->setName(Inst->getName());
366 C->insertBefore(LoopEntryBranch);
367 ValueMap[Inst] = C;
368 }
Devang Patelc4625da2007-04-07 01:25:15 +0000369 }
370
Dan Gohmane6e37b92009-10-24 23:19:52 +0000371 // Along with all the other instructions, we just cloned OrigHeader's
372 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
373 // successors by duplicating their incoming values for OrigHeader.
374 TerminatorInst *TI = OrigHeader->getTerminator();
375 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
376 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
377 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner64c24db2011-01-08 19:26:33 +0000378 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelc4625da2007-04-07 01:25:15 +0000379
Dan Gohmane6e37b92009-10-24 23:19:52 +0000380 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
381 // OrigPreHeader's old terminator (the original branch into the loop), and
382 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
383 LoopEntryBranch->eraseFromParent();
Devang Patelc4625da2007-04-07 01:25:15 +0000384
Chris Lattner64c24db2011-01-08 19:26:33 +0000385 // If there were any uses of instructions in the duplicated block outside the
386 // loop, update them, inserting PHI nodes as required
387 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelc4625da2007-04-07 01:25:15 +0000388
Dan Gohmane6e37b92009-10-24 23:19:52 +0000389 // NewHeader is now the header of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000390 L->moveToHeader(NewHeader);
Chris Lattner883401a2011-01-08 19:10:28 +0000391 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelc4625da2007-04-07 01:25:15 +0000392
Andrew Trickc3a825b2012-02-14 00:00:19 +0000393
Chris Lattner5d373702011-01-08 19:59:06 +0000394 // At this point, we've finished our major CFG changes. As part of cloning
395 // the loop into the preheader we've simplified instructions and the
396 // duplicated conditional branch may now be branching on a constant. If it is
397 // branching on a constant and if that constant means that we enter the loop,
398 // then we fold away the cond branch to an uncond branch. This simplifies the
399 // loop in cases important for nested loops, and it also means we don't have
400 // to split as many edges.
401 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
402 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
403 if (!isa<ConstantInt>(PHBI->getCondition()) ||
404 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
405 != NewHeader) {
406 // The conditional branch can't be folded, handle the general case.
407 // Update DominatorTree to reflect the CFG change we just made. Then split
408 // edges as necessary to preserve LoopSimplify form.
409 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000410 // Everything that was dominated by the old loop header is now dominated
411 // by the original loop preheader. Conceptually the header was merged
412 // into the preheader, even though we reuse the actual block as a new
413 // loop latch.
414 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
415 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
416 OrigHeaderNode->end());
417 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
418 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
419 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000420
Benjamin Kramer64f30e32012-09-01 12:04:51 +0000421 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
422 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
423
Chris Lattner5d373702011-01-08 19:59:06 +0000424 // Update OrigHeader to be dominated by the new header block.
425 DT->changeImmediateDominator(OrigHeader, OrigLatch);
426 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000427
Chris Lattner5d373702011-01-08 19:59:06 +0000428 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotema94d6e82012-07-24 10:51:42 +0000429 // thus is not a preheader anymore.
430 // Split the edge to form a real preheader.
Chris Lattner5d373702011-01-08 19:59:06 +0000431 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
432 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Trickc3a825b2012-02-14 00:00:19 +0000433
Nadav Rotema94d6e82012-07-24 10:51:42 +0000434 // Preserve canonical loop form, which means that 'Exit' should have only
435 // one predecessor.
Chris Lattner5d373702011-01-08 19:59:06 +0000436 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
437 ExitSplit->moveBefore(Exit);
438 } else {
439 // We can fold the conditional branch in the preheader, this makes things
440 // simpler. The first step is to remove the extra edge to the Exit block.
441 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelbd5426a2011-04-29 20:38:55 +0000442 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
443 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner5d373702011-01-08 19:59:06 +0000444 PHBI->eraseFromParent();
Andrew Trickc3a825b2012-02-14 00:00:19 +0000445
Chris Lattner5d373702011-01-08 19:59:06 +0000446 // With our CFG finalized, update DomTree if it is available.
447 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
448 // Update OrigHeader to be dominated by the new header block.
449 DT->changeImmediateDominator(NewHeader, OrigPreheader);
450 DT->changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000451
452 // Brute force incremental dominator tree update. Call
453 // findNearestCommonDominator on all CFG predecessors of each child of the
454 // original header.
455 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
Benjamin Kramer7de70782012-09-02 11:57:22 +0000456 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
457 OrigHeaderNode->end());
458 bool Changed;
459 do {
460 Changed = false;
461 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
462 DomTreeNode *Node = HeaderChildren[I];
463 BasicBlock *BB = Node->getBlock();
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000464
Benjamin Kramer7de70782012-09-02 11:57:22 +0000465 pred_iterator PI = pred_begin(BB);
466 BasicBlock *NearestDom = *PI;
467 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
468 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
469
470 // Remember if this changes the DomTree.
471 if (Node->getIDom()->getBlock() != NearestDom) {
472 DT->changeImmediateDominator(BB, NearestDom);
473 Changed = true;
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000474 }
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000475 }
476
Benjamin Kramer7de70782012-09-02 11:57:22 +0000477 // If the dominator changed, this may have an effect on other
478 // predecessors, continue until we reach a fixpoint.
479 } while (Changed);
Chris Lattner5d373702011-01-08 19:59:06 +0000480 }
Devang Patel990e8662007-07-11 23:47:28 +0000481 }
Andrew Trickc3a825b2012-02-14 00:00:19 +0000482
Chris Lattner5d373702011-01-08 19:59:06 +0000483 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner0e4a1542011-01-08 18:52:51 +0000484 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000485
Chris Lattner93767fd2011-01-11 07:47:59 +0000486 // Now that the CFG and DomTree are in a consistent state again, try to merge
487 // the OrigHeader block into OrigLatch. This will succeed if they are
488 // connected by an unconditional branch. This is just a cleanup so the
489 // emitted code isn't too gross in this common case.
490 MergeBlockIntoPredecessor(OrigHeader, this);
Andrew Trickc3a825b2012-02-14 00:00:19 +0000491
Benjamin Kramerd70846e2012-08-30 15:39:42 +0000492 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
493
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000494 ++NumRotated;
495 return true;
Devang Patel5464b962007-04-09 20:19:46 +0000496}
Chris Lattnera1ae0c72011-01-08 18:55:50 +0000497