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/IntrinsicInst.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/Dominators.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) {}
40 // Rotate Loop L as many times as possible. Return true if
41 // loop is rotated at least once.
42 bool runOnLoop(Loop *L, LPPassManager &LPM);
44 // LCSSA form makes instruction renaming easier.
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addPreserved<DominatorTree>();
47 AU.addPreserved<DominanceFrontier>();
48 AU.addRequired<LoopInfo>();
49 AU.addPreserved<LoopInfo>();
50 AU.addRequiredID(LoopSimplifyID);
51 AU.addPreservedID(LoopSimplifyID);
52 AU.addRequiredID(LCSSAID);
53 AU.addPreservedID(LCSSAID);
54 AU.addPreserved<ScalarEvolution>();
60 bool rotateLoop(Loop *L, LPPassManager &LPM);
62 /// Initialize local data
65 /// After loop rotation, loop pre-header has multiple sucessors.
66 /// Insert one forwarding basic block to ensure that loop pre-header
67 /// has only one successor.
68 void preserveCanonicalLoopForm(LPPassManager &LPM);
72 BasicBlock *OrigHeader;
73 BasicBlock *OrigPreHeader;
74 BasicBlock *OrigLatch;
75 BasicBlock *NewHeader;
77 LPPassManager *LPM_Ptr;
81 char LoopRotate::ID = 0;
82 INITIALIZE_PASS(LoopRotate, "loop-rotate", "Rotate Loops", false, false);
84 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
86 /// Rotate Loop L as many times as possible. Return true if
87 /// the loop is rotated at least once.
88 bool LoopRotate::runOnLoop(Loop *Lp, LPPassManager &LPM) {
90 bool RotatedOneLoop = false;
94 // One loop can be rotated multiple times.
95 while (rotateLoop(Lp,LPM)) {
96 RotatedOneLoop = true;
100 return RotatedOneLoop;
103 /// Rotate loop LP. Return true if the loop is rotated.
104 bool LoopRotate::rotateLoop(Loop *Lp, LPPassManager &LPM) {
107 OrigPreHeader = L->getLoopPreheader();
108 if (!OrigPreHeader) return false;
110 OrigLatch = L->getLoopLatch();
111 if (!OrigLatch) return false;
113 OrigHeader = L->getHeader();
115 // If the loop has only one block then there is not much to rotate.
116 if (L->getBlocks().size() == 1)
119 // If the loop header is not one of the loop exiting blocks then
120 // either this loop is already rotated or it is not
121 // suitable for loop rotation transformations.
122 if (!L->isLoopExiting(OrigHeader))
125 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
128 assert(BI->isConditional() && "Branch Instruction is not conditional");
130 // Updating PHInodes in loops with multiple exits adds complexity.
131 // Keep it simple, and restrict loop rotation to loops with one exit only.
132 // In future, lift this restriction and support for multiple exits if
134 SmallVector<BasicBlock*, 8> ExitBlocks;
135 L->getExitBlocks(ExitBlocks);
136 if (ExitBlocks.size() > 1)
139 // Check size of original header and reject
140 // loop if it is very big.
143 // FIXME: Use common api to estimate size.
144 for (BasicBlock::const_iterator OI = OrigHeader->begin(),
145 OE = OrigHeader->end(); OI != OE; ++OI) {
146 if (isa<PHINode>(OI))
147 continue; // PHI nodes don't count.
148 if (isa<DbgInfoIntrinsic>(OI))
149 continue; // Debug intrinsics don't count as size.
153 if (Size > MAX_HEADER_SIZE)
156 // Now, this loop is suitable for rotation.
158 // Anything ScalarEvolution may know about this loop or the PHI nodes
159 // in its header will soon be invalidated.
160 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
163 // Find new Loop header. NewHeader is a Header's one and only successor
164 // that is inside loop. Header's other successor is outside the
165 // loop. Otherwise loop is not suitable for rotation.
166 Exit = BI->getSuccessor(0);
167 NewHeader = BI->getSuccessor(1);
168 if (L->contains(Exit))
169 std::swap(Exit, NewHeader);
170 assert(NewHeader && "Unable to determine new loop header");
171 assert(L->contains(NewHeader) && !L->contains(Exit) &&
172 "Unable to determine loop header and exit blocks");
174 // This code assumes that the new header has exactly one predecessor.
175 // Remove any single-entry PHI nodes in it.
176 assert(NewHeader->getSinglePredecessor() &&
177 "New header doesn't have one pred!");
178 FoldSingleEntryPHINodes(NewHeader);
180 // Begin by walking OrigHeader and populating ValueMap with an entry for
182 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
183 DenseMap<const Value *, Value *> ValueMap;
185 // For PHI nodes, the value available in OldPreHeader is just the
186 // incoming value from OldPreHeader.
187 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
188 ValueMap[PN] = PN->getIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
190 // For the rest of the instructions, either hoist to the OrigPreheader if
191 // possible or create a clone in the OldPreHeader if not.
192 TerminatorInst *LoopEntryBranch = OrigPreHeader->getTerminator();
194 Instruction *Inst = I++;
196 // If the instruction's operands are invariant and it doesn't read or write
197 // memory, then it is safe to hoist. Doing this doesn't change the order of
198 // execution in the preheader, but does prevent the instruction from
199 // executing in each iteration of the loop. This means it is safe to hoist
200 // something that might trap, but isn't safe to hoist something that reads
201 // memory (without proving that the loop doesn't write).
202 if (L->hasLoopInvariantOperands(Inst) &&
203 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
204 !isa<TerminatorInst>(Inst)) {
205 Inst->moveBefore(LoopEntryBranch);
209 // Otherwise, create a duplicate of the instruction.
210 Instruction *C = Inst->clone();
211 C->setName(Inst->getName());
212 C->insertBefore(LoopEntryBranch);
216 // Along with all the other instructions, we just cloned OrigHeader's
217 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
218 // successors by duplicating their incoming values for OrigHeader.
219 TerminatorInst *TI = OrigHeader->getTerminator();
220 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
221 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
222 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
223 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreHeader);
225 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
226 // OrigPreHeader's old terminator (the original branch into the loop), and
227 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
228 LoopEntryBranch->eraseFromParent();
229 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
230 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreHeader));
232 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
235 for (I = OrigHeader->begin(); I != E; ++I) {
236 Value *OrigHeaderVal = I;
237 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
239 // The value now exits in two versions: the initial value in the preheader
240 // and the loop "next" value in the original header.
241 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
242 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
243 SSA.AddAvailableValue(OrigPreHeader, OrigPreHeaderVal);
245 // Visit each use of the OrigHeader instruction.
246 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
247 UE = OrigHeaderVal->use_end(); UI != UE; ) {
248 // Grab the use before incrementing the iterator.
249 Use &U = UI.getUse();
251 // Increment the iterator before removing the use from the list.
254 // SSAUpdater can't handle a non-PHI use in the same block as an
255 // earlier def. We can easily handle those cases manually.
256 Instruction *UserInst = cast<Instruction>(U.getUser());
257 if (!isa<PHINode>(UserInst)) {
258 BasicBlock *UserBB = UserInst->getParent();
260 // The original users in the OrigHeader are already using the
261 // original definitions.
262 if (UserBB == OrigHeader)
265 // Users in the OrigPreHeader need to use the value to which the
266 // original definitions are mapped.
267 if (UserBB == OrigPreHeader) {
268 U = OrigPreHeaderVal;
273 // Anything else can be handled by SSAUpdater.
278 // NewHeader is now the header of the loop.
279 L->moveToHeader(NewHeader);
281 // Move the original header to the bottom of the loop, where it now more
282 // naturally belongs. This isn't necessary for correctness, and CodeGen can
283 // usually reorder blocks on its own to fix things like this up, but it's
284 // still nice to keep the IR readable.
286 // The original header should have only one predecessor at this point, since
287 // we checked that the loop had a proper preheader and unique backedge before
289 assert(OrigHeader->getSinglePredecessor() &&
290 "Original loop header has too many predecessors after loop rotation!");
291 OrigHeader->moveAfter(OrigHeader->getSinglePredecessor());
293 // Also, since this original header only has one predecessor, zap its
294 // PHI nodes, which are now trivial.
295 FoldSingleEntryPHINodes(OrigHeader);
297 // TODO: We could just go ahead and merge OrigHeader into its predecessor
298 // at this point, if we don't mind updating dominator info.
300 // Establish a new preheader, update dominators, etc.
301 preserveCanonicalLoopForm(LPM);
307 /// Initialize local data
308 void LoopRotate::initialize() {
311 OrigPreHeader = NULL;
316 /// After loop rotation, loop pre-header has multiple sucessors.
317 /// Insert one forwarding basic block to ensure that loop pre-header
318 /// has only one successor.
319 void LoopRotate::preserveCanonicalLoopForm(LPPassManager &LPM) {
321 // Right now original pre-header has two successors, new header and
322 // exit block. Insert new block between original pre-header and
323 // new header such that loop's new pre-header has only one successor.
324 BasicBlock *NewPreHeader = BasicBlock::Create(OrigHeader->getContext(),
326 OrigHeader->getParent(),
328 LoopInfo &LI = getAnalysis<LoopInfo>();
329 if (Loop *PL = LI.getLoopFor(OrigPreHeader))
330 PL->addBasicBlockToLoop(NewPreHeader, LI.getBase());
331 BranchInst::Create(NewHeader, NewPreHeader);
333 BranchInst *OrigPH_BI = cast<BranchInst>(OrigPreHeader->getTerminator());
334 if (OrigPH_BI->getSuccessor(0) == NewHeader)
335 OrigPH_BI->setSuccessor(0, NewPreHeader);
337 assert(OrigPH_BI->getSuccessor(1) == NewHeader &&
338 "Unexpected original pre-header terminator");
339 OrigPH_BI->setSuccessor(1, NewPreHeader);
343 for (BasicBlock::iterator I = NewHeader->begin();
344 (PN = dyn_cast<PHINode>(I)); ++I) {
345 int index = PN->getBasicBlockIndex(OrigPreHeader);
346 assert(index != -1 && "Expected incoming value from Original PreHeader");
347 PN->setIncomingBlock(index, NewPreHeader);
348 assert(PN->getBasicBlockIndex(OrigPreHeader) == -1 &&
349 "Expected only one incoming value from Original PreHeader");
352 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
353 DT->addNewBlock(NewPreHeader, OrigPreHeader);
354 DT->changeImmediateDominator(L->getHeader(), NewPreHeader);
355 DT->changeImmediateDominator(Exit, OrigPreHeader);
356 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
359 if (L->getHeader() != B) {
360 DomTreeNode *Node = DT->getNode(B);
361 if (Node && Node->getBlock() == OrigHeader)
362 DT->changeImmediateDominator(*BI, L->getHeader());
365 DT->changeImmediateDominator(OrigHeader, OrigLatch);
368 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>()) {
369 // New Preheader's dominance frontier is Exit block.
370 DominanceFrontier::DomSetType NewPHSet;
371 NewPHSet.insert(Exit);
372 DF->addBasicBlock(NewPreHeader, NewPHSet);
374 // New Header's dominance frontier now includes itself and Exit block
375 DominanceFrontier::iterator HeadI = DF->find(L->getHeader());
376 if (HeadI != DF->end()) {
377 DominanceFrontier::DomSetType & HeaderSet = HeadI->second;
379 HeaderSet.insert(L->getHeader());
380 HeaderSet.insert(Exit);
382 DominanceFrontier::DomSetType HeaderSet;
383 HeaderSet.insert(L->getHeader());
384 HeaderSet.insert(Exit);
385 DF->addBasicBlock(L->getHeader(), HeaderSet);
388 // Original header (new Loop Latch)'s dominance frontier is Exit.
389 DominanceFrontier::iterator LatchI = DF->find(L->getLoopLatch());
390 if (LatchI != DF->end()) {
391 DominanceFrontier::DomSetType &LatchSet = LatchI->second;
392 LatchSet = LatchI->second;
394 LatchSet.insert(Exit);
396 DominanceFrontier::DomSetType LatchSet;
397 LatchSet.insert(Exit);
398 DF->addBasicBlock(L->getHeader(), LatchSet);
401 // If a loop block dominates new loop latch then add to its frontiers
402 // new header and Exit and remove new latch (which is equal to original
404 BasicBlock *NewLatch = L->getLoopLatch();
406 assert(NewLatch == OrigHeader && "NewLatch is inequal to OrigHeader");
408 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
409 for (Loop::block_iterator BI = L->block_begin(), BE = L->block_end();
412 if (DT->dominates(B, NewLatch)) {
413 DominanceFrontier::iterator BDFI = DF->find(B);
414 if (BDFI != DF->end()) {
415 DominanceFrontier::DomSetType &BSet = BDFI->second;
416 BSet.erase(NewLatch);
417 BSet.insert(L->getHeader());
420 DominanceFrontier::DomSetType BSet;
421 BSet.insert(L->getHeader());
423 DF->addBasicBlock(B, BSet);
430 // Preserve canonical loop form, which means Exit block should
431 // have only one predecessor.
432 SplitEdge(L->getLoopLatch(), Exit, this);
434 assert(NewHeader && L->getHeader() == NewHeader &&
435 "Invalid loop header after loop rotation");
436 assert(NewPreHeader && L->getLoopPreheader() == NewPreHeader &&
437 "Invalid loop preheader after loop rotation");
438 assert(L->getLoopLatch() &&
439 "Invalid loop latch after loop rotation");