blob: 079ff92d4540025b8e1985e3106e214602eb2d9a [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"
16#include "llvm/Function.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/LoopPass.h"
19#include "llvm/Analysis/InstructionSimplify.h"
Devang Patelfac4d1f2007-07-11 23:47:28 +000020#include "llvm/Analysis/ScalarEvolution.h"
Devang Patelf42389f2007-04-07 01:25:15 +000021#include "llvm/Transforms/Utils/Local.h"
Devang Patelfac4d1f2007-07-11 23:47:28 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohmanb9797942009-10-24 23:19:52 +000023#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner2b3f20e2011-01-08 07:21:31 +000024#include "llvm/Transforms/Utils/ValueMapper.h"
Devang Patelf42389f2007-04-07 01:25:15 +000025#include "llvm/Support/Debug.h"
26#include "llvm/ADT/Statistic.h"
Devang Patelf42389f2007-04-07 01:25:15 +000027using namespace llvm;
28
29#define MAX_HEADER_SIZE 16
30
31STATISTIC(NumRotated, "Number of loops rotated");
32namespace {
33
Chris Lattner2dd09db2009-09-02 06:11:42 +000034 class LoopRotate : public LoopPass {
Devang Patelf42389f2007-04-07 01:25:15 +000035 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000036 static char ID; // Pass ID, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000037 LoopRotate() : LoopPass(ID) {
38 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
39 }
Devang Patel09f162c2007-05-01 21:15:47 +000040
Devang Patel88bc2c62007-04-09 16:11:48 +000041 // LCSSA form makes instruction renaming easier.
Devang Patelf42389f2007-04-07 01:25:15 +000042 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanefd7f9c2010-07-16 17:58:45 +000043 AU.addPreserved<DominatorTree>();
Dan Gohmanefd7f9c2010-07-16 17:58:45 +000044 AU.addRequired<LoopInfo>();
45 AU.addPreserved<LoopInfo>();
Devang Patela42c3142008-02-15 01:24:49 +000046 AU.addRequiredID(LoopSimplifyID);
47 AU.addPreservedID(LoopSimplifyID);
Devang Patelf42389f2007-04-07 01:25:15 +000048 AU.addRequiredID(LCSSAID);
49 AU.addPreservedID(LCSSAID);
Devang Patelfac4d1f2007-07-11 23:47:28 +000050 AU.addPreserved<ScalarEvolution>();
Devang Patelf42389f2007-04-07 01:25:15 +000051 }
52
Chris Lattnerfee37c52011-01-08 18:55:50 +000053 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner385f2ec2011-01-08 17:48:33 +000054 bool rotateLoop(Loop *L);
Devang Patelf42389f2007-04-07 01:25:15 +000055
Devang Patelf42389f2007-04-07 01:25:15 +000056 private:
Chris Lattner25ba40a2011-01-08 17:38:45 +000057 LoopInfo *LI;
Devang Patelf42389f2007-04-07 01:25:15 +000058 };
Devang Patelf42389f2007-04-07 01:25:15 +000059}
Dan Gohmand78c4002008-05-13 00:00:25 +000060
61char LoopRotate::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000062INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +000063INITIALIZE_PASS_DEPENDENCY(LoopInfo)
64INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
65INITIALIZE_PASS_DEPENDENCY(LCSSA)
Owen Anderson8ac477f2010-10-12 19:48:12 +000066INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
Devang Patelf42389f2007-04-07 01:25:15 +000067
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +000068Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelf42389f2007-04-07 01:25:15 +000069
Devang Patel88bc2c62007-04-09 16:11:48 +000070/// Rotate Loop L as many times as possible. Return true if
Dan Gohman091e4402009-06-25 00:22:44 +000071/// the loop is rotated at least once.
Chris Lattner385f2ec2011-01-08 17:48:33 +000072bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner25ba40a2011-01-08 17:38:45 +000073 LI = &getAnalysis<LoopInfo>();
Devang Patelfac4d1f2007-07-11 23:47:28 +000074
Devang Patelf42389f2007-04-07 01:25:15 +000075 // One loop can be rotated multiple times.
Chris Lattner25ba40a2011-01-08 17:38:45 +000076 bool MadeChange = false;
Chris Lattner385f2ec2011-01-08 17:48:33 +000077 while (rotateLoop(L))
Chris Lattner25ba40a2011-01-08 17:38:45 +000078 MadeChange = true;
Devang Patelf42389f2007-04-07 01:25:15 +000079
Chris Lattner25ba40a2011-01-08 17:38:45 +000080 return MadeChange;
Devang Patelf42389f2007-04-07 01:25:15 +000081}
82
Dan Gohmanb5650eb2007-05-11 21:10:54 +000083/// Rotate loop LP. Return true if the loop is rotated.
Chris Lattner385f2ec2011-01-08 17:48:33 +000084bool LoopRotate::rotateLoop(Loop *L) {
Dan Gohman091e4402009-06-25 00:22:44 +000085 // If the loop has only one block then there is not much to rotate.
Devang Patel88bc2c62007-04-09 16:11:48 +000086 if (L->getBlocks().size() == 1)
Devang Patelf42389f2007-04-07 01:25:15 +000087 return false;
Chris Lattner7fab23b2011-01-08 18:06:22 +000088
89 BasicBlock *OrigHeader = L->getHeader();
90
91 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
92 if (BI == 0 || BI->isUnconditional())
93 return false;
94
Dan Gohman091e4402009-06-25 00:22:44 +000095 // If the loop header is not one of the loop exiting blocks then
96 // either this loop is already rotated or it is not
Devang Patelf42389f2007-04-07 01:25:15 +000097 // suitable for loop rotation transformations.
Dan Gohman8f4078b2009-10-24 23:34:26 +000098 if (!L->isLoopExiting(OrigHeader))
Devang Patelf42389f2007-04-07 01:25:15 +000099 return false;
100
Devang Patel88bc2c62007-04-09 16:11:48 +0000101 // Updating PHInodes in loops with multiple exits adds complexity.
102 // Keep it simple, and restrict loop rotation to loops with one exit only.
103 // In future, lift this restriction and support for multiple exits if
104 // required.
Devang Patelb5933bb2007-08-21 00:31:24 +0000105 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelf42389f2007-04-07 01:25:15 +0000106 L->getExitBlocks(ExitBlocks);
107 if (ExitBlocks.size() > 1)
108 return false;
109
Chris Lattner679572e2011-01-02 07:35:53 +0000110 // Check size of original header and reject loop if it is very big.
111 {
112 CodeMetrics Metrics;
113 Metrics.analyzeBasicBlock(OrigHeader);
114 if (Metrics.NumInsts > MAX_HEADER_SIZE)
115 return false;
Devang Patelbab43b42009-03-06 03:51:30 +0000116 }
117
Devang Patelfac4d1f2007-07-11 23:47:28 +0000118 // Now, this loop is suitable for rotation.
Chris Lattner7fab23b2011-01-08 18:06:22 +0000119 BasicBlock *OrigPreHeader = L->getLoopPreheader();
120 BasicBlock *OrigLatch = L->getLoopLatch();
121 assert(OrigPreHeader && OrigLatch && "Loop not in canonical form?");
Devang Patelfac4d1f2007-07-11 23:47:28 +0000122
Dan Gohmanfc20b672009-09-27 15:37:03 +0000123 // Anything ScalarEvolution may know about this loop or the PHI nodes
124 // in its header will soon be invalidated.
125 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
Dan Gohman880c92a2009-10-31 15:04:55 +0000126 SE->forgetLoop(L);
Dan Gohmanfc20b672009-09-27 15:37:03 +0000127
Devang Patelf42389f2007-04-07 01:25:15 +0000128 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattner57cb4722009-01-26 01:57:01 +0000129 // that is inside loop. Header's other successor is outside the
130 // loop. Otherwise loop is not suitable for rotation.
Chris Lattner385f2ec2011-01-08 17:48:33 +0000131 BasicBlock *Exit = BI->getSuccessor(0);
132 BasicBlock *NewHeader = BI->getSuccessor(1);
Devang Patel88bc2c62007-04-09 16:11:48 +0000133 if (L->contains(Exit))
134 std::swap(Exit, NewHeader);
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000135 assert(NewHeader && "Unable to determine new loop header");
Devang Patel88bc2c62007-04-09 16:11:48 +0000136 assert(L->contains(NewHeader) && !L->contains(Exit) &&
137 "Unable to determine loop header and exit blocks");
Chris Lattner7b6647c2009-01-26 02:11:30 +0000138
Dan Gohman091e4402009-06-25 00:22:44 +0000139 // This code assumes that the new header has exactly one predecessor.
140 // Remove any single-entry PHI nodes in it.
Chris Lattner7b6647c2009-01-26 02:11:30 +0000141 assert(NewHeader->getSinglePredecessor() &&
142 "New header doesn't have one pred!");
143 FoldSingleEntryPHINodes(NewHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000144
Dan Gohmanb9797942009-10-24 23:19:52 +0000145 // Begin by walking OrigHeader and populating ValueMap with an entry for
146 // each Instruction.
Devang Patel88bc2c62007-04-09 16:11:48 +0000147 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000148 ValueToValueMapTy ValueMap;
Devang Patelb9af5742007-04-09 19:04:21 +0000149
Dan Gohmanb9797942009-10-24 23:19:52 +0000150 // For PHI nodes, the value available in OldPreHeader is just the
151 // incoming value from OldPreHeader.
152 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
153 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
Devang Patelf42389f2007-04-07 01:25:15 +0000154
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000155 // For the rest of the instructions, either hoist to the OrigPreheader if
156 // possible or create a clone in the OldPreHeader if not.
Dan Gohmanb9797942009-10-24 23:19:52 +0000157 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
Chris Lattnerb01c24a2010-09-06 01:10:22 +0000158 while (I != E) {
159 Instruction *Inst = I++;
160
161 // If the instruction's operands are invariant and it doesn't read or write
162 // memory, then it is safe to hoist. Doing this doesn't change the order of
163 // execution in the preheader, but does prevent the instruction from
164 // executing in each iteration of the loop. This means it is safe to hoist
165 // something that might trap, but isn't safe to hoist something that reads
166 // memory (without proving that the loop doesn't write).
167 if (L->hasLoopInvariantOperands(Inst) &&
168 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
169 !isa<TerminatorInst>(Inst)) {
170 Inst->moveBefore(LoopEntryBranch);
171 continue;
172 }
173
174 // Otherwise, create a duplicate of the instruction.
175 Instruction *C = Inst->clone();
Chris Lattner43f8d162011-01-08 08:15:20 +0000176
Chris Lattner8c5defd2011-01-08 08:24:46 +0000177 // Eagerly remap the operands of the instruction.
178 RemapInstruction(C, ValueMap,
179 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
180
181 // With the operands remapped, see if the instruction constant folds or is
182 // otherwise simplifyable. This commonly occurs because the entry from PHI
183 // nodes allows icmps and other instructions to fold.
Chris Lattner25ba40a2011-01-08 17:38:45 +0000184 Value *V = SimplifyInstruction(C);
185 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
Chris Lattner8c5defd2011-01-08 08:24:46 +0000186 // If so, then delete the temporary instruction and stick the folded value
187 // in the map.
188 delete C;
189 ValueMap[Inst] = V;
190 } else {
191 // Otherwise, stick the new instruction into the new block!
192 C->setName(Inst->getName());
193 C->insertBefore(LoopEntryBranch);
194 ValueMap[Inst] = C;
195 }
Devang Patelf42389f2007-04-07 01:25:15 +0000196 }
197
Dan Gohmanb9797942009-10-24 23:19:52 +0000198 // Along with all the other instructions, we just cloned OrigHeader's
199 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
200 // successors by duplicating their incoming values for OrigHeader.
201 TerminatorInst *TI = OrigHeader->getTerminator();
202 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
203 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
204 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
205 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
Devang Patelf42389f2007-04-07 01:25:15 +0000206
Dan Gohmanb9797942009-10-24 23:19:52 +0000207 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
208 // OrigPreHeader's old terminator (the original branch into the loop), and
209 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
210 LoopEntryBranch->eraseFromParent();
211 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
212 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
Devang Patelf42389f2007-04-07 01:25:15 +0000213
Dan Gohman6a10d5e2009-10-26 15:55:24 +0000214 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
Dan Gohmanb9797942009-10-24 23:19:52 +0000215 // as necessary.
216 SSAUpdater SSA;
217 for (I = OrigHeader->begin(); I != E; ++I) {
218 Value *OrigHeaderVal = I;
219 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
Devang Patelf42389f2007-04-07 01:25:15 +0000220
Chris Lattner2b3f20e2011-01-08 07:21:31 +0000221 // If there are no uses of the value (e.g. because it returns void), there
222 // is nothing to rewrite.
223 if (OrigHeaderVal->use_empty() && OrigPreHeaderVal->use_empty())
224 continue;
225
Dan Gohmanb9797942009-10-24 23:19:52 +0000226 // The value now exits in two versions: the initial value in the preheader
227 // and the loop "next" value in the original header.
Duncan Sands67781492010-09-02 08:14:03 +0000228 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
Dan Gohmanb9797942009-10-24 23:19:52 +0000229 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
230 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
Devang Patelf42389f2007-04-07 01:25:15 +0000231
Dan Gohmanb9797942009-10-24 23:19:52 +0000232 // Visit each use of the OrigHeader instruction.
233 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
234 UE = OrigHeaderVal->use_end(); UI != UE; ) {
235 // Grab the use before incrementing the iterator.
236 Use &U = UI.getUse();
Devang Patelf42389f2007-04-07 01:25:15 +0000237
Dan Gohmanb9797942009-10-24 23:19:52 +0000238 // Increment the iterator before removing the use from the list.
239 ++UI;
240
241 // SSAUpdater can't handle a non-PHI use in the same block as an
242 // earlier def. We can easily handle those cases manually.
243 Instruction *UserInst = cast<Instruction>(U.getUser());
244 if (!isa<PHINode>(UserInst)) {
245 BasicBlock *UserBB = UserInst->getParent();
246
247 // The original users in the OrigHeader are already using the
248 // original definitions.
249 if (UserBB == OrigHeader)
Devang Patelb28a3912007-04-09 16:21:29 +0000250 continue;
251
Dan Gohmanb9797942009-10-24 23:19:52 +0000252 // Users in the OrigPreHeader need to use the value to which the
253 // original definitions are mapped.
254 if (UserBB == OrigPreHeader) {
255 U = OrigPreHeaderVal;
Devang Patelf42389f2007-04-07 01:25:15 +0000256 continue;
Dan Gohmanb9797942009-10-24 23:19:52 +0000257 }
Devang Patelf42389f2007-04-07 01:25:15 +0000258 }
259
Dan Gohmanb9797942009-10-24 23:19:52 +0000260 // Anything else can be handled by SSAUpdater.
261 SSA.RewriteUse(U);
Devang Patelf42389f2007-04-07 01:25:15 +0000262 }
263 }
Devang Patelf42389f2007-04-07 01:25:15 +0000264
Dan Gohmanb9797942009-10-24 23:19:52 +0000265 // NewHeader is now the header of the loop.
Devang Patelf42389f2007-04-07 01:25:15 +0000266 L->moveToHeader(NewHeader);
267
Dan Gohman5047ca02010-08-17 17:39:21 +0000268 // Move the original header to the bottom of the loop, where it now more
269 // naturally belongs. This isn't necessary for correctness, and CodeGen can
270 // usually reorder blocks on its own to fix things like this up, but it's
271 // still nice to keep the IR readable.
272 //
273 // The original header should have only one predecessor at this point, since
274 // we checked that the loop had a proper preheader and unique backedge before
275 // we started.
276 assert(OrigHeader->getSinglePredecessor() &&
277 "Original loop header has too many predecessors after loop rotation!");
278 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
279
280 // Also, since this original header only has one predecessor, zap its
281 // PHI nodes, which are now trivial.
282 FoldSingleEntryPHINodes(OrigHeader);
Chris Lattner063dca02011-01-08 18:52:51 +0000283
Chris Lattnerfee37c52011-01-08 18:55:50 +0000284
285
286 // Update DominatorTree to reflect the CFG change we just made. Then split
287 // edges as necessary to preserve LoopSimplify form.
Chris Lattner063dca02011-01-08 18:52:51 +0000288 assert(L->getHeader() == NewHeader && "Latch block is our new header");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000289
Duncan Sands5a913d62009-01-28 13:14:17 +0000290 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Chris Lattner063dca02011-01-08 18:52:51 +0000291 // Since OrigPreheader now has the conditional branch to Exit block, it is
292 // the dominator of Exit.
Devang Patelfac4d1f2007-07-11 23:47:28 +0000293 DT->changeImmediateDominator(Exit, OrigPreHeader);
Chris Lattner063dca02011-01-08 18:52:51 +0000294 DT->changeImmediateDominator(NewHeader, OrigPreHeader);
295
296 // Update OrigHeader to be dominated by the new header block.
Devang Patelfac4d1f2007-07-11 23:47:28 +0000297 DT->changeImmediateDominator(OrigHeader, OrigLatch);
298 }
Chris Lattner063dca02011-01-08 18:52:51 +0000299
300 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
301 // thus is not a preheader anymore. Split the edge to form a real preheader.
302 BasicBlock *NewPH = SplitCriticalEdge(OrigPreHeader, NewHeader, this);
303 NewPH->setName(NewHeader->getName() + ".lr.ph");
304
Chris Lattnerfee37c52011-01-08 18:55:50 +0000305 // Preserve canonical loop form, which means that 'Exit' should have only one
Chris Lattner063dca02011-01-08 18:52:51 +0000306 // predecessor.
307 SplitCriticalEdge(L->getLoopLatch(), Exit, this);
Chris Lattnerfee37c52011-01-08 18:55:50 +0000308
Chris Lattner063dca02011-01-08 18:52:51 +0000309 assert(L->getLoopPreheader() == NewPH &&
Chris Lattnerd67aaa62009-01-26 01:38:24 +0000310 "Invalid loop preheader after loop rotation");
Chris Lattner063dca02011-01-08 18:52:51 +0000311 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
Chris Lattnerfee37c52011-01-08 18:55:50 +0000312
313
314 // TODO: We could just go ahead and merge OrigHeader into its predecessor
315 // at this point, if we don't mind updating dominator info.
316
317 ++NumRotated;
318 return true;
Devang Patel85419782007-04-09 20:19:46 +0000319}
Chris Lattnerfee37c52011-01-08 18:55:50 +0000320
321