blob: 004ca14260409f7d5f8eb5a8a0c1c79b30ed8e49 [file] [log] [blame]
Devang Patelf42389f2007-04-07 01:25:15 +00001//===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
2//
3// 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.
Devang Patelf42389f2007-04-07 01:25:15 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Loop Rotation Pass.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel88bc2c62007-04-09 16:11:48 +000014#define DEBUG_TYPE "loop-rotate"
Devang Patelf42389f2007-04-07 01:25:15 +000015#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/Statistic.h"
Chris Lattner679572e2011-01-02 07:35:53 +000017#include "llvm/Analysis/CodeMetrics.h"
Chris Lattner8c5defd2011-01-08 08:24:46 +000018#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/LoopPass.h"
Devang Patelfac4d1f2007-07-11 23:47:28 +000020#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruthbb9caa92013-01-21 13:04:33 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Andrew Trick10cc4532012-02-14 00:00:23 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Function.h"
25#include "llvm/IR/IntrinsicInst.h"
Benjamin Kramerafdfdb52012-08-30 15:39:42 +000026#include "llvm/Support/CFG.h"
Devang Patelf42389f2007-04-07 01:25:15 +000027#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Transforms/Utils/BasicBlockUtils.h"
29#include "llvm/Transforms/Utils/Local.h"
30#include "llvm/Transforms/Utils/SSAUpdater.h"
31#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000032using namespace llvm;
33
34#define MAX_HEADER_SIZE 16
35
36STATISTIC(NumRotated, "Number of loops rotated");
37namespace {
38
Chris Lattner2dd09db2009-09-02 06:11:42 +000039 class LoopRotate : public LoopPass {
Devang Patelf42389f2007-04-07 01:25:15 +000040 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000041 static char ID; // Pass ID, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000042 LoopRotate() : LoopPass(ID) {
43 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
44 }
Devang Patel09f162c2007-05-01 21:15:47 +000045
Devang Patel88bc2c62007-04-09 16:11:48 +000046 // LCSSA form makes instruction renaming easier.
Devang Patelf42389f2007-04-07 01:25:15 +000047 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth73523022014-01-13 13:07:17 +000048 AU.addPreserved<DominatorTreeWrapperPass>();
Dan Gohmanefd7f9c2010-07-16 17:58:45 +000049 AU.addRequired<LoopInfo>();
50 AU.addPreserved<LoopInfo>();
Devang Patela42c3142008-02-15 01:24:49 +000051 AU.addRequiredID(LoopSimplifyID);
52 AU.addPreservedID(LoopSimplifyID);
Devang Patelf42389f2007-04-07 01:25:15 +000053 AU.addRequiredID(LCSSAID);
54 AU.addPreservedID(LCSSAID);
Devang Patelfac4d1f2007-07-11 23:47:28 +000055 AU.addPreserved<ScalarEvolution>();
Chandler Carruthbb9caa92013-01-21 13:04:33 +000056 AU.addRequired<TargetTransformInfo>();
Devang Patelf42389f2007-04-07 01:25:15 +000057 }
58
Chris Lattnerfee37c52011-01-08 18:55:50 +000059 bool runOnLoop(Loop *L, LPPassManager &LPM);
Andrew Trick9c72b072013-05-06 17:58:18 +000060 bool simplifyLoopLatch(Loop *L);
61 bool rotateLoop(Loop *L, bool SimplifiedLatch);
Andrew Tricka20f1982012-02-14 00:00:19 +000062
Devang Patelf42389f2007-04-07 01:25:15 +000063 private:
Chris Lattner25ba40a2011-01-08 17:38:45 +000064 LoopInfo *LI;
Chandler Carruthbb9caa92013-01-21 13:04:33 +000065 const TargetTransformInfo *TTI;
Devang Patelf42389f2007-04-07 01:25:15 +000066 };
Devang Patelf42389f2007-04-07 01:25:15 +000067}
Andrew Tricka20f1982012-02-14 00:00:19 +000068
Dan Gohmand78c4002008-05-13 00:00:25 +000069char LoopRotate::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000070INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Chandler Carruthbb9caa92013-01-21 13:04:33 +000071INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +000072INITIALIZE_PASS_DEPENDENCY(LoopInfo)
73INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
74INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson8ac477f2010-10-12 19:48:12 +000075INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelf42389f2007-04-07 01:25:15 +000076
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +000077Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelf42389f2007-04-07 01:25:15 +000078
Devang Patel88bc2c62007-04-09 16:11:48 +000079/// Rotate Loop L as many times as possible. Return true if
Dan Gohman091e4402009-06-25 00:22:44 +000080/// the loop is rotated at least once.
Chris Lattner385f2ec2011-01-08 17:48:33 +000081bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner25ba40a2011-01-08 17:38:45 +000082 LI = &getAnalysis<LoopInfo>();
Chandler Carruthbb9caa92013-01-21 13:04:33 +000083 TTI = &getAnalysis<TargetTransformInfo>();
Devang Patelfac4d1f2007-07-11 23:47:28 +000084
Andrew Trick10cc4532012-02-14 00:00:23 +000085 // Simplify the loop latch before attempting to rotate the header
86 // upward. Rotation may not be needed if the loop tail can be folded into the
87 // loop exit.
Andrew Trick9c72b072013-05-06 17:58:18 +000088 bool SimplifiedLatch = simplifyLoopLatch(L);
Andrew Trick10cc4532012-02-14 00:00:23 +000089
Devang Patelf42389f2007-04-07 01:25:15 +000090 // One loop can be rotated multiple times.
Chris Lattner25ba40a2011-01-08 17:38:45 +000091 bool MadeChange = false;
Andrew Trick9c72b072013-05-06 17:58:18 +000092 while (rotateLoop(L, SimplifiedLatch)) {
Chris Lattner25ba40a2011-01-08 17:38:45 +000093 MadeChange = true;
Andrew Trick9c72b072013-05-06 17:58:18 +000094 SimplifiedLatch = false;
95 }
Chris Lattner25ba40a2011-01-08 17:38:45 +000096 return MadeChange;
Devang Patelf42389f2007-04-07 01:25:15 +000097}
98
Chris Lattner30f318e2011-01-08 19:26:33 +000099/// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
100/// old header into the preheader. If there were uses of the values produced by
101/// these instruction that were outside of the loop, we have to insert PHI nodes
102/// to merge the two values. Do this now.
103static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
104 BasicBlock *OrigPreheader,
105 ValueToValueMapTy &ValueMap) {
106 // Remove PHI node entries that are no longer live.
107 BasicBlock::iterator I, E = OrigHeader->end();
108 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
109 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
Andrew Tricka20f1982012-02-14 00:00:19 +0000110
Chris Lattner30f318e2011-01-08 19:26:33 +0000111 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
112 // as necessary.
113 SSAUpdater SSA;
114 for (I = OrigHeader->begin(); I != E; ++I) {
115 Value *OrigHeaderVal = I;
Andrew Tricka20f1982012-02-14 00:00:19 +0000116
Chris Lattner30f318e2011-01-08 19:26:33 +0000117 // If there are no uses of the value (e.g. because it returns void), there
118 // is nothing to rewrite.
119 if (OrigHeaderVal->use_empty())
120 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000121
Chris Lattner30f318e2011-01-08 19:26:33 +0000122 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
123
124 // The value now exits in two versions: the initial value in the preheader
125 // and the loop "next" value in the original header.
126 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
127 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
128 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
Andrew Tricka20f1982012-02-14 00:00:19 +0000129
Chris Lattner30f318e2011-01-08 19:26:33 +0000130 // Visit each use of the OrigHeader instruction.
131 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
132 UE = OrigHeaderVal->use_end(); UI != UE; ) {
133 // Grab the use before incrementing the iterator.
134 Use &U = UI.getUse();
Andrew Tricka20f1982012-02-14 00:00:19 +0000135
Chris Lattner30f318e2011-01-08 19:26:33 +0000136 // Increment the iterator before removing the use from the list.
137 ++UI;
Andrew Tricka20f1982012-02-14 00:00:19 +0000138
Chris Lattner30f318e2011-01-08 19:26:33 +0000139 // SSAUpdater can't handle a non-PHI use in the same block as an
140 // earlier def. We can easily handle those cases manually.
141 Instruction *UserInst = cast<Instruction>(U.getUser());
142 if (!isa<PHINode>(UserInst)) {
143 BasicBlock *UserBB = UserInst->getParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000144
Chris Lattner30f318e2011-01-08 19:26:33 +0000145 // The original users in the OrigHeader are already using the
146 // original definitions.
147 if (UserBB == OrigHeader)
148 continue;
Andrew Tricka20f1982012-02-14 00:00:19 +0000149
Chris Lattner30f318e2011-01-08 19:26:33 +0000150 // Users in the OrigPreHeader need to use the value to which the
151 // original definitions are mapped.
152 if (UserBB == OrigPreheader) {
153 U = OrigPreHeaderVal;
154 continue;
155 }
156 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000157
Chris Lattner30f318e2011-01-08 19:26:33 +0000158 // Anything else can be handled by SSAUpdater.
159 SSA.RewriteUse(U);
160 }
161 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000162}
Chris Lattner30f318e2011-01-08 19:26:33 +0000163
Andrew Trick10cc4532012-02-14 00:00:23 +0000164/// Determine whether the instructions in this range my be safely and cheaply
165/// speculated. This is not an important enough situation to develop complex
166/// heuristics. We handle a single arithmetic instruction along with any type
167/// conversions.
168static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
169 BasicBlock::iterator End) {
170 bool seenIncrement = false;
171 for (BasicBlock::iterator I = Begin; I != End; ++I) {
172
173 if (!isSafeToSpeculativelyExecute(I))
174 return false;
175
176 if (isa<DbgInfoIntrinsic>(I))
177 continue;
178
179 switch (I->getOpcode()) {
180 default:
181 return false;
182 case Instruction::GetElementPtr:
183 // GEPs are cheap if all indices are constant.
184 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
185 return false;
186 // fall-thru to increment case
187 case Instruction::Add:
188 case Instruction::Sub:
189 case Instruction::And:
190 case Instruction::Or:
191 case Instruction::Xor:
192 case Instruction::Shl:
193 case Instruction::LShr:
194 case Instruction::AShr:
195 if (seenIncrement)
196 return false;
197 seenIncrement = true;
198 break;
199 case Instruction::Trunc:
200 case Instruction::ZExt:
201 case Instruction::SExt:
202 // ignore type conversions
203 break;
204 }
205 }
206 return true;
207}
208
209/// Fold the loop tail into the loop exit by speculating the loop tail
210/// instructions. Typically, this is a single post-increment. In the case of a
211/// simple 2-block loop, hoisting the increment can be much better than
212/// duplicating the entire loop header. In the cast of loops with early exits,
213/// rotation will not work anyway, but simplifyLoopLatch will put the loop in
214/// canonical form so downstream passes can handle it.
215///
216/// I don't believe this invalidates SCEV.
Andrew Trick9c72b072013-05-06 17:58:18 +0000217bool LoopRotate::simplifyLoopLatch(Loop *L) {
Andrew Trick10cc4532012-02-14 00:00:23 +0000218 BasicBlock *Latch = L->getLoopLatch();
219 if (!Latch || Latch->hasAddressTaken())
Andrew Trick9c72b072013-05-06 17:58:18 +0000220 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000221
222 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
223 if (!Jmp || !Jmp->isUnconditional())
Andrew Trick9c72b072013-05-06 17:58:18 +0000224 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000225
226 BasicBlock *LastExit = Latch->getSinglePredecessor();
227 if (!LastExit || !L->isLoopExiting(LastExit))
Andrew Trick9c72b072013-05-06 17:58:18 +0000228 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000229
230 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
231 if (!BI)
Andrew Trick9c72b072013-05-06 17:58:18 +0000232 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000233
234 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
Andrew Trick9c72b072013-05-06 17:58:18 +0000235 return false;
Andrew Trick10cc4532012-02-14 00:00:23 +0000236
237 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
238 << LastExit->getName() << "\n");
239
240 // Hoist the instructions from Latch into LastExit.
241 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
242
243 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
244 BasicBlock *Header = Jmp->getSuccessor(0);
245 assert(Header == L->getHeader() && "expected a backward branch");
246
247 // Remove Latch from the CFG so that LastExit becomes the new Latch.
248 BI->setSuccessor(FallThruPath, Header);
249 Latch->replaceSuccessorsPhiUsesWith(LastExit);
250 Jmp->eraseFromParent();
251
252 // Nuke the Latch block.
253 assert(Latch->empty() && "unable to evacuate Latch");
254 LI->removeBlock(Latch);
Chandler Carruth73523022014-01-13 13:07:17 +0000255 if (DominatorTreeWrapperPass *DTWP =
256 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
257 DTWP->getDomTree().eraseNode(Latch);
Andrew Trick10cc4532012-02-14 00:00:23 +0000258 Latch->eraseFromParent();
Andrew Trick9c72b072013-05-06 17:58:18 +0000259 return true;
Andrew Trick10cc4532012-02-14 00:00:23 +0000260}
261
Dan Gohmanb5650eb2007-05-11 21:10:54 +0000262/// Rotate loop LP. Return true if the loop is rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000263///
264/// \param SimplifiedLatch is true if the latch was just folded into the final
265/// loop exit. In this case we may want to rotate even though the new latch is
266/// now an exiting branch. This rotation would have happened had the latch not
267/// been simplified. However, if SimplifiedLatch is false, then we avoid
268/// rotating loops in which the latch exits to avoid excessive or endless
269/// rotation. LoopRotate should be repeatable and converge to a canonical
270/// form. This property is satisfied because simplifying the loop latch can only
271/// happen once across multiple invocations of the LoopRotate pass.
272bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
Dan Gohman091e4402009-06-25 00:22:44 +0000273 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +0000274 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +0000275 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000276
Chris Lattner7fab23b2011-01-08 18:06:22 +0000277 BasicBlock *OrigHeader = L->getHeader();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000278 BasicBlock *OrigLatch = L->getLoopLatch();
Andrew Tricka20f1982012-02-14 00:00:19 +0000279
Chris Lattner7fab23b2011-01-08 18:06:22 +0000280 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
281 if (BI == 0 || BI->isUnconditional())
282 return false;
Andrew Tricka20f1982012-02-14 00:00:19 +0000283
Dan Gohman091e4402009-06-25 00:22:44 +0000284 // If the loop header is not one of the loop exiting blocks then
285 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +0000286 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +0000287 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +0000288 return false;
289
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000290 // If the loop latch already contains a branch that leaves the loop then the
291 // loop is already rotated.
Andrew Trick9c72b072013-05-06 17:58:18 +0000292 if (OrigLatch == 0)
293 return false;
294
295 // Rotate if either the loop latch does *not* exit the loop, or if the loop
296 // latch was just simplified.
297 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
Devang Patelf42389f2007-04-07 01:25:15 +0000298 return false;
299
James Molloy4f6fb952012-12-20 16:04:27 +0000300 // Check size of original header and reject loop if it is very big or we can't
301 // duplicate blocks inside it.
Chris Lattner679572e2011-01-02 07:35:53 +0000302 {
303 CodeMetrics Metrics;
Chandler Carruthbb9caa92013-01-21 13:04:33 +0000304 Metrics.analyzeBasicBlock(OrigHeader, *TTI);
James Molloy4f6fb952012-12-20 16:04:27 +0000305 if (Metrics.notDuplicatable) {
Alp Tokerf907b892013-12-05 05:44:44 +0000306 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
James Molloy4f6fb952012-12-20 16:04:27 +0000307 << " instructions: "; L->dump());
308 return false;
309 }
Chris Lattner679572e2011-01-02 07:35:53 +0000310 if (Metrics.NumInsts > MAX_HEADER_SIZE)
311 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000312 }
313
Devang Patelfac4d1f2007-07-11 23:47:28 +0000314 // Now, this loop is suitable for rotation.
Chris Lattner30f318e2011-01-08 19:26:33 +0000315 BasicBlock *OrigPreheader = L->getLoopPreheader();
Andrew Tricka20f1982012-02-14 00:00:19 +0000316
Chris Lattner88974f42011-04-09 07:25:58 +0000317 // If the loop could not be converted to canonical form, it must have an
318 // indirectbr in it, just give up.
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000319 if (OrigPreheader == 0)
Chris Lattner88974f42011-04-09 07:25:58 +0000320 return false;
Devang Patelfac4d1f2007-07-11 23:47:28 +0000321
Dan Gohmanfc20b672009-09-27 15:37:03 +0000322 // Anything ScalarEvolution may know about this loop or the PHI nodes
323 // in its header will soon be invalidated.
324 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman880c92a2009-10-31 15:04:55 +0000325 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000326
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000327 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
328
Devang Patelf42389f2007-04-07 01:25:15 +0000329 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000330 // that is inside loop. Header's other successor is outside the
331 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000332 BasicBlock *Exit = BI->getSuccessor(0);
333 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000334 if (L->contains(Exit))
335 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000336 assert(NewHeader && "Unable to determine new loop header");
Andrew Tricka20f1982012-02-14 00:00:19 +0000337 assert(L->contains(NewHeader) && !L->contains(Exit) &&
Devang Patel88bc2c62007-04-09 16:11:48 +0000338 "Unable to determine loop header and exit blocks");
Andrew Tricka20f1982012-02-14 00:00:19 +0000339
Dan Gohman091e4402009-06-25 00:22:44 +0000340 // This code assumes that the new header has exactly one predecessor.
341 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000342 assert(NewHeader->getSinglePredecessor() &&
343 "New header doesn't have one pred!");
344 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000345
Dan Gohmanb9797942009-10-24 23:19:52 +0000346 // Begin by walking OrigHeader and populating ValueMap with an entry for
347 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000348 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000349 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000350
Dan Gohmanb9797942009-10-24 23:19:52 +0000351 // For PHI nodes, the value available in OldPreHeader is just the
352 // incoming value from OldPreHeader.
353 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
Jay Foad372ad642011-06-20 14:18:48 +0000354 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000355
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000356 // For the rest of the instructions, either hoist to the OrigPreheader if
357 // possible or create a clone in the OldPreHeader if not.
Chris Lattner30f318e2011-01-08 19:26:33 +0000358 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000359 while (I != E) {
360 Instruction *Inst = I++;
Andrew Tricka20f1982012-02-14 00:00:19 +0000361
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000362 // If the instruction's operands are invariant and it doesn't read or write
363 // memory, then it is safe to hoist. Doing this doesn't change the order of
364 // execution in the preheader, but does prevent the instruction from
365 // executing in each iteration of the loop. This means it is safe to hoist
366 // something that might trap, but isn't safe to hoist something that reads
367 // memory (without proving that the loop doesn't write).
368 if (L->hasLoopInvariantOperands(Inst) &&
369 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
Eli Friedmanc4588852012-02-16 00:41:10 +0000370 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
371 !isa<AllocaInst>(Inst)) {
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000372 Inst->moveBefore(LoopEntryBranch);
373 continue;
374 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000375
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000376 // Otherwise, create a duplicate of the instruction.
377 Instruction *C = Inst->clone();
Andrew Tricka20f1982012-02-14 00:00:19 +0000378
Chris Lattner8c5defd2011-01-08 08:24:46 +0000379 // Eagerly remap the operands of the instruction.
380 RemapInstruction(C, ValueMap,
381 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
Andrew Tricka20f1982012-02-14 00:00:19 +0000382
Chris Lattner8c5defd2011-01-08 08:24:46 +0000383 // With the operands remapped, see if the instruction constant folds or is
384 // otherwise simplifyable. This commonly occurs because the entry from PHI
385 // nodes allows icmps and other instructions to fold.
Chris Lattner25ba40a2011-01-08 17:38:45 +0000386 Value *V = SimplifyInstruction(C);
387 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000388 // If so, then delete the temporary instruction and stick the folded value
389 // in the map.
390 delete C;
391 ValueMap[Inst] = V;
392 } else {
393 // Otherwise, stick the new instruction into the new block!
394 C->setName(Inst->getName());
395 C->insertBefore(LoopEntryBranch);
396 ValueMap[Inst] = C;
397 }
Devang Patelf42389f2007-04-07 01:25:15 +0000398 }
399
Dan Gohmanb9797942009-10-24 23:19:52 +0000400 // Along with all the other instructions, we just cloned OrigHeader's
401 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
402 // successors by duplicating their incoming values for OrigHeader.
403 TerminatorInst *TI = OrigHeader->getTerminator();
404 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
405 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
406 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
Chris Lattner30f318e2011-01-08 19:26:33 +0000407 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
Devang Patelf42389f2007-04-07 01:25:15 +0000408
Dan Gohmanb9797942009-10-24 23:19:52 +0000409 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
410 // OrigPreHeader's old terminator (the original branch into the loop), and
411 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
412 LoopEntryBranch->eraseFromParent();
Devang Patelf42389f2007-04-07 01:25:15 +0000413
Chris Lattner30f318e2011-01-08 19:26:33 +0000414 // If there were any uses of instructions in the duplicated block outside the
415 // loop, update them, inserting PHI nodes as required
416 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
Devang Patelf42389f2007-04-07 01:25:15 +0000417
Dan Gohmanb9797942009-10-24 23:19:52 +0000418 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000419 L->moveToHeader(NewHeader);
Chris Lattner26151302011-01-08 19:10:28 +0000420 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Devang Patelf42389f2007-04-07 01:25:15 +0000421
Andrew Tricka20f1982012-02-14 00:00:19 +0000422
Chris Lattner59c82f82011-01-08 19:59:06 +0000423 // At this point, we've finished our major CFG changes. As part of cloning
424 // the loop into the preheader we've simplified instructions and the
425 // duplicated conditional branch may now be branching on a constant. If it is
426 // branching on a constant and if that constant means that we enter the loop,
427 // then we fold away the cond branch to an uncond branch. This simplifies the
428 // loop in cases important for nested loops, and it also means we don't have
429 // to split as many edges.
430 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
431 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
432 if (!isa<ConstantInt>(PHBI->getCondition()) ||
433 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
434 != NewHeader) {
435 // The conditional branch can't be folded, handle the general case.
436 // Update DominatorTree to reflect the CFG change we just made. Then split
437 // edges as necessary to preserve LoopSimplify form.
Chandler Carruth73523022014-01-13 13:07:17 +0000438 if (DominatorTreeWrapperPass *DTWP =
439 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
440 DominatorTree &DT = DTWP->getDomTree();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000441 // Everything that was dominated by the old loop header is now dominated
442 // by the original loop preheader. Conceptually the header was merged
443 // into the preheader, even though we reuse the actual block as a new
444 // loop latch.
Chandler Carruth73523022014-01-13 13:07:17 +0000445 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000446 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
447 OrigHeaderNode->end());
Chandler Carruth73523022014-01-13 13:07:17 +0000448 DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000449 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
Chandler Carruth73523022014-01-13 13:07:17 +0000450 DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
Andrew Tricka20f1982012-02-14 00:00:19 +0000451
Chandler Carruth73523022014-01-13 13:07:17 +0000452 assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode);
453 assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode);
Benjamin Kramer3be6a482012-09-01 12:04:51 +0000454
Chris Lattner59c82f82011-01-08 19:59:06 +0000455 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth73523022014-01-13 13:07:17 +0000456 DT.changeImmediateDominator(OrigHeader, OrigLatch);
Chris Lattner59c82f82011-01-08 19:59:06 +0000457 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000458
Chris Lattner59c82f82011-01-08 19:59:06 +0000459 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
Nadav Rotem465834c2012-07-24 10:51:42 +0000460 // thus is not a preheader anymore.
461 // Split the edge to form a real preheader.
Chris Lattner59c82f82011-01-08 19:59:06 +0000462 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
463 NewPH->setName(NewHeader->getName() + ".lr.ph");
Andrew Tricka20f1982012-02-14 00:00:19 +0000464
Nadav Rotem465834c2012-07-24 10:51:42 +0000465 // Preserve canonical loop form, which means that 'Exit' should have only
466 // one predecessor.
Chris Lattner59c82f82011-01-08 19:59:06 +0000467 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
468 ExitSplit->moveBefore(Exit);
469 } else {
470 // We can fold the conditional branch in the preheader, this makes things
471 // simpler. The first step is to remove the extra edge to the Exit block.
472 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
Devang Patelc1f7c1d2011-04-29 20:38:55 +0000473 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
474 NewBI->setDebugLoc(PHBI->getDebugLoc());
Chris Lattner59c82f82011-01-08 19:59:06 +0000475 PHBI->eraseFromParent();
Andrew Tricka20f1982012-02-14 00:00:19 +0000476
Chris Lattner59c82f82011-01-08 19:59:06 +0000477 // With our CFG finalized, update DomTree if it is available.
Chandler Carruth73523022014-01-13 13:07:17 +0000478 if (DominatorTreeWrapperPass *DTWP =
479 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
480 DominatorTree &DT = DTWP->getDomTree();
Chris Lattner59c82f82011-01-08 19:59:06 +0000481 // Update OrigHeader to be dominated by the new header block.
Chandler Carruth73523022014-01-13 13:07:17 +0000482 DT.changeImmediateDominator(NewHeader, OrigPreheader);
483 DT.changeImmediateDominator(OrigHeader, OrigLatch);
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000484
485 // Brute force incremental dominator tree update. Call
486 // findNearestCommonDominator on all CFG predecessors of each child of the
487 // original header.
Chandler Carruth73523022014-01-13 13:07:17 +0000488 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000489 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
490 OrigHeaderNode->end());
491 bool Changed;
492 do {
493 Changed = false;
494 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
495 DomTreeNode *Node = HeaderChildren[I];
496 BasicBlock *BB = Node->getBlock();
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000497
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000498 pred_iterator PI = pred_begin(BB);
499 BasicBlock *NearestDom = *PI;
500 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
Chandler Carruth73523022014-01-13 13:07:17 +0000501 NearestDom = DT.findNearestCommonDominator(NearestDom, *PI);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000502
503 // Remember if this changes the DomTree.
504 if (Node->getIDom()->getBlock() != NearestDom) {
Chandler Carruth73523022014-01-13 13:07:17 +0000505 DT.changeImmediateDominator(BB, NearestDom);
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000506 Changed = true;
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000507 }
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000508 }
509
Benjamin Kramer599a4bb2012-09-02 11:57:22 +0000510 // If the dominator changed, this may have an effect on other
511 // predecessors, continue until we reach a fixpoint.
512 } while (Changed);
Chris Lattner59c82f82011-01-08 19:59:06 +0000513 }
Devang Patelfac4d1f2007-07-11 23:47:28 +0000514 }
Andrew Tricka20f1982012-02-14 00:00:19 +0000515
Chris Lattner59c82f82011-01-08 19:59:06 +0000516 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000517 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000518
Chris Lattner63fe78d2011-01-11 07:47:59 +0000519 // Now that the CFG and DomTree are in a consistent state again, try to merge
520 // the OrigHeader block into OrigLatch. This will succeed if they are
521 // connected by an unconditional branch. This is just a cleanup so the
522 // emitted code isn't too gross in this common case.
523 MergeBlockIntoPredecessor(OrigHeader, this);
Andrew Tricka20f1982012-02-14 00:00:19 +0000524
Benjamin Kramerafdfdb52012-08-30 15:39:42 +0000525 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
526
Chris Lattnerfee37c52011-01-08 18:55:50 +0000527 ++NumRotated;
528 return true;
Devang Patel85419782007-04-09 20:19:46 +0000529}