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/ADT/Statistic.h"
17 #include "llvm/Analysis/CodeMetrics.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/ScalarEvolution.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Transforms/Utils/SSAUpdater.h"
31 #include "llvm/Transforms/Utils/ValueMapper.h"
34 #define MAX_HEADER_SIZE 16
36 STATISTIC(NumRotated, "Number of loops rotated");
39 class LoopRotate : public LoopPass {
41 static char ID; // Pass ID, replacement for typeid
42 LoopRotate() : LoopPass(ID) {
43 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
46 // LCSSA form makes instruction renaming easier.
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addPreserved<DominatorTreeWrapperPass>();
49 AU.addRequired<LoopInfo>();
50 AU.addPreserved<LoopInfo>();
51 AU.addRequiredID(LoopSimplifyID);
52 AU.addPreservedID(LoopSimplifyID);
53 AU.addRequiredID(LCSSAID);
54 AU.addPreservedID(LCSSAID);
55 AU.addPreserved<ScalarEvolution>();
56 AU.addRequired<TargetTransformInfo>();
59 bool runOnLoop(Loop *L, LPPassManager &LPM);
60 bool simplifyLoopLatch(Loop *L);
61 bool rotateLoop(Loop *L, bool SimplifiedLatch);
65 const TargetTransformInfo *TTI;
69 char LoopRotate::ID = 0;
70 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
71 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
72 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
73 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
74 INITIALIZE_PASS_DEPENDENCY(LCSSA)
75 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
77 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
79 /// Rotate Loop L as many times as possible. Return true if
80 /// the loop is rotated at least once.
81 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
82 if (skipOptnoneFunction(L))
85 LI = &getAnalysis<LoopInfo>();
86 TTI = &getAnalysis<TargetTransformInfo>();
88 // Simplify the loop latch before attempting to rotate the header
89 // upward. Rotation may not be needed if the loop tail can be folded into the
91 bool SimplifiedLatch = simplifyLoopLatch(L);
93 // One loop can be rotated multiple times.
94 bool MadeChange = false;
95 while (rotateLoop(L, SimplifiedLatch)) {
97 SimplifiedLatch = false;
102 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
103 /// old header into the preheader. If there were uses of the values produced by
104 /// these instruction that were outside of the loop, we have to insert PHI nodes
105 /// to merge the two values. Do this now.
106 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
107 BasicBlock *OrigPreheader,
108 ValueToValueMapTy &ValueMap) {
109 // Remove PHI node entries that are no longer live.
110 BasicBlock::iterator I, E = OrigHeader->end();
111 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
112 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
114 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
117 for (I = OrigHeader->begin(); I != E; ++I) {
118 Value *OrigHeaderVal = I;
120 // If there are no uses of the value (e.g. because it returns void), there
121 // is nothing to rewrite.
122 if (OrigHeaderVal->use_empty())
125 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
127 // The value now exits in two versions: the initial value in the preheader
128 // and the loop "next" value in the original header.
129 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
130 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
131 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
133 // Visit each use of the OrigHeader instruction.
134 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
135 UE = OrigHeaderVal->use_end(); UI != UE; ) {
136 // Grab the use before incrementing the iterator.
137 Use &U = UI.getUse();
139 // Increment the iterator before removing the use from the list.
142 // SSAUpdater can't handle a non-PHI use in the same block as an
143 // earlier def. We can easily handle those cases manually.
144 Instruction *UserInst = cast<Instruction>(U.getUser());
145 if (!isa<PHINode>(UserInst)) {
146 BasicBlock *UserBB = UserInst->getParent();
148 // The original users in the OrigHeader are already using the
149 // original definitions.
150 if (UserBB == OrigHeader)
153 // Users in the OrigPreHeader need to use the value to which the
154 // original definitions are mapped.
155 if (UserBB == OrigPreheader) {
156 U = OrigPreHeaderVal;
161 // Anything else can be handled by SSAUpdater.
167 /// Determine whether the instructions in this range my be safely and cheaply
168 /// speculated. This is not an important enough situation to develop complex
169 /// heuristics. We handle a single arithmetic instruction along with any type
171 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
172 BasicBlock::iterator End) {
173 bool seenIncrement = false;
174 for (BasicBlock::iterator I = Begin; I != End; ++I) {
176 if (!isSafeToSpeculativelyExecute(I))
179 if (isa<DbgInfoIntrinsic>(I))
182 switch (I->getOpcode()) {
185 case Instruction::GetElementPtr:
186 // GEPs are cheap if all indices are constant.
187 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
189 // fall-thru to increment case
190 case Instruction::Add:
191 case Instruction::Sub:
192 case Instruction::And:
193 case Instruction::Or:
194 case Instruction::Xor:
195 case Instruction::Shl:
196 case Instruction::LShr:
197 case Instruction::AShr:
200 seenIncrement = true;
202 case Instruction::Trunc:
203 case Instruction::ZExt:
204 case Instruction::SExt:
205 // ignore type conversions
212 /// Fold the loop tail into the loop exit by speculating the loop tail
213 /// instructions. Typically, this is a single post-increment. In the case of a
214 /// simple 2-block loop, hoisting the increment can be much better than
215 /// duplicating the entire loop header. In the cast of loops with early exits,
216 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
217 /// canonical form so downstream passes can handle it.
219 /// I don't believe this invalidates SCEV.
220 bool LoopRotate::simplifyLoopLatch(Loop *L) {
221 BasicBlock *Latch = L->getLoopLatch();
222 if (!Latch || Latch->hasAddressTaken())
225 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
226 if (!Jmp || !Jmp->isUnconditional())
229 BasicBlock *LastExit = Latch->getSinglePredecessor();
230 if (!LastExit || !L->isLoopExiting(LastExit))
233 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
237 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
240 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
241 << LastExit->getName() << "\n");
243 // Hoist the instructions from Latch into LastExit.
244 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
246 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
247 BasicBlock *Header = Jmp->getSuccessor(0);
248 assert(Header == L->getHeader() && "expected a backward branch");
250 // Remove Latch from the CFG so that LastExit becomes the new Latch.
251 BI->setSuccessor(FallThruPath, Header);
252 Latch->replaceSuccessorsPhiUsesWith(LastExit);
253 Jmp->eraseFromParent();
255 // Nuke the Latch block.
256 assert(Latch->empty() && "unable to evacuate Latch");
257 LI->removeBlock(Latch);
258 if (DominatorTreeWrapperPass *DTWP =
259 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
260 DTWP->getDomTree().eraseNode(Latch);
261 Latch->eraseFromParent();
265 /// Rotate loop LP. Return true if the loop is rotated.
267 /// \param SimplifiedLatch is true if the latch was just folded into the final
268 /// loop exit. In this case we may want to rotate even though the new latch is
269 /// now an exiting branch. This rotation would have happened had the latch not
270 /// been simplified. However, if SimplifiedLatch is false, then we avoid
271 /// rotating loops in which the latch exits to avoid excessive or endless
272 /// rotation. LoopRotate should be repeatable and converge to a canonical
273 /// form. This property is satisfied because simplifying the loop latch can only
274 /// happen once across multiple invocations of the LoopRotate pass.
275 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
276 // If the loop has only one block then there is not much to rotate.
277 if (L->getBlocks().size() == 1)
280 BasicBlock *OrigHeader = L->getHeader();
281 BasicBlock *OrigLatch = L->getLoopLatch();
283 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
284 if (BI == 0 || BI->isUnconditional())
287 // If the loop header is not one of the loop exiting blocks then
288 // either this loop is already rotated or it is not
289 // suitable for loop rotation transformations.
290 if (!L->isLoopExiting(OrigHeader))
293 // If the loop latch already contains a branch that leaves the loop then the
294 // loop is already rotated.
298 // Rotate if either the loop latch does *not* exit the loop, or if the loop
299 // latch was just simplified.
300 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
303 // Check size of original header and reject loop if it is very big or we can't
304 // duplicate blocks inside it.
307 Metrics.analyzeBasicBlock(OrigHeader, *TTI);
308 if (Metrics.notDuplicatable) {
309 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
310 << " instructions: "; L->dump());
313 if (Metrics.NumInsts > MAX_HEADER_SIZE)
317 // Now, this loop is suitable for rotation.
318 BasicBlock *OrigPreheader = L->getLoopPreheader();
320 // If the loop could not be converted to canonical form, it must have an
321 // indirectbr in it, just give up.
322 if (OrigPreheader == 0)
325 // Anything ScalarEvolution may know about this loop or the PHI nodes
326 // in its header will soon be invalidated.
327 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
330 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
332 // Find new Loop header. NewHeader is a Header's one and only successor
333 // that is inside loop. Header's other successor is outside the
334 // loop. Otherwise loop is not suitable for rotation.
335 BasicBlock *Exit = BI->getSuccessor(0);
336 BasicBlock *NewHeader = BI->getSuccessor(1);
337 if (L->contains(Exit))
338 std::swap(Exit, NewHeader);
339 assert(NewHeader && "Unable to determine new loop header");
340 assert(L->contains(NewHeader) && !L->contains(Exit) &&
341 "Unable to determine loop header and exit blocks");
343 // This code assumes that the new header has exactly one predecessor.
344 // Remove any single-entry PHI nodes in it.
345 assert(NewHeader->getSinglePredecessor() &&
346 "New header doesn't have one pred!");
347 FoldSingleEntryPHINodes(NewHeader);
349 // Begin by walking OrigHeader and populating ValueMap with an entry for
351 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
352 ValueToValueMapTy ValueMap;
354 // For PHI nodes, the value available in OldPreHeader is just the
355 // incoming value from OldPreHeader.
356 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
357 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
359 // For the rest of the instructions, either hoist to the OrigPreheader if
360 // possible or create a clone in the OldPreHeader if not.
361 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
363 Instruction *Inst = I++;
365 // If the instruction's operands are invariant and it doesn't read or write
366 // memory, then it is safe to hoist. Doing this doesn't change the order of
367 // execution in the preheader, but does prevent the instruction from
368 // executing in each iteration of the loop. This means it is safe to hoist
369 // something that might trap, but isn't safe to hoist something that reads
370 // memory (without proving that the loop doesn't write).
371 if (L->hasLoopInvariantOperands(Inst) &&
372 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
373 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
374 !isa<AllocaInst>(Inst)) {
375 Inst->moveBefore(LoopEntryBranch);
379 // Otherwise, create a duplicate of the instruction.
380 Instruction *C = Inst->clone();
382 // Eagerly remap the operands of the instruction.
383 RemapInstruction(C, ValueMap,
384 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
386 // With the operands remapped, see if the instruction constant folds or is
387 // otherwise simplifyable. This commonly occurs because the entry from PHI
388 // nodes allows icmps and other instructions to fold.
389 Value *V = SimplifyInstruction(C);
390 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
391 // If so, then delete the temporary instruction and stick the folded value
396 // Otherwise, stick the new instruction into the new block!
397 C->setName(Inst->getName());
398 C->insertBefore(LoopEntryBranch);
403 // Along with all the other instructions, we just cloned OrigHeader's
404 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
405 // successors by duplicating their incoming values for OrigHeader.
406 TerminatorInst *TI = OrigHeader->getTerminator();
407 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
408 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
409 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
410 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
412 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
413 // OrigPreHeader's old terminator (the original branch into the loop), and
414 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
415 LoopEntryBranch->eraseFromParent();
417 // If there were any uses of instructions in the duplicated block outside the
418 // loop, update them, inserting PHI nodes as required
419 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
421 // NewHeader is now the header of the loop.
422 L->moveToHeader(NewHeader);
423 assert(L->getHeader() == NewHeader && "Latch block is our new header");
426 // At this point, we've finished our major CFG changes. As part of cloning
427 // the loop into the preheader we've simplified instructions and the
428 // duplicated conditional branch may now be branching on a constant. If it is
429 // branching on a constant and if that constant means that we enter the loop,
430 // then we fold away the cond branch to an uncond branch. This simplifies the
431 // loop in cases important for nested loops, and it also means we don't have
432 // to split as many edges.
433 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
434 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
435 if (!isa<ConstantInt>(PHBI->getCondition()) ||
436 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
438 // The conditional branch can't be folded, handle the general case.
439 // Update DominatorTree to reflect the CFG change we just made. Then split
440 // edges as necessary to preserve LoopSimplify form.
441 if (DominatorTreeWrapperPass *DTWP =
442 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
443 DominatorTree &DT = DTWP->getDomTree();
444 // Everything that was dominated by the old loop header is now dominated
445 // by the original loop preheader. Conceptually the header was merged
446 // into the preheader, even though we reuse the actual block as a new
448 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
449 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
450 OrigHeaderNode->end());
451 DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader);
452 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
453 DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
455 assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode);
456 assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode);
458 // Update OrigHeader to be dominated by the new header block.
459 DT.changeImmediateDominator(OrigHeader, OrigLatch);
462 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
463 // thus is not a preheader anymore.
464 // Split the edge to form a real preheader.
465 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
466 NewPH->setName(NewHeader->getName() + ".lr.ph");
468 // Preserve canonical loop form, which means that 'Exit' should have only
469 // one predecessor. Note that Exit could be an exit block for multiple
470 // nested loops, causing both of the edges to now be critical and need to
472 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
473 bool SplitLatchEdge = false;
474 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
475 PE = ExitPreds.end();
477 // We only need to split loop exit edges.
478 Loop *PredLoop = LI->getLoopFor(*PI);
479 if (!PredLoop || PredLoop->contains(Exit))
481 SplitLatchEdge |= L->getLoopLatch() == *PI;
482 BasicBlock *ExitSplit = SplitCriticalEdge(*PI, Exit, this);
483 ExitSplit->moveBefore(Exit);
485 assert(SplitLatchEdge &&
486 "Despite splitting all preds, failed to split latch exit?");
488 // We can fold the conditional branch in the preheader, this makes things
489 // simpler. The first step is to remove the extra edge to the Exit block.
490 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
491 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
492 NewBI->setDebugLoc(PHBI->getDebugLoc());
493 PHBI->eraseFromParent();
495 // With our CFG finalized, update DomTree if it is available.
496 if (DominatorTreeWrapperPass *DTWP =
497 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
498 DominatorTree &DT = DTWP->getDomTree();
499 // Update OrigHeader to be dominated by the new header block.
500 DT.changeImmediateDominator(NewHeader, OrigPreheader);
501 DT.changeImmediateDominator(OrigHeader, OrigLatch);
503 // Brute force incremental dominator tree update. Call
504 // findNearestCommonDominator on all CFG predecessors of each child of the
506 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
507 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
508 OrigHeaderNode->end());
512 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
513 DomTreeNode *Node = HeaderChildren[I];
514 BasicBlock *BB = Node->getBlock();
516 pred_iterator PI = pred_begin(BB);
517 BasicBlock *NearestDom = *PI;
518 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
519 NearestDom = DT.findNearestCommonDominator(NearestDom, *PI);
521 // Remember if this changes the DomTree.
522 if (Node->getIDom()->getBlock() != NearestDom) {
523 DT.changeImmediateDominator(BB, NearestDom);
528 // If the dominator changed, this may have an effect on other
529 // predecessors, continue until we reach a fixpoint.
534 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
535 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
537 // Now that the CFG and DomTree are in a consistent state again, try to merge
538 // the OrigHeader block into OrigLatch. This will succeed if they are
539 // connected by an unconditional branch. This is just a cleanup so the
540 // emitted code isn't too gross in this common case.
541 MergeBlockIntoPredecessor(OrigHeader, this);
543 DEBUG(dbgs() << "LoopRotation: into "; L->dump());