1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Rotation Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-rotate"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Function.h"
17 #include "llvm/Analysis/LoopPass.h"
18 #include "llvm/Analysis/DominanceFrontier.h"
19 #include "llvm/Analysis/CodeMetrics.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Transforms/Utils/SSAUpdater.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/SmallVector.h"
30 #define MAX_HEADER_SIZE 16
32 STATISTIC(NumRotated, "Number of loops rotated");
35 class LoopRotate : public LoopPass {
37 static char ID; // Pass ID, replacement for typeid
38 LoopRotate() : LoopPass(ID) {
39 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
42 // Rotate Loop L as many times as possible. Return true if
43 // loop is rotated at least once.
44 bool runOnLoop(Loop *L, LPPassManager &LPM);
46 // LCSSA form makes instruction renaming easier.
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addPreserved<DominatorTree>();
49 AU.addPreserved<DominanceFrontier>();
50 AU.addRequired<LoopInfo>();
51 AU.addPreserved<LoopInfo>();
52 AU.addRequiredID(LoopSimplifyID);
53 AU.addPreservedID(LoopSimplifyID);
54 AU.addRequiredID(LCSSAID);
55 AU.addPreservedID(LCSSAID);
56 AU.addPreserved<ScalarEvolution>();
62 bool rotateLoop(Loop *L, LPPassManager &LPM);
64 /// Initialize local data
67 /// After loop rotation, loop pre-header has multiple sucessors.
68 /// Insert one forwarding basic block to ensure that loop pre-header
69 /// has only one successor.
70 void preserveCanonicalLoopForm(LPPassManager &LPM);
74 BasicBlock *OrigHeader;
75 BasicBlock *OrigPreHeader;
76 BasicBlock *OrigLatch;
77 BasicBlock *NewHeader;
79 LPPassManager *LPM_Ptr;
83 char LoopRotate::ID = 0;
84 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
85 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
86 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
87 INITIALIZE_PASS_DEPENDENCY(LCSSA)
88 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
90 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
92 /// Rotate Loop L as many times as possible. Return true if
93 /// the loop is rotated at least once.
94 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
96 bool RotatedOneLoop = false;
100 // One loop can be rotated multiple times.
101 while (rotateLoop(Lp,LPM)) {
102 RotatedOneLoop = true;
106 return RotatedOneLoop;
109 /// Rotate loop LP. Return true if the loop is rotated.
110 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
113 OrigPreHeader = L->getLoopPreheader();
114 if (!OrigPreHeader) return false;
116 OrigLatch = L->getLoopLatch();
117 if (!OrigLatch) return false;
119 OrigHeader = L->getHeader();
121 // If the loop has only one block then there is not much to rotate.
122 if (L->getBlocks().size() == 1)
125 // If the loop header is not one of the loop exiting blocks then
126 // either this loop is already rotated or it is not
127 // suitable for loop rotation transformations.
128 if (!L->isLoopExiting(OrigHeader))
131 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
134 assert(BI->isConditional() && "Branch Instruction is not conditional");
136 // Updating PHInodes in loops with multiple exits adds complexity.
137 // Keep it simple, and restrict loop rotation to loops with one exit only.
138 // In future, lift this restriction and support for multiple exits if
140 SmallVector<BasicBlock*, 8> ExitBlocks;
141 L->getExitBlocks(ExitBlocks);
142 if (ExitBlocks.size() > 1)
145 // Check size of original header and reject loop if it is very big.
148 Metrics.analyzeBasicBlock(OrigHeader);
149 if (Metrics.NumInsts > MAX_HEADER_SIZE)
153 // Now, this loop is suitable for rotation.
155 // Anything ScalarEvolution may know about this loop or the PHI nodes
156 // in its header will soon be invalidated.
157 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
160 // Find new Loop header. NewHeader is a Header's one and only successor
161 // that is inside loop. Header's other successor is outside the
162 // loop. Otherwise loop is not suitable for rotation.
163 Exit = BI->getSuccessor(0);
164 NewHeader = BI->getSuccessor(1);
165 if (L->contains(Exit))
166 std::swap(Exit, NewHeader);
167 assert(NewHeader && "Unable to determine new loop header");
168 assert(L->contains(NewHeader) && !L->contains(Exit) &&
169 "Unable to determine loop header and exit blocks");
171 // This code assumes that the new header has exactly one predecessor.
172 // Remove any single-entry PHI nodes in it.
173 assert(NewHeader->getSinglePredecessor() &&
174 "New header doesn't have one pred!");
175 FoldSingleEntryPHINodes(NewHeader);
177 // Begin by walking OrigHeader and populating ValueMap with an entry for
179 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
180 DenseMap<const Value *, Value *> ValueMap;
182 // For PHI nodes, the value available in OldPreHeader is just the
183 // incoming value from OldPreHeader.
184 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
185 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
187 // For the rest of the instructions, either hoist to the OrigPreheader if
188 // possible or create a clone in the OldPreHeader if not.
189 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
191 Instruction *Inst = I++;
193 // If the instruction's operands are invariant and it doesn't read or write
194 // memory, then it is safe to hoist. Doing this doesn't change the order of
195 // execution in the preheader, but does prevent the instruction from
196 // executing in each iteration of the loop. This means it is safe to hoist
197 // something that might trap, but isn't safe to hoist something that reads
198 // memory (without proving that the loop doesn't write).
199 if (L->hasLoopInvariantOperands(Inst) &&
200 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
201 !isa<TerminatorInst>(Inst)) {
202 Inst->moveBefore(LoopEntryBranch);
206 // Otherwise, create a duplicate of the instruction.
207 Instruction *C = Inst->clone();
208 C->setName(Inst->getName());
209 C->insertBefore(LoopEntryBranch);
213 // Along with all the other instructions, we just cloned OrigHeader's
214 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
215 // successors by duplicating their incoming values for OrigHeader.
216 TerminatorInst *TI = OrigHeader->getTerminator();
217 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
218 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
219 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
220 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
222 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
223 // OrigPreHeader's old terminator (the original branch into the loop), and
224 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
225 LoopEntryBranch->eraseFromParent();
226 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
227 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
229 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
232 for (I = OrigHeader->begin(); I != E; ++I) {
233 Value *OrigHeaderVal = I;
234 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
236 // The value now exits in two versions: the initial value in the preheader
237 // and the loop "next" value in the original header.
238 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
239 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
240 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
242 // Visit each use of the OrigHeader instruction.
243 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
244 UE = OrigHeaderVal->use_end(); UI != UE; ) {
245 // Grab the use before incrementing the iterator.
246 Use &U = UI.getUse();
248 // Increment the iterator before removing the use from the list.
251 // SSAUpdater can't handle a non-PHI use in the same block as an
252 // earlier def. We can easily handle those cases manually.
253 Instruction *UserInst = cast<Instruction>(U.getUser());
254 if (!isa<PHINode>(UserInst)) {
255 BasicBlock *UserBB = UserInst->getParent();
257 // The original users in the OrigHeader are already using the
258 // original definitions.
259 if (UserBB == OrigHeader)
262 // Users in the OrigPreHeader need to use the value to which the
263 // original definitions are mapped.
264 if (UserBB == OrigPreHeader) {
265 U = OrigPreHeaderVal;
270 // Anything else can be handled by SSAUpdater.
275 // NewHeader is now the header of the loop.
276 L->moveToHeader(NewHeader);
278 // Move the original header to the bottom of the loop, where it now more
279 // naturally belongs. This isn't necessary for correctness, and CodeGen can
280 // usually reorder blocks on its own to fix things like this up, but it's
281 // still nice to keep the IR readable.
283 // The original header should have only one predecessor at this point, since
284 // we checked that the loop had a proper preheader and unique backedge before
286 assert(OrigHeader->getSinglePredecessor() &&
287 "Original loop header has too many predecessors after loop rotation!");
288 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
290 // Also, since this original header only has one predecessor, zap its
291 // PHI nodes, which are now trivial.
292 FoldSingleEntryPHINodes(OrigHeader);
294 // TODO: We could just go ahead and merge OrigHeader into its predecessor
295 // at this point, if we don't mind updating dominator info.
297 // Establish a new preheader, update dominators, etc.
298 preserveCanonicalLoopForm(LPM);
304 /// Initialize local data
305 void LoopRotate::initialize() {
308 OrigPreHeader = NULL;
313 /// After loop rotation, loop pre-header has multiple sucessors.
314 /// Insert one forwarding basic block to ensure that loop pre-header
315 /// has only one successor.
316 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
318 // Right now original pre-header has two successors, new header and
319 // exit block. Insert new block between original pre-header and
320 // new header such that loop's new pre-header has only one successor.
321 BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
323 OrigHeader->getParent(),
325 LoopInfo &LI = getAnalysis<LoopInfo>();
326 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
327 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
328 BranchInst::Create(NewHeader, NewPreHeader);
330 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
331 if (OrigPH_BI->getSuccessor(0) == NewHeader)
332 OrigPH_BI->setSuccessor(0, NewPreHeader);
334 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
335 "Unexpected original pre-header terminator");
336 OrigPH_BI->setSuccessor(1, NewPreHeader);
340 for (BasicBlock::iterator I = NewHeader->begin();
341 (PN = dyn_cast<PHINode>(I)); ++I) {
342 int index = PN->getBasicBlockIndex(OrigPreHeader);
343 assert(index != -1 && "Expected incoming value from Original PreHeader");
344 PN->setIncomingBlock(index, NewPreHeader);
345 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
346 "Expected only one incoming value from Original PreHeader");
349 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
350 DT->addNewBlock(NewPreHeader, OrigPreHeader);
351 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
352 DT->changeImmediateDominator(Exit, OrigPreHeader);
353 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
356 if (L->getHeader() != B) {
357 DomTreeNode *Node = DT->getNode(B);
358 if (Node && Node->getBlock() == OrigHeader)
359 DT->changeImmediateDominator(*BI, L->getHeader());
362 DT->changeImmediateDominator(OrigHeader, OrigLatch);
365 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
366 // New Preheader's dominance frontier is Exit block.
367 DominanceFrontier::DomSetType NewPHSet;
368 NewPHSet.insert(Exit);
369 DF->addBasicBlock(NewPreHeader, NewPHSet);
371 // New Header's dominance frontier now includes itself and Exit block
372 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
373 if (HeadI != DF->end()) {
374 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
376 HeaderSet.insert(L->getHeader());
377 HeaderSet.insert(Exit);
379 DominanceFrontier::DomSetType HeaderSet;
380 HeaderSet.insert(L->getHeader());
381 HeaderSet.insert(Exit);
382 DF->addBasicBlock(L->getHeader(), HeaderSet);
385 // Original header (new Loop Latch)'s dominance frontier is Exit.
386 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
387 if (LatchI != DF->end()) {
388 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
389 LatchSet = LatchI->second;
391 LatchSet.insert(Exit);
393 DominanceFrontier::DomSetType LatchSet;
394 LatchSet.insert(Exit);
395 DF->addBasicBlock(L->getHeader(), LatchSet);
398 // If a loop block dominates new loop latch then add to its frontiers
399 // new header and Exit and remove new latch (which is equal to original
401 BasicBlock *NewLatch = L->getLoopLatch();
403 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
405 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
406 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
409 if (DT->dominates(B, NewLatch)) {
410 DominanceFrontier::iterator BDFI = DF->find(B);
411 if (BDFI != DF->end()) {
412 DominanceFrontier::DomSetType &BSet = BDFI->second;
413 BSet.erase(NewLatch);
414 BSet.insert(L->getHeader());
417 DominanceFrontier::DomSetType BSet;
418 BSet.insert(L->getHeader());
420 DF->addBasicBlock(B, BSet);
427 // Preserve canonical loop form, which means Exit block should
428 // have only one predecessor.
429 SplitEdge(L->getLoopLatch(), Exit, this);
431 assert(NewHeader && L->getHeader() == NewHeader &&
432 "Invalid loop header after loop rotation");
433 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
434 "Invalid loop preheader after loop rotation");
435 assert(L->getLoopLatch() &&
436 "Invalid loop latch after loop rotation");