blob: d2b20fa611e04537591092c3cdd85537990f88e2 [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 Patel3f43a702009-03-06 03:51:30 +000017#include "llvm/IntrinsicInst.h"
Devang Patelc4625da2007-04-07 01:25:15 +000018#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/LoopPass.h"
Devang Patel990e8662007-07-11 23:47:28 +000020#include "llvm/Analysis/Dominators.h"
21#include "llvm/Analysis/ScalarEvolution.h"
Devang Patelc4625da2007-04-07 01:25:15 +000022#include "llvm/Transforms/Utils/Local.h"
Devang Patel990e8662007-07-11 23:47:28 +000023#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Devang Patelc4625da2007-04-07 01:25:15 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/SmallVector.h"
Devang Patelc4625da2007-04-07 01:25:15 +000028using namespace llvm;
29
30#define MAX_HEADER_SIZE 16
31
32STATISTIC(NumRotated, "Number of loops rotated");
33namespace {
34
Devang Patel32231332007-04-09 16:11:48 +000035 class VISIBILITY_HIDDEN RenameData {
Devang Patelc4625da2007-04-07 01:25:15 +000036 public:
Devang Patele9881542007-04-09 19:04:21 +000037 RenameData(Instruction *O, Value *P, Instruction *H)
Devang Patel32231332007-04-09 16:11:48 +000038 : Original(O), PreHeader(P), Header(H) { }
Devang Patelc4625da2007-04-07 01:25:15 +000039 public:
40 Instruction *Original; // Original instruction
Devang Patele9881542007-04-09 19:04:21 +000041 Value *PreHeader; // Original pre-header replacement
Devang Patelc4625da2007-04-07 01:25:15 +000042 Instruction *Header; // New header replacement
43 };
Devang Patel32231332007-04-09 16:11:48 +000044
Devang Patelc4625da2007-04-07 01:25:15 +000045 class VISIBILITY_HIDDEN LoopRotate : public LoopPass {
46
47 public:
Devang Patel19974732007-05-03 01:11:54 +000048 static char ID; // Pass ID, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000049 LoopRotate() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000050
Devang Patel32231332007-04-09 16:11:48 +000051 // Rotate Loop L as many times as possible. Return true if
52 // loop is rotated at least once.
Devang Patelc4625da2007-04-07 01:25:15 +000053 bool runOnLoop(Loop *L, LPPassManager &LPM);
Devang Patel32231332007-04-09 16:11:48 +000054
55 // LCSSA form makes instruction renaming easier.
Devang Patelc4625da2007-04-07 01:25:15 +000056 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel9d9b2042008-02-15 01:24:49 +000057 AU.addRequiredID(LoopSimplifyID);
58 AU.addPreservedID(LoopSimplifyID);
Devang Patelc4625da2007-04-07 01:25:15 +000059 AU.addRequiredID(LCSSAID);
60 AU.addPreservedID(LCSSAID);
Devang Patel990e8662007-07-11 23:47:28 +000061 AU.addPreserved<ScalarEvolution>();
62 AU.addPreserved<LoopInfo>();
Devang Pateld9a6dcb2007-07-30 20:22:53 +000063 AU.addPreserved<DominatorTree>();
64 AU.addPreserved<DominanceFrontier>();
Devang Patelc4625da2007-04-07 01:25:15 +000065 }
66
67 // Helper functions
68
69 /// Do actual work
70 bool rotateLoop(Loop *L, LPPassManager &LPM);
71
72 /// Initialize local data
73 void initialize();
74
75 /// Make sure all Exit block PHINodes have required incoming values.
76 /// If incoming value is constant or defined outside the loop then
Devang Patele9881542007-04-09 19:04:21 +000077 /// PHINode may not have an entry for original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +000078 void updateExitBlock();
79
80 /// Return true if this instruction is used outside original header.
81 bool usedOutsideOriginalHeader(Instruction *In);
82
83 /// Find Replacement information for instruction. Return NULL if it is
84 /// not available.
Devang Patel4522c8a2007-04-09 17:09:13 +000085 const RenameData *findReplacementData(Instruction *I);
Devang Patelc4625da2007-04-07 01:25:15 +000086
Devang Patel5464b962007-04-09 20:19:46 +000087 /// After loop rotation, loop pre-header has multiple sucessors.
88 /// Insert one forwarding basic block to ensure that loop pre-header
89 /// has only one successor.
90 void preserveCanonicalLoopForm(LPPassManager &LPM);
91
Devang Patelc4625da2007-04-07 01:25:15 +000092 private:
93
94 Loop *L;
95 BasicBlock *OrigHeader;
96 BasicBlock *OrigPreHeader;
97 BasicBlock *OrigLatch;
98 BasicBlock *NewHeader;
Devang Patelc4625da2007-04-07 01:25:15 +000099 BasicBlock *Exit;
Devang Patel990e8662007-07-11 23:47:28 +0000100 LPPassManager *LPM_Ptr;
Devang Patel32231332007-04-09 16:11:48 +0000101 SmallVector<RenameData, MAX_HEADER_SIZE> LoopHeaderInfo;
Devang Patelc4625da2007-04-07 01:25:15 +0000102 };
Devang Patelc4625da2007-04-07 01:25:15 +0000103}
Dan Gohman844731a2008-05-13 00:00:25 +0000104
105char LoopRotate::ID = 0;
106static RegisterPass<LoopRotate> X("loop-rotate", "Rotate Loops");
Devang Patelc4625da2007-04-07 01:25:15 +0000107
Daniel Dunbar394f0442008-10-22 23:32:42 +0000108Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
Devang Patelc4625da2007-04-07 01:25:15 +0000109
Devang Patel32231332007-04-09 16:11:48 +0000110/// Rotate Loop L as many times as possible. Return true if
Dan Gohmancc4e6052009-06-25 00:22:44 +0000111/// the loop is rotated at least once.
Devang Patelc4625da2007-04-07 01:25:15 +0000112bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
Devang Patel990e8662007-07-11 23:47:28 +0000113
Devang Patelc4625da2007-04-07 01:25:15 +0000114 bool RotatedOneLoop = false;
115 initialize();
Devang Patel990e8662007-07-11 23:47:28 +0000116 LPM_Ptr = &LPM;
Devang Patelc4625da2007-04-07 01:25:15 +0000117
118 // One loop can be rotated multiple times.
119 while (rotateLoop(Lp,LPM)) {
120 RotatedOneLoop = true;
121 initialize();
122 }
123
124 return RotatedOneLoop;
125}
126
Dan Gohman23d9d272007-05-11 21:10:54 +0000127/// Rotate loop LP. Return true if the loop is rotated.
Devang Patelc4625da2007-04-07 01:25:15 +0000128bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
Devang Patelc4625da2007-04-07 01:25:15 +0000129 L = Lp;
Devang Patelc4625da2007-04-07 01:25:15 +0000130
131 OrigHeader = L->getHeader();
132 OrigPreHeader = L->getLoopPreheader();
133 OrigLatch = L->getLoopLatch();
134
Dan Gohmancc4e6052009-06-25 00:22:44 +0000135 // If the loop has only one block then there is not much to rotate.
Devang Patel32231332007-04-09 16:11:48 +0000136 if (L->getBlocks().size() == 1)
Devang Patelc4625da2007-04-07 01:25:15 +0000137 return false;
138
Chris Lattner2ba25432009-01-26 01:38:24 +0000139 assert(OrigHeader && OrigLatch && OrigPreHeader &&
140 "Loop is not in canonical form");
Devang Patele9881542007-04-09 19:04:21 +0000141
Dan Gohmancc4e6052009-06-25 00:22:44 +0000142 // If the loop header is not one of the loop exiting blocks then
143 // either this loop is already rotated or it is not
Devang Patelc4625da2007-04-07 01:25:15 +0000144 // suitable for loop rotation transformations.
145 if (!L->isLoopExit(OrigHeader))
146 return false;
147
148 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
149 if (!BI)
150 return false;
Chris Lattner2ba25432009-01-26 01:38:24 +0000151 assert(BI->isConditional() && "Branch Instruction is not conditional");
Devang Patelc4625da2007-04-07 01:25:15 +0000152
Devang Patel32231332007-04-09 16:11:48 +0000153 // Updating PHInodes in loops with multiple exits adds complexity.
154 // Keep it simple, and restrict loop rotation to loops with one exit only.
155 // In future, lift this restriction and support for multiple exits if
156 // required.
Devang Patelb7211a22007-08-21 00:31:24 +0000157 SmallVector<BasicBlock*, 8> ExitBlocks;
Devang Patelc4625da2007-04-07 01:25:15 +0000158 L->getExitBlocks(ExitBlocks);
159 if (ExitBlocks.size() > 1)
160 return false;
161
Devang Patel990e8662007-07-11 23:47:28 +0000162 // Check size of original header and reject
163 // loop if it is very big.
Devang Patel3f43a702009-03-06 03:51:30 +0000164 unsigned Size = 0;
165
166 // FIXME: Use common api to estimate size.
167 for (BasicBlock::const_iterator OI = OrigHeader->begin(),
168 OE = OrigHeader->end(); OI != OE; ++OI) {
169 if (isa<PHINode>(OI))
170 continue; // PHI nodes don't count.
171 if (isa<DbgInfoIntrinsic>(OI))
172 continue; // Debug intrinsics don't count as size.
173 Size++;
174 }
175
176 if (Size > MAX_HEADER_SIZE)
Devang Patel990e8662007-07-11 23:47:28 +0000177 return false;
178
179 // Now, this loop is suitable for rotation.
180
Devang Patelc4625da2007-04-07 01:25:15 +0000181 // Find new Loop header. NewHeader is a Header's one and only successor
Chris Lattnerf6784a32009-01-26 01:57:01 +0000182 // that is inside loop. Header's other successor is outside the
183 // loop. Otherwise loop is not suitable for rotation.
Devang Patel32231332007-04-09 16:11:48 +0000184 Exit = BI->getSuccessor(0);
185 NewHeader = BI->getSuccessor(1);
186 if (L->contains(Exit))
187 std::swap(Exit, NewHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000188 assert(NewHeader && "Unable to determine new loop header");
Devang Patel32231332007-04-09 16:11:48 +0000189 assert(L->contains(NewHeader) && !L->contains(Exit) &&
190 "Unable to determine loop header and exit blocks");
Chris Lattner3796a262009-01-26 02:11:30 +0000191
Dan Gohmancc4e6052009-06-25 00:22:44 +0000192 // This code assumes that the new header has exactly one predecessor.
193 // Remove any single-entry PHI nodes in it.
Chris Lattner3796a262009-01-26 02:11:30 +0000194 assert(NewHeader->getSinglePredecessor() &&
195 "New header doesn't have one pred!");
196 FoldSingleEntryPHINodes(NewHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000197
Dan Gohmancc4e6052009-06-25 00:22:44 +0000198 // Copy PHI nodes and other instructions from the original header
199 // into the original pre-header. Unlike the original header, the original
200 // pre-header is not a member of the loop.
Devang Patelc4625da2007-04-07 01:25:15 +0000201 //
Dan Gohmancc4e6052009-06-25 00:22:44 +0000202 // The new loop header is the one and only successor of original header that
Devang Patelc4625da2007-04-07 01:25:15 +0000203 // is inside the loop. All other original header successors are outside
Dan Gohmancc4e6052009-06-25 00:22:44 +0000204 // the loop. Copy PHI Nodes from the original header into the new loop header.
Devang Patele9881542007-04-09 19:04:21 +0000205 // Add second incoming value, from original loop pre-header into these phi
Devang Patelc4625da2007-04-07 01:25:15 +0000206 // nodes. If a value defined in original header is used outside original
207 // header then new loop header will need new phi nodes with two incoming
208 // values, one definition from original header and second definition is
Devang Patele9881542007-04-09 19:04:21 +0000209 // from original loop pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000210
Devang Patele9881542007-04-09 19:04:21 +0000211 // Remove terminator from Original pre-header. Original pre-header will
212 // receive a clone of original header terminator as a new terminator.
213 OrigPreHeader->getInstList().pop_back();
Devang Patel32231332007-04-09 16:11:48 +0000214 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
Chris Lattnerf6784a32009-01-26 01:57:01 +0000215 PHINode *PN = 0;
Devang Patel4522c8a2007-04-09 17:09:13 +0000216 for (; (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patele9881542007-04-09 19:04:21 +0000217 // PHI nodes are not copied into original pre-header. Instead their values
218 // are directly propagated.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000219 Value *NPV = PN->getIncomingValueForBlock(OrigPreHeader);
Devang Patele9881542007-04-09 19:04:21 +0000220
Dan Gohmancc4e6052009-06-25 00:22:44 +0000221 // Create a new PHI node with two incoming values for NewHeader.
222 // One incoming value is from OrigLatch (through OrigHeader) and the
Devang Patele9881542007-04-09 19:04:21 +0000223 // second incoming value is from original pre-header.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000224 PHINode *NH = PHINode::Create(PN->getType(), PN->getName(),
Dan Gohman610c0e22008-06-19 17:37:25 +0000225 NewHeader->begin());
Devang Patel32231332007-04-09 16:11:48 +0000226 NH->addIncoming(PN->getIncomingValueForBlock(OrigLatch), OrigHeader);
Devang Patele9881542007-04-09 19:04:21 +0000227 NH->addIncoming(NPV, OrigPreHeader);
Devang Patel32231332007-04-09 16:11:48 +0000228
Devang Patele9881542007-04-09 19:04:21 +0000229 // "In" can be replaced by NH at various places.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000230 LoopHeaderInfo.push_back(RenameData(PN, NPV, NH));
Devang Patel32231332007-04-09 16:11:48 +0000231 }
Devang Patelc4625da2007-04-07 01:25:15 +0000232
Devang Patel32231332007-04-09 16:11:48 +0000233 // Now, handle non-phi instructions.
234 for (; I != E; ++I) {
235 Instruction *In = I;
Chris Lattner2ba25432009-01-26 01:38:24 +0000236 assert(!isa<PHINode>(In) && "PHINode is not expected here");
Chris Lattnerf6784a32009-01-26 01:57:01 +0000237
Devang Patele9881542007-04-09 19:04:21 +0000238 // This is not a PHI instruction. Insert its clone into original pre-header.
Devang Patel32231332007-04-09 16:11:48 +0000239 // If this instruction is using a value from same basic block then
240 // update it to use value from cloned instruction.
Owen Andersone922c022009-07-22 00:24:57 +0000241 Instruction *C = In->clone(In->getContext());
Owen Anderson6bc41e82008-04-14 17:38:21 +0000242 C->setName(In->getName());
Devang Patele9881542007-04-09 19:04:21 +0000243 OrigPreHeader->getInstList().push_back(C);
244
245 for (unsigned opi = 0, e = In->getNumOperands(); opi != e; ++opi) {
Chris Lattnerf6784a32009-01-26 01:57:01 +0000246 Instruction *OpInsn = dyn_cast<Instruction>(In->getOperand(opi));
247 if (!OpInsn) continue; // Ignore non-instruction values.
248 if (const RenameData *D = findReplacementData(OpInsn))
249 C->setOperand(opi, D->PreHeader);
Devang Patele9881542007-04-09 19:04:21 +0000250 }
251
Devang Patel32231332007-04-09 16:11:48 +0000252 // If this instruction is used outside this basic block then
253 // create new PHINode for this instruction.
254 Instruction *NewHeaderReplacement = NULL;
255 if (usedOutsideOriginalHeader(In)) {
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000256 PHINode *PN = PHINode::Create(In->getType(), In->getName(),
257 NewHeader->begin());
258 PN->addIncoming(In, OrigHeader);
259 PN->addIncoming(C, OrigPreHeader);
260 NewHeaderReplacement = PN;
Dale Johannesen79602672008-05-01 22:27:44 +0000261 }
Devang Patel32231332007-04-09 16:11:48 +0000262 LoopHeaderInfo.push_back(RenameData(In, C, NewHeaderReplacement));
Devang Patelc4625da2007-04-07 01:25:15 +0000263 }
264
Devang Patelc4625da2007-04-07 01:25:15 +0000265 // Rename uses of original header instructions to reflect their new
Devang Patele9881542007-04-09 19:04:21 +0000266 // definitions (either from original pre-header node or from newly created
Devang Patelc4625da2007-04-07 01:25:15 +0000267 // new header PHINodes.
268 //
269 // Original header instructions are used in
270 // 1) Original header:
271 //
272 // If instruction is used in non-phi instructions then it is using
273 // defintion from original heder iteself. Do not replace this use
Devang Patele9881542007-04-09 19:04:21 +0000274 // with definition from new header or original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000275 //
276 // If instruction is used in phi node then it is an incoming
277 // value. Rename its use to reflect new definition from new-preheader
278 // or new header.
279 //
280 // 2) Inside loop but not in original header
281 //
282 // Replace this use to reflect definition from new header.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000283 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
Devang Patel4522c8a2007-04-09 17:09:13 +0000284 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
Devang Patelc4625da2007-04-07 01:25:15 +0000285
Devang Patel32231332007-04-09 16:11:48 +0000286 if (!ILoopHeaderInfo.Header)
Devang Patelc4625da2007-04-07 01:25:15 +0000287 continue;
288
Devang Patel32231332007-04-09 16:11:48 +0000289 Instruction *OldPhi = ILoopHeaderInfo.Original;
290 Instruction *NewPhi = ILoopHeaderInfo.Header;
Devang Patelc4625da2007-04-07 01:25:15 +0000291
292 // Before replacing uses, collect them first, so that iterator is
293 // not invalidated.
294 SmallVector<Instruction *, 16> AllUses;
295 for (Value::use_iterator UI = OldPhi->use_begin(), UE = OldPhi->use_end();
Chris Lattnerf6784a32009-01-26 01:57:01 +0000296 UI != UE; ++UI)
297 AllUses.push_back(cast<Instruction>(UI));
Devang Patelc4625da2007-04-07 01:25:15 +0000298
299 for (SmallVector<Instruction *, 16>::iterator UI = AllUses.begin(),
300 UE = AllUses.end(); UI != UE; ++UI) {
301 Instruction *U = *UI;
302 BasicBlock *Parent = U->getParent();
303
304 // Used inside original header
305 if (Parent == OrigHeader) {
306 // Do not rename uses inside original header non-phi instructions.
Devang Patelc4625da2007-04-07 01:25:15 +0000307 PHINode *PU = dyn_cast<PHINode>(U);
Devang Patel24a1c492007-04-09 16:21:29 +0000308 if (!PU)
309 continue;
310
Devang Patelc4625da2007-04-07 01:25:15 +0000311 // Do not rename uses inside original header phi nodes, if the
312 // incoming value is for new header.
313 if (PU->getBasicBlockIndex(NewHeader) != -1
314 && PU->getIncomingValueForBlock(NewHeader) == U)
315 continue;
Devang Patel4522c8a2007-04-09 17:09:13 +0000316
Devang Patelc4625da2007-04-07 01:25:15 +0000317 U->replaceUsesOfWith(OldPhi, NewPhi);
318 continue;
319 }
320
321 // Used inside loop, but not in original header.
322 if (L->contains(U->getParent())) {
Devang Patel24a1c492007-04-09 16:21:29 +0000323 if (U != NewPhi)
Devang Patelc4625da2007-04-07 01:25:15 +0000324 U->replaceUsesOfWith(OldPhi, NewPhi);
325 continue;
326 }
Nick Lewycky8f5149e2007-07-07 16:23:34 +0000327
Devang Patel990e8662007-07-11 23:47:28 +0000328 // Used inside Exit Block. Since we are in LCSSA form, U must be PHINode.
329 if (U->getParent() == Exit) {
Chris Lattner2ba25432009-01-26 01:38:24 +0000330 assert(isa<PHINode>(U) && "Use in Exit Block that is not PHINode");
Devang Patel990e8662007-07-11 23:47:28 +0000331
332 PHINode *UPhi = cast<PHINode>(U);
333 // UPhi already has one incoming argument from original header.
334 // Add second incoming argument from new Pre header.
335 UPhi->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
336 } else {
Dan Gohmancc4e6052009-06-25 00:22:44 +0000337 // Used outside Exit block. Create a new PHI node in the exit block
338 // to receive the value from the new header and pre-header.
Dan Gohman610c0e22008-06-19 17:37:25 +0000339 PHINode *PN = PHINode::Create(U->getType(), U->getName(),
340 Exit->begin());
Devang Patel990e8662007-07-11 23:47:28 +0000341 PN->addIncoming(ILoopHeaderInfo.PreHeader, OrigPreHeader);
342 PN->addIncoming(OldPhi, OrigHeader);
Devang Patel990e8662007-07-11 23:47:28 +0000343 U->replaceUsesOfWith(OldPhi, PN);
344 }
Devang Patelc4625da2007-04-07 01:25:15 +0000345 }
346 }
347
348 /// Make sure all Exit block PHINodes have required incoming values.
349 updateExitBlock();
350
351 // Update CFG
352
353 // Removing incoming branch from loop preheader to original header.
354 // Now original header is inside the loop.
Dan Gohmancfb32202009-06-27 21:23:40 +0000355 for (BasicBlock::iterator I = OrigHeader->begin();
356 (PN = dyn_cast<PHINode>(I)); ++I)
357 PN->removeIncomingValue(OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000358
359 // Make NewHeader as the new header for the loop.
360 L->moveToHeader(NewHeader);
361
Devang Patel5464b962007-04-09 20:19:46 +0000362 preserveCanonicalLoopForm(LPM);
363
Devang Patelc4625da2007-04-07 01:25:15 +0000364 NumRotated++;
365 return true;
366}
367
Devang Patelc4625da2007-04-07 01:25:15 +0000368/// Make sure all Exit block PHINodes have required incoming values.
Dan Gohmancc4e6052009-06-25 00:22:44 +0000369/// If an incoming value is constant or defined outside the loop then
370/// PHINode may not have an entry for the original pre-header.
Devang Patelc4625da2007-04-07 01:25:15 +0000371void LoopRotate::updateExitBlock() {
372
Dan Gohmane1047fb2009-06-26 00:35:12 +0000373 PHINode *PN;
Dan Gohman30d670f2009-06-26 00:26:03 +0000374 for (BasicBlock::iterator I = Exit->begin();
Dan Gohmane1047fb2009-06-26 00:35:12 +0000375 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patelc4625da2007-04-07 01:25:15 +0000376
Devang Patele9881542007-04-09 19:04:21 +0000377 // There is already one incoming value from original pre-header block.
378 if (PN->getBasicBlockIndex(OrigPreHeader) != -1)
Devang Patel6c361572007-04-09 22:20:10 +0000379 continue;
Devang Patelcfde9592007-04-09 16:41:46 +0000380
Devang Patel4522c8a2007-04-09 17:09:13 +0000381 const RenameData *ILoopHeaderInfo;
Devang Patelcfde9592007-04-09 16:41:46 +0000382 Value *V = PN->getIncomingValueForBlock(OrigHeader);
Dan Gohman30d670f2009-06-26 00:26:03 +0000383 if (isa<Instruction>(V) &&
Devang Patelcfde9592007-04-09 16:41:46 +0000384 (ILoopHeaderInfo = findReplacementData(cast<Instruction>(V)))) {
Chris Lattnere34e9a22007-04-14 23:32:02 +0000385 assert(ILoopHeaderInfo->PreHeader && "Missing New Preheader Instruction");
Devang Patele9881542007-04-09 19:04:21 +0000386 PN->addIncoming(ILoopHeaderInfo->PreHeader, OrigPreHeader);
Devang Patelcfde9592007-04-09 16:41:46 +0000387 } else {
Devang Patele9881542007-04-09 19:04:21 +0000388 PN->addIncoming(V, OrigPreHeader);
Devang Patelc4625da2007-04-07 01:25:15 +0000389 }
390 }
391}
392
Devang Patelc4625da2007-04-07 01:25:15 +0000393/// Initialize local data
394void LoopRotate::initialize() {
395 L = NULL;
396 OrigHeader = NULL;
397 OrigPreHeader = NULL;
398 NewHeader = NULL;
Devang Patelc4625da2007-04-07 01:25:15 +0000399 Exit = NULL;
400
Devang Patel32231332007-04-09 16:11:48 +0000401 LoopHeaderInfo.clear();
Devang Patelc4625da2007-04-07 01:25:15 +0000402}
403
Devang Patel24a1c492007-04-09 16:21:29 +0000404/// Return true if this instruction is used by any instructions in the loop that
405/// aren't in original header.
Devang Patelc4625da2007-04-07 01:25:15 +0000406bool LoopRotate::usedOutsideOriginalHeader(Instruction *In) {
Devang Patelc4625da2007-04-07 01:25:15 +0000407 for (Value::use_iterator UI = In->use_begin(), UE = In->use_end();
408 UI != UE; ++UI) {
Chris Lattnerf6784a32009-01-26 01:57:01 +0000409 BasicBlock *UserBB = cast<Instruction>(UI)->getParent();
410 if (UserBB != OrigHeader && L->contains(UserBB))
411 return true;
Devang Patelc4625da2007-04-07 01:25:15 +0000412 }
413
414 return false;
415}
416
417/// Find Replacement information for instruction. Return NULL if it is
418/// not available.
Devang Patel4522c8a2007-04-09 17:09:13 +0000419const RenameData *LoopRotate::findReplacementData(Instruction *In) {
Devang Patelc4625da2007-04-07 01:25:15 +0000420
Devang Patel32231332007-04-09 16:11:48 +0000421 // Since LoopHeaderInfo is small, linear walk is OK.
Chris Lattnerf6784a32009-01-26 01:57:01 +0000422 for (unsigned LHI = 0, LHI_E = LoopHeaderInfo.size(); LHI != LHI_E; ++LHI) {
Devang Patel4522c8a2007-04-09 17:09:13 +0000423 const RenameData &ILoopHeaderInfo = LoopHeaderInfo[LHI];
424 if (ILoopHeaderInfo.Original == In)
425 return &ILoopHeaderInfo;
426 }
Devang Patelc4625da2007-04-07 01:25:15 +0000427 return NULL;
428}
Devang Patel5464b962007-04-09 20:19:46 +0000429
430/// After loop rotation, loop pre-header has multiple sucessors.
431/// Insert one forwarding basic block to ensure that loop pre-header
432/// has only one successor.
433void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
434
435 // Right now original pre-header has two successors, new header and
436 // exit block. Insert new block between original pre-header and
437 // new header such that loop's new pre-header has only one successor.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000438 BasicBlock *NewPreHeader = BasicBlock::Create("bb.nph",
439 OrigHeader->getParent(),
Gabor Greif051a9502008-04-06 20:25:17 +0000440 NewHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000441 LoopInfo &LI = LPM.getAnalysis<LoopInfo>();
442 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
Owen Andersond735ee82007-11-27 03:43:35 +0000443 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
Gabor Greif051a9502008-04-06 20:25:17 +0000444 BranchInst::Create(NewHeader, NewPreHeader);
Devang Patel5464b962007-04-09 20:19:46 +0000445
446 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
447 if (OrigPH_BI->getSuccessor(0) == NewHeader)
448 OrigPH_BI->setSuccessor(0, NewPreHeader);
449 else {
Chris Lattner2ba25432009-01-26 01:38:24 +0000450 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
451 "Unexpected original pre-header terminator");
Devang Patel5464b962007-04-09 20:19:46 +0000452 OrigPH_BI->setSuccessor(1, NewPreHeader);
453 }
Devang Patel5464b962007-04-09 20:19:46 +0000454
Dan Gohmancfb32202009-06-27 21:23:40 +0000455 PHINode *PN;
456 for (BasicBlock::iterator I = NewHeader->begin();
457 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patel5464b962007-04-09 20:19:46 +0000458 int index = PN->getBasicBlockIndex(OrigPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000459 assert(index != -1 && "Expected incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000460 PN->setIncomingBlock(index, NewPreHeader);
Chris Lattner2ba25432009-01-26 01:38:24 +0000461 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
462 "Expected only one incoming value from Original PreHeader");
Devang Patel5464b962007-04-09 20:19:46 +0000463 }
464
Duncan Sands1465d612009-01-28 13:14:17 +0000465 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000466 DT->addNewBlock(NewPreHeader, OrigPreHeader);
467 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
468 DT->changeImmediateDominator(Exit, OrigPreHeader);
469 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
470 BI != BE; ++BI) {
471 BasicBlock *B = *BI;
472 if (L->getHeader() != B) {
473 DomTreeNode *Node = DT->getNode(B);
474 if (Node && Node->getBlock() == OrigHeader)
475 DT->changeImmediateDominator(*BI, L->getHeader());
476 }
477 }
478 DT->changeImmediateDominator(OrigHeader, OrigLatch);
479 }
480
Duncan Sands1465d612009-01-28 13:14:17 +0000481 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
Devang Patel990e8662007-07-11 23:47:28 +0000482 // New Preheader's dominance frontier is Exit block.
483 DominanceFrontier::DomSetType NewPHSet;
484 NewPHSet.insert(Exit);
485 DF->addBasicBlock(NewPreHeader, NewPHSet);
486
487 // New Header's dominance frontier now includes itself and Exit block
488 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
489 if (HeadI != DF->end()) {
490 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
491 HeaderSet.clear();
492 HeaderSet.insert(L->getHeader());
493 HeaderSet.insert(Exit);
494 } else {
495 DominanceFrontier::DomSetType HeaderSet;
496 HeaderSet.insert(L->getHeader());
497 HeaderSet.insert(Exit);
498 DF->addBasicBlock(L->getHeader(), HeaderSet);
499 }
500
501 // Original header (new Loop Latch)'s dominance frontier is Exit.
502 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
503 if (LatchI != DF->end()) {
504 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
505 LatchSet = LatchI->second;
506 LatchSet.clear();
507 LatchSet.insert(Exit);
508 } else {
509 DominanceFrontier::DomSetType LatchSet;
510 LatchSet.insert(Exit);
511 DF->addBasicBlock(L->getHeader(), LatchSet);
512 }
513
514 // If a loop block dominates new loop latch then its frontier is
515 // new header and Exit.
516 BasicBlock *NewLatch = L->getLoopLatch();
Duncan Sands1465d612009-01-28 13:14:17 +0000517 DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>();
Devang Patel990e8662007-07-11 23:47:28 +0000518 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
519 BI != BE; ++BI) {
520 BasicBlock *B = *BI;
521 if (DT->dominates(B, NewLatch)) {
522 DominanceFrontier::iterator BDFI = DF->find(B);
523 if (BDFI != DF->end()) {
524 DominanceFrontier::DomSetType &BSet = BDFI->second;
525 BSet = BDFI->second;
526 BSet.clear();
527 BSet.insert(L->getHeader());
528 BSet.insert(Exit);
529 } else {
530 DominanceFrontier::DomSetType BSet;
531 BSet.insert(L->getHeader());
532 BSet.insert(Exit);
533 DF->addBasicBlock(B, BSet);
534 }
535 }
536 }
537 }
538
539 // Preserve canonical loop form, which means Exit block should
540 // have only one predecessor.
541 BasicBlock *NExit = SplitEdge(L->getLoopLatch(), Exit, this);
542
543 // Preserve LCSSA.
Dan Gohmancfb32202009-06-27 21:23:40 +0000544 for (BasicBlock::iterator I = Exit->begin();
545 (PN = dyn_cast<PHINode>(I)); ++I) {
Devang Patel990e8662007-07-11 23:47:28 +0000546 unsigned N = PN->getNumIncomingValues();
Dan Gohmancfb32202009-06-27 21:23:40 +0000547 for (unsigned index = 0; index != N; ++index)
Devang Patel990e8662007-07-11 23:47:28 +0000548 if (PN->getIncomingBlock(index) == NExit) {
Dan Gohman610c0e22008-06-19 17:37:25 +0000549 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName(),
550 NExit->begin());
Devang Patel990e8662007-07-11 23:47:28 +0000551 NewPN->addIncoming(PN->getIncomingValue(index), L->getLoopLatch());
552 PN->setIncomingValue(index, NewPN);
553 PN->setIncomingBlock(index, NExit);
Dan Gohman610c0e22008-06-19 17:37:25 +0000554 break;
Devang Patel990e8662007-07-11 23:47:28 +0000555 }
556 }
557
Chris Lattner2ba25432009-01-26 01:38:24 +0000558 assert(NewHeader && L->getHeader() == NewHeader &&
559 "Invalid loop header after loop rotation");
560 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
561 "Invalid loop preheader after loop rotation");
562 assert(L->getLoopLatch() &&
563 "Invalid loop latch after loop rotation");
Devang Patel5464b962007-04-09 20:19:46 +0000564}