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 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/AssumptionTracker.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/CFG.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Transforms/Utils/SSAUpdater.h"
32 #include "llvm/Transforms/Utils/ValueMapper.h"
35 #define DEBUG_TYPE "loop-rotate"
37 static cl::opt<unsigned>
38 DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
39 cl::desc("The default maximum header size for automatic loop rotation"));
41 STATISTIC(NumRotated, "Number of loops rotated");
44 class LoopRotate : public LoopPass {
46 static char ID; // Pass ID, replacement for typeid
47 LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
48 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
49 if (SpecifiedMaxHeaderSize == -1)
50 MaxHeaderSize = DefaultRotationThreshold;
52 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
55 // LCSSA form makes instruction renaming easier.
56 void getAnalysisUsage(AnalysisUsage &AU) const override {
57 AU.addRequired<AssumptionTracker>();
58 AU.addPreserved<DominatorTreeWrapperPass>();
59 AU.addRequired<LoopInfo>();
60 AU.addPreserved<LoopInfo>();
61 AU.addRequiredID(LoopSimplifyID);
62 AU.addPreservedID(LoopSimplifyID);
63 AU.addRequiredID(LCSSAID);
64 AU.addPreservedID(LCSSAID);
65 AU.addPreserved<ScalarEvolution>();
66 AU.addRequired<TargetTransformInfo>();
69 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
70 bool simplifyLoopLatch(Loop *L);
71 bool rotateLoop(Loop *L, bool SimplifiedLatch);
74 unsigned MaxHeaderSize;
76 const TargetTransformInfo *TTI;
77 AssumptionTracker *AT;
81 char LoopRotate::ID = 0;
82 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
83 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
84 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
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(int MaxHeaderSize) {
91 return new LoopRotate(MaxHeaderSize);
94 /// Rotate Loop L as many times as possible. Return true if
95 /// the loop is rotated at least once.
96 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
97 if (skipOptnoneFunction(L))
100 // Save the loop metadata.
101 MDNode *LoopMD = L->getLoopID();
103 LI = &getAnalysis<LoopInfo>();
104 TTI = &getAnalysis<TargetTransformInfo>();
105 AT = &getAnalysis<AssumptionTracker>();
107 // Simplify the loop latch before attempting to rotate the header
108 // upward. Rotation may not be needed if the loop tail can be folded into the
110 bool SimplifiedLatch = simplifyLoopLatch(L);
112 // One loop can be rotated multiple times.
113 bool MadeChange = false;
114 while (rotateLoop(L, SimplifiedLatch)) {
116 SimplifiedLatch = false;
119 // Restore the loop metadata.
120 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
121 if ((MadeChange || SimplifiedLatch) && LoopMD)
122 L->setLoopID(LoopMD);
127 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
128 /// old header into the preheader. If there were uses of the values produced by
129 /// these instruction that were outside of the loop, we have to insert PHI nodes
130 /// to merge the two values. Do this now.
131 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
132 BasicBlock *OrigPreheader,
133 ValueToValueMapTy &ValueMap) {
134 // Remove PHI node entries that are no longer live.
135 BasicBlock::iterator I, E = OrigHeader->end();
136 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
137 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
139 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
142 for (I = OrigHeader->begin(); I != E; ++I) {
143 Value *OrigHeaderVal = I;
145 // If there are no uses of the value (e.g. because it returns void), there
146 // is nothing to rewrite.
147 if (OrigHeaderVal->use_empty())
150 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
152 // The value now exits in two versions: the initial value in the preheader
153 // and the loop "next" value in the original header.
154 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
155 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
156 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
158 // Visit each use of the OrigHeader instruction.
159 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
160 UE = OrigHeaderVal->use_end(); UI != UE; ) {
161 // Grab the use before incrementing the iterator.
164 // Increment the iterator before removing the use from the list.
167 // SSAUpdater can't handle a non-PHI use in the same block as an
168 // earlier def. We can easily handle those cases manually.
169 Instruction *UserInst = cast<Instruction>(U.getUser());
170 if (!isa<PHINode>(UserInst)) {
171 BasicBlock *UserBB = UserInst->getParent();
173 // The original users in the OrigHeader are already using the
174 // original definitions.
175 if (UserBB == OrigHeader)
178 // Users in the OrigPreHeader need to use the value to which the
179 // original definitions are mapped.
180 if (UserBB == OrigPreheader) {
181 U = OrigPreHeaderVal;
186 // Anything else can be handled by SSAUpdater.
192 /// Determine whether the instructions in this range may be safely and cheaply
193 /// speculated. This is not an important enough situation to develop complex
194 /// heuristics. We handle a single arithmetic instruction along with any type
196 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
197 BasicBlock::iterator End) {
198 bool seenIncrement = false;
199 for (BasicBlock::iterator I = Begin; I != End; ++I) {
201 if (!isSafeToSpeculativelyExecute(I))
204 if (isa<DbgInfoIntrinsic>(I))
207 switch (I->getOpcode()) {
210 case Instruction::GetElementPtr:
211 // GEPs are cheap if all indices are constant.
212 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
214 // fall-thru to increment case
215 case Instruction::Add:
216 case Instruction::Sub:
217 case Instruction::And:
218 case Instruction::Or:
219 case Instruction::Xor:
220 case Instruction::Shl:
221 case Instruction::LShr:
222 case Instruction::AShr:
225 seenIncrement = true;
227 case Instruction::Trunc:
228 case Instruction::ZExt:
229 case Instruction::SExt:
230 // ignore type conversions
237 /// Fold the loop tail into the loop exit by speculating the loop tail
238 /// instructions. Typically, this is a single post-increment. In the case of a
239 /// simple 2-block loop, hoisting the increment can be much better than
240 /// duplicating the entire loop header. In the case of loops with early exits,
241 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
242 /// canonical form so downstream passes can handle it.
244 /// I don't believe this invalidates SCEV.
245 bool LoopRotate::simplifyLoopLatch(Loop *L) {
246 BasicBlock *Latch = L->getLoopLatch();
247 if (!Latch || Latch->hasAddressTaken())
250 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
251 if (!Jmp || !Jmp->isUnconditional())
254 BasicBlock *LastExit = Latch->getSinglePredecessor();
255 if (!LastExit || !L->isLoopExiting(LastExit))
258 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
262 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
265 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
266 << LastExit->getName() << "\n");
268 // Hoist the instructions from Latch into LastExit.
269 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
271 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
272 BasicBlock *Header = Jmp->getSuccessor(0);
273 assert(Header == L->getHeader() && "expected a backward branch");
275 // Remove Latch from the CFG so that LastExit becomes the new Latch.
276 BI->setSuccessor(FallThruPath, Header);
277 Latch->replaceSuccessorsPhiUsesWith(LastExit);
278 Jmp->eraseFromParent();
280 // Nuke the Latch block.
281 assert(Latch->empty() && "unable to evacuate Latch");
282 LI->removeBlock(Latch);
283 if (DominatorTreeWrapperPass *DTWP =
284 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
285 DTWP->getDomTree().eraseNode(Latch);
286 Latch->eraseFromParent();
290 /// Rotate loop LP. Return true if the loop is rotated.
292 /// \param SimplifiedLatch is true if the latch was just folded into the final
293 /// loop exit. In this case we may want to rotate even though the new latch is
294 /// now an exiting branch. This rotation would have happened had the latch not
295 /// been simplified. However, if SimplifiedLatch is false, then we avoid
296 /// rotating loops in which the latch exits to avoid excessive or endless
297 /// rotation. LoopRotate should be repeatable and converge to a canonical
298 /// form. This property is satisfied because simplifying the loop latch can only
299 /// happen once across multiple invocations of the LoopRotate pass.
300 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
301 // If the loop has only one block then there is not much to rotate.
302 if (L->getBlocks().size() == 1)
305 BasicBlock *OrigHeader = L->getHeader();
306 BasicBlock *OrigLatch = L->getLoopLatch();
308 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
309 if (!BI || BI->isUnconditional())
312 // If the loop header is not one of the loop exiting blocks then
313 // either this loop is already rotated or it is not
314 // suitable for loop rotation transformations.
315 if (!L->isLoopExiting(OrigHeader))
318 // If the loop latch already contains a branch that leaves the loop then the
319 // loop is already rotated.
323 // Rotate if either the loop latch does *not* exit the loop, or if the loop
324 // latch was just simplified.
325 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
328 // Check size of original header and reject loop if it is very big or we can't
329 // duplicate blocks inside it.
331 SmallPtrSet<const Value *, 32> EphValues;
332 CodeMetrics::collectEphemeralValues(L, AT, EphValues);
335 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
336 if (Metrics.notDuplicatable) {
337 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
338 << " instructions: "; L->dump());
341 if (Metrics.NumInsts > MaxHeaderSize)
345 // Now, this loop is suitable for rotation.
346 BasicBlock *OrigPreheader = L->getLoopPreheader();
348 // If the loop could not be converted to canonical form, it must have an
349 // indirectbr in it, just give up.
353 // Anything ScalarEvolution may know about this loop or the PHI nodes
354 // in its header will soon be invalidated.
355 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
358 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
360 // Find new Loop header. NewHeader is a Header's one and only successor
361 // that is inside loop. Header's other successor is outside the
362 // loop. Otherwise loop is not suitable for rotation.
363 BasicBlock *Exit = BI->getSuccessor(0);
364 BasicBlock *NewHeader = BI->getSuccessor(1);
365 if (L->contains(Exit))
366 std::swap(Exit, NewHeader);
367 assert(NewHeader && "Unable to determine new loop header");
368 assert(L->contains(NewHeader) && !L->contains(Exit) &&
369 "Unable to determine loop header and exit blocks");
371 // This code assumes that the new header has exactly one predecessor.
372 // Remove any single-entry PHI nodes in it.
373 assert(NewHeader->getSinglePredecessor() &&
374 "New header doesn't have one pred!");
375 FoldSingleEntryPHINodes(NewHeader);
377 // Begin by walking OrigHeader and populating ValueMap with an entry for
379 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
380 ValueToValueMapTy ValueMap;
382 // For PHI nodes, the value available in OldPreHeader is just the
383 // incoming value from OldPreHeader.
384 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
385 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
387 // For the rest of the instructions, either hoist to the OrigPreheader if
388 // possible or create a clone in the OldPreHeader if not.
389 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
391 Instruction *Inst = I++;
393 // If the instruction's operands are invariant and it doesn't read or write
394 // memory, then it is safe to hoist. Doing this doesn't change the order of
395 // execution in the preheader, but does prevent the instruction from
396 // executing in each iteration of the loop. This means it is safe to hoist
397 // something that might trap, but isn't safe to hoist something that reads
398 // memory (without proving that the loop doesn't write).
399 if (L->hasLoopInvariantOperands(Inst) &&
400 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
401 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
402 !isa<AllocaInst>(Inst)) {
403 Inst->moveBefore(LoopEntryBranch);
407 // Otherwise, create a duplicate of the instruction.
408 Instruction *C = Inst->clone();
410 // Eagerly remap the operands of the instruction.
411 RemapInstruction(C, ValueMap,
412 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
414 // With the operands remapped, see if the instruction constant folds or is
415 // otherwise simplifyable. This commonly occurs because the entry from PHI
416 // nodes allows icmps and other instructions to fold.
417 // FIXME: Provide DL, TLI, DT, AT to SimplifyInstruction.
418 Value *V = SimplifyInstruction(C);
419 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
420 // If so, then delete the temporary instruction and stick the folded value
425 // Otherwise, stick the new instruction into the new block!
426 C->setName(Inst->getName());
427 C->insertBefore(LoopEntryBranch);
432 // Along with all the other instructions, we just cloned OrigHeader's
433 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
434 // successors by duplicating their incoming values for OrigHeader.
435 TerminatorInst *TI = OrigHeader->getTerminator();
436 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
437 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
438 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
439 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
441 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
442 // OrigPreHeader's old terminator (the original branch into the loop), and
443 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
444 LoopEntryBranch->eraseFromParent();
446 // If there were any uses of instructions in the duplicated block outside the
447 // loop, update them, inserting PHI nodes as required
448 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
450 // NewHeader is now the header of the loop.
451 L->moveToHeader(NewHeader);
452 assert(L->getHeader() == NewHeader && "Latch block is our new header");
455 // At this point, we've finished our major CFG changes. As part of cloning
456 // the loop into the preheader we've simplified instructions and the
457 // duplicated conditional branch may now be branching on a constant. If it is
458 // branching on a constant and if that constant means that we enter the loop,
459 // then we fold away the cond branch to an uncond branch. This simplifies the
460 // loop in cases important for nested loops, and it also means we don't have
461 // to split as many edges.
462 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
463 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
464 if (!isa<ConstantInt>(PHBI->getCondition()) ||
465 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
467 // The conditional branch can't be folded, handle the general case.
468 // Update DominatorTree to reflect the CFG change we just made. Then split
469 // edges as necessary to preserve LoopSimplify form.
470 if (DominatorTreeWrapperPass *DTWP =
471 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
472 DominatorTree &DT = DTWP->getDomTree();
473 // Everything that was dominated by the old loop header is now dominated
474 // by the original loop preheader. Conceptually the header was merged
475 // into the preheader, even though we reuse the actual block as a new
477 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
478 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
479 OrigHeaderNode->end());
480 DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader);
481 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
482 DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
484 assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode);
485 assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode);
487 // Update OrigHeader to be dominated by the new header block.
488 DT.changeImmediateDominator(OrigHeader, OrigLatch);
491 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
492 // thus is not a preheader anymore.
493 // Split the edge to form a real preheader.
494 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
495 NewPH->setName(NewHeader->getName() + ".lr.ph");
497 // Preserve canonical loop form, which means that 'Exit' should have only
498 // one predecessor. Note that Exit could be an exit block for multiple
499 // nested loops, causing both of the edges to now be critical and need to
501 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
502 bool SplitLatchEdge = false;
503 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
504 PE = ExitPreds.end();
506 // We only need to split loop exit edges.
507 Loop *PredLoop = LI->getLoopFor(*PI);
508 if (!PredLoop || PredLoop->contains(Exit))
510 SplitLatchEdge |= L->getLoopLatch() == *PI;
511 BasicBlock *ExitSplit = SplitCriticalEdge(*PI, Exit, this);
512 ExitSplit->moveBefore(Exit);
514 assert(SplitLatchEdge &&
515 "Despite splitting all preds, failed to split latch exit?");
517 // We can fold the conditional branch in the preheader, this makes things
518 // simpler. The first step is to remove the extra edge to the Exit block.
519 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
520 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
521 NewBI->setDebugLoc(PHBI->getDebugLoc());
522 PHBI->eraseFromParent();
524 // With our CFG finalized, update DomTree if it is available.
525 if (DominatorTreeWrapperPass *DTWP =
526 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
527 DominatorTree &DT = DTWP->getDomTree();
528 // Update OrigHeader to be dominated by the new header block.
529 DT.changeImmediateDominator(NewHeader, OrigPreheader);
530 DT.changeImmediateDominator(OrigHeader, OrigLatch);
532 // Brute force incremental dominator tree update. Call
533 // findNearestCommonDominator on all CFG predecessors of each child of the
535 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
536 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
537 OrigHeaderNode->end());
541 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
542 DomTreeNode *Node = HeaderChildren[I];
543 BasicBlock *BB = Node->getBlock();
545 pred_iterator PI = pred_begin(BB);
546 BasicBlock *NearestDom = *PI;
547 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
548 NearestDom = DT.findNearestCommonDominator(NearestDom, *PI);
550 // Remember if this changes the DomTree.
551 if (Node->getIDom()->getBlock() != NearestDom) {
552 DT.changeImmediateDominator(BB, NearestDom);
557 // If the dominator changed, this may have an effect on other
558 // predecessors, continue until we reach a fixpoint.
563 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
564 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
566 // Now that the CFG and DomTree are in a consistent state again, try to merge
567 // the OrigHeader block into OrigLatch. This will succeed if they are
568 // connected by an unconditional branch. This is just a cleanup so the
569 // emitted code isn't too gross in this common case.
570 MergeBlockIntoPredecessor(OrigHeader, this);
572 DEBUG(dbgs() << "LoopRotation: into "; L->dump());