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/CodeMetrics.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/Transforms/Utils/SSAUpdater.h"
26 #include "llvm/Transforms/Utils/ValueMapper.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/Statistic.h"
32 #define MAX_HEADER_SIZE 16
34 STATISTIC(NumRotated, "Number of loops rotated");
37 class LoopRotate : public LoopPass {
39 static char ID; // Pass ID, replacement for typeid
40 LoopRotate() : LoopPass(ID) {
41 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
44 // LCSSA form makes instruction renaming easier.
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addPreserved<DominatorTree>();
47 AU.addRequired<LoopInfo>();
48 AU.addPreserved<LoopInfo>();
49 AU.addRequiredID(LoopSimplifyID);
50 AU.addPreservedID(LoopSimplifyID);
51 AU.addRequiredID(LCSSAID);
52 AU.addPreservedID(LCSSAID);
53 AU.addPreserved<ScalarEvolution>();
56 bool runOnLoop(Loop *L, LPPassManager &LPM);
57 void simplifyLoopLatch(Loop *L);
58 bool rotateLoop(Loop *L);
65 char LoopRotate::ID = 0;
66 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
67 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
68 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
69 INITIALIZE_PASS_DEPENDENCY(LCSSA)
70 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
72 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
74 /// Rotate Loop L as many times as possible. Return true if
75 /// the loop is rotated at least once.
76 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
77 LI = &getAnalysis<LoopInfo>();
79 // Simplify the loop latch before attempting to rotate the header
80 // upward. Rotation may not be needed if the loop tail can be folded into the
84 // One loop can be rotated multiple times.
85 bool MadeChange = false;
92 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
93 /// old header into the preheader. If there were uses of the values produced by
94 /// these instruction that were outside of the loop, we have to insert PHI nodes
95 /// to merge the two values. Do this now.
96 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
97 BasicBlock *OrigPreheader,
98 ValueToValueMapTy &ValueMap) {
99 // Remove PHI node entries that are no longer live.
100 BasicBlock::iterator I, E = OrigHeader->end();
101 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
102 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
104 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
107 for (I = OrigHeader->begin(); I != E; ++I) {
108 Value *OrigHeaderVal = I;
110 // If there are no uses of the value (e.g. because it returns void), there
111 // is nothing to rewrite.
112 if (OrigHeaderVal->use_empty())
115 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
117 // The value now exits in two versions: the initial value in the preheader
118 // and the loop "next" value in the original header.
119 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
120 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
121 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
123 // Visit each use of the OrigHeader instruction.
124 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
125 UE = OrigHeaderVal->use_end(); UI != UE; ) {
126 // Grab the use before incrementing the iterator.
127 Use &U = UI.getUse();
129 // Increment the iterator before removing the use from the list.
132 // SSAUpdater can't handle a non-PHI use in the same block as an
133 // earlier def. We can easily handle those cases manually.
134 Instruction *UserInst = cast<Instruction>(U.getUser());
135 if (!isa<PHINode>(UserInst)) {
136 BasicBlock *UserBB = UserInst->getParent();
138 // The original users in the OrigHeader are already using the
139 // original definitions.
140 if (UserBB == OrigHeader)
143 // Users in the OrigPreHeader need to use the value to which the
144 // original definitions are mapped.
145 if (UserBB == OrigPreheader) {
146 U = OrigPreHeaderVal;
151 // Anything else can be handled by SSAUpdater.
157 /// Determine whether the instructions in this range my be safely and cheaply
158 /// speculated. This is not an important enough situation to develop complex
159 /// heuristics. We handle a single arithmetic instruction along with any type
161 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
162 BasicBlock::iterator End) {
163 bool seenIncrement = false;
164 for (BasicBlock::iterator I = Begin; I != End; ++I) {
166 if (!isSafeToSpeculativelyExecute(I))
169 if (isa<DbgInfoIntrinsic>(I))
172 switch (I->getOpcode()) {
175 case Instruction::GetElementPtr:
176 // GEPs are cheap if all indices are constant.
177 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
179 // fall-thru to increment case
180 case Instruction::Add:
181 case Instruction::Sub:
182 case Instruction::And:
183 case Instruction::Or:
184 case Instruction::Xor:
185 case Instruction::Shl:
186 case Instruction::LShr:
187 case Instruction::AShr:
190 seenIncrement = true;
192 case Instruction::Trunc:
193 case Instruction::ZExt:
194 case Instruction::SExt:
195 // ignore type conversions
202 /// Fold the loop tail into the loop exit by speculating the loop tail
203 /// instructions. Typically, this is a single post-increment. In the case of a
204 /// simple 2-block loop, hoisting the increment can be much better than
205 /// duplicating the entire loop header. In the cast of loops with early exits,
206 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
207 /// canonical form so downstream passes can handle it.
209 /// I don't believe this invalidates SCEV.
210 void LoopRotate::simplifyLoopLatch(Loop *L) {
211 BasicBlock *Latch = L->getLoopLatch();
212 if (!Latch || Latch->hasAddressTaken())
215 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
216 if (!Jmp || !Jmp->isUnconditional())
219 BasicBlock *LastExit = Latch->getSinglePredecessor();
220 if (!LastExit || !L->isLoopExiting(LastExit))
223 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
227 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
230 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
231 << LastExit->getName() << "\n");
233 // Hoist the instructions from Latch into LastExit.
234 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
236 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
237 BasicBlock *Header = Jmp->getSuccessor(0);
238 assert(Header == L->getHeader() && "expected a backward branch");
240 // Remove Latch from the CFG so that LastExit becomes the new Latch.
241 BI->setSuccessor(FallThruPath, Header);
242 Latch->replaceSuccessorsPhiUsesWith(LastExit);
243 Jmp->eraseFromParent();
245 // Nuke the Latch block.
246 assert(Latch->empty() && "unable to evacuate Latch");
247 LI->removeBlock(Latch);
248 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
249 DT->eraseNode(Latch);
250 Latch->eraseFromParent();
253 /// Rotate loop LP. Return true if the loop is rotated.
254 bool LoopRotate::rotateLoop(Loop *L) {
255 // If the loop has only one block then there is not much to rotate.
256 if (L->getBlocks().size() == 1)
259 BasicBlock *OrigHeader = L->getHeader();
260 BasicBlock *OrigLatch = L->getLoopLatch();
262 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
263 if (BI == 0 || BI->isUnconditional())
266 // If the loop header is not one of the loop exiting blocks then
267 // either this loop is already rotated or it is not
268 // suitable for loop rotation transformations.
269 if (!L->isLoopExiting(OrigHeader))
272 // If the loop latch already contains a branch that leaves the loop then the
273 // loop is already rotated.
274 if (OrigLatch == 0 || L->isLoopExiting(OrigLatch))
277 // Check size of original header and reject loop if it is very big.
280 Metrics.analyzeBasicBlock(OrigHeader);
281 if (Metrics.NumInsts > MAX_HEADER_SIZE)
285 // Now, this loop is suitable for rotation.
286 BasicBlock *OrigPreheader = L->getLoopPreheader();
288 // If the loop could not be converted to canonical form, it must have an
289 // indirectbr in it, just give up.
290 if (OrigPreheader == 0)
293 // Anything ScalarEvolution may know about this loop or the PHI nodes
294 // in its header will soon be invalidated.
295 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
298 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
300 // Find new Loop header. NewHeader is a Header's one and only successor
301 // that is inside loop. Header's other successor is outside the
302 // loop. Otherwise loop is not suitable for rotation.
303 BasicBlock *Exit = BI->getSuccessor(0);
304 BasicBlock *NewHeader = BI->getSuccessor(1);
305 if (L->contains(Exit))
306 std::swap(Exit, NewHeader);
307 assert(NewHeader && "Unable to determine new loop header");
308 assert(L->contains(NewHeader) && !L->contains(Exit) &&
309 "Unable to determine loop header and exit blocks");
311 // This code assumes that the new header has exactly one predecessor.
312 // Remove any single-entry PHI nodes in it.
313 assert(NewHeader->getSinglePredecessor() &&
314 "New header doesn't have one pred!");
315 FoldSingleEntryPHINodes(NewHeader);
317 // Begin by walking OrigHeader and populating ValueMap with an entry for
319 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
320 ValueToValueMapTy ValueMap;
322 // For PHI nodes, the value available in OldPreHeader is just the
323 // incoming value from OldPreHeader.
324 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
325 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
327 // For the rest of the instructions, either hoist to the OrigPreheader if
328 // possible or create a clone in the OldPreHeader if not.
329 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
331 Instruction *Inst = I++;
333 // If the instruction's operands are invariant and it doesn't read or write
334 // memory, then it is safe to hoist. Doing this doesn't change the order of
335 // execution in the preheader, but does prevent the instruction from
336 // executing in each iteration of the loop. This means it is safe to hoist
337 // something that might trap, but isn't safe to hoist something that reads
338 // memory (without proving that the loop doesn't write).
339 if (L->hasLoopInvariantOperands(Inst) &&
340 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
341 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
342 !isa<AllocaInst>(Inst)) {
343 Inst->moveBefore(LoopEntryBranch);
347 // Otherwise, create a duplicate of the instruction.
348 Instruction *C = Inst->clone();
350 // Eagerly remap the operands of the instruction.
351 RemapInstruction(C, ValueMap,
352 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
354 // With the operands remapped, see if the instruction constant folds or is
355 // otherwise simplifyable. This commonly occurs because the entry from PHI
356 // nodes allows icmps and other instructions to fold.
357 Value *V = SimplifyInstruction(C);
358 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
359 // If so, then delete the temporary instruction and stick the folded value
364 // Otherwise, stick the new instruction into the new block!
365 C->setName(Inst->getName());
366 C->insertBefore(LoopEntryBranch);
371 // Along with all the other instructions, we just cloned OrigHeader's
372 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
373 // successors by duplicating their incoming values for OrigHeader.
374 TerminatorInst *TI = OrigHeader->getTerminator();
375 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
376 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
377 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
378 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
380 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
381 // OrigPreHeader's old terminator (the original branch into the loop), and
382 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
383 LoopEntryBranch->eraseFromParent();
385 // If there were any uses of instructions in the duplicated block outside the
386 // loop, update them, inserting PHI nodes as required
387 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
389 // NewHeader is now the header of the loop.
390 L->moveToHeader(NewHeader);
391 assert(L->getHeader() == NewHeader && "Latch block is our new header");
394 // At this point, we've finished our major CFG changes. As part of cloning
395 // the loop into the preheader we've simplified instructions and the
396 // duplicated conditional branch may now be branching on a constant. If it is
397 // branching on a constant and if that constant means that we enter the loop,
398 // then we fold away the cond branch to an uncond branch. This simplifies the
399 // loop in cases important for nested loops, and it also means we don't have
400 // to split as many edges.
401 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
402 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
403 if (!isa<ConstantInt>(PHBI->getCondition()) ||
404 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
406 // The conditional branch can't be folded, handle the general case.
407 // Update DominatorTree to reflect the CFG change we just made. Then split
408 // edges as necessary to preserve LoopSimplify form.
409 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
410 // Everything that was dominated by the old loop header is now dominated
411 // by the original loop preheader. Conceptually the header was merged
412 // into the preheader, even though we reuse the actual block as a new
414 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
415 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
416 OrigHeaderNode->end());
417 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
418 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
419 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
421 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
422 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
424 // Update OrigHeader to be dominated by the new header block.
425 DT->changeImmediateDominator(OrigHeader, OrigLatch);
428 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
429 // thus is not a preheader anymore.
430 // Split the edge to form a real preheader.
431 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
432 NewPH->setName(NewHeader->getName() + ".lr.ph");
434 // Preserve canonical loop form, which means that 'Exit' should have only
436 BasicBlock *ExitSplit = SplitCriticalEdge(L->getLoopLatch(), Exit, this);
437 ExitSplit->moveBefore(Exit);
439 // We can fold the conditional branch in the preheader, this makes things
440 // simpler. The first step is to remove the extra edge to the Exit block.
441 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
442 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
443 NewBI->setDebugLoc(PHBI->getDebugLoc());
444 PHBI->eraseFromParent();
446 // With our CFG finalized, update DomTree if it is available.
447 if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
448 // Update OrigHeader to be dominated by the new header block.
449 DT->changeImmediateDominator(NewHeader, OrigPreheader);
450 DT->changeImmediateDominator(OrigHeader, OrigLatch);
452 // Brute force incremental dominator tree update. Call
453 // findNearestCommonDominator on all CFG predecessors of each child of the
455 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
456 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
457 OrigHeaderNode->end());
461 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
462 DomTreeNode *Node = HeaderChildren[I];
463 BasicBlock *BB = Node->getBlock();
465 pred_iterator PI = pred_begin(BB);
466 BasicBlock *NearestDom = *PI;
467 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
468 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
470 // Remember if this changes the DomTree.
471 if (Node->getIDom()->getBlock() != NearestDom) {
472 DT->changeImmediateDominator(BB, NearestDom);
477 // If the dominator changed, this may have an effect on other
478 // predecessors, continue until we reach a fixpoint.
483 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
484 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
486 // Now that the CFG and DomTree are in a consistent state again, try to merge
487 // the OrigHeader block into OrigLatch. This will succeed if they are
488 // connected by an unconditional branch. This is just a cleanup so the
489 // emitted code isn't too gross in this common case.
490 MergeBlockIntoPredecessor(OrigHeader, this);
492 DEBUG(dbgs() << "LoopRotation: into "; L->dump());