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/LoopRotation.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/BasicAliasAnalysis.h"
19 #include "llvm/Analysis/CodeMetrics.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
25 #include "llvm/Analysis/TargetTransformInfo.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Scalar/LoopPassManager.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/LoopUtils.h"
40 #include "llvm/Transforms/Utils/SSAUpdater.h"
41 #include "llvm/Transforms/Utils/ValueMapper.h"
44 #define DEBUG_TYPE "loop-rotate"
46 static cl::opt<unsigned> DefaultRotationThreshold(
47 "rotation-max-header-size", cl::init(16), cl::Hidden,
48 cl::desc("The default maximum header size for automatic loop rotation"));
50 STATISTIC(NumRotated, "Number of loops rotated");
53 /// A simple loop rotation transformation.
55 const unsigned MaxHeaderSize;
57 const TargetTransformInfo *TTI;
61 const SimplifyQuery &SQ;
64 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
65 const TargetTransformInfo *TTI, AssumptionCache *AC,
66 DominatorTree *DT, ScalarEvolution *SE, const SimplifyQuery &SQ)
67 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
69 bool processLoop(Loop *L);
72 bool rotateLoop(Loop *L, bool SimplifiedLatch);
73 bool simplifyLoopLatch(Loop *L);
75 } // end anonymous namespace
77 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
78 /// old header into the preheader. If there were uses of the values produced by
79 /// these instruction that were outside of the loop, we have to insert PHI nodes
80 /// to merge the two values. Do this now.
81 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
82 BasicBlock *OrigPreheader,
83 ValueToValueMapTy &ValueMap,
84 SmallVectorImpl<PHINode*> *InsertedPHIs) {
85 // Remove PHI node entries that are no longer live.
86 BasicBlock::iterator I, E = OrigHeader->end();
87 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
88 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
90 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
92 SSAUpdater SSA(InsertedPHIs);
93 for (I = OrigHeader->begin(); I != E; ++I) {
94 Value *OrigHeaderVal = &*I;
96 // If there are no uses of the value (e.g. because it returns void), there
97 // is nothing to rewrite.
98 if (OrigHeaderVal->use_empty())
101 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
103 // The value now exits in two versions: the initial value in the preheader
104 // and the loop "next" value in the original header.
105 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
106 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
107 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
109 // Visit each use of the OrigHeader instruction.
110 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
111 UE = OrigHeaderVal->use_end();
113 // Grab the use before incrementing the iterator.
116 // Increment the iterator before removing the use from the list.
119 // SSAUpdater can't handle a non-PHI use in the same block as an
120 // earlier def. We can easily handle those cases manually.
121 Instruction *UserInst = cast<Instruction>(U.getUser());
122 if (!isa<PHINode>(UserInst)) {
123 BasicBlock *UserBB = UserInst->getParent();
125 // The original users in the OrigHeader are already using the
126 // original definitions.
127 if (UserBB == OrigHeader)
130 // Users in the OrigPreHeader need to use the value to which the
131 // original definitions are mapped.
132 if (UserBB == OrigPreheader) {
133 U = OrigPreHeaderVal;
138 // Anything else can be handled by SSAUpdater.
142 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
144 LLVMContext &C = OrigHeader->getContext();
145 if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) {
146 if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) {
147 for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E;) {
148 // Grab the use before incrementing the iterator. Otherwise, altering
149 // the Use will invalidate the iterator.
151 DbgInfoIntrinsic *UserInst = dyn_cast<DbgInfoIntrinsic>(U.getUser());
155 // The original users in the OrigHeader are already using the original
157 BasicBlock *UserBB = UserInst->getParent();
158 if (UserBB == OrigHeader)
161 // Users in the OrigPreHeader need to use the value to which the
162 // original definitions are mapped and anything else can be handled by
163 // the SSAUpdater. To avoid adding PHINodes, check if the value is
164 // available in UserBB, if not substitute undef.
166 if (UserBB == OrigPreheader)
167 NewVal = OrigPreHeaderVal;
168 else if (SSA.HasValueForBlock(UserBB))
169 NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
171 NewVal = UndefValue::get(OrigHeaderVal->getType());
172 U = MetadataAsValue::get(C, ValueAsMetadata::get(NewVal));
179 /// Propagate dbg.value intrinsics through the newly inserted Phis.
180 static void insertDebugValues(BasicBlock *OrigHeader,
181 SmallVectorImpl<PHINode*> &InsertedPHIs) {
182 ValueToValueMapTy DbgValueMap;
184 // Map existing PHI nodes to their dbg.values.
185 for (auto &I : *OrigHeader) {
186 if (auto DbgII = dyn_cast<DbgInfoIntrinsic>(&I)) {
187 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
188 DbgValueMap.insert({Loc, DbgII});
192 // Then iterate through the new PHIs and look to see if they use one of the
193 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
194 // propagate the info through the new PHI.
195 LLVMContext &C = OrigHeader->getContext();
196 for (auto PHI : InsertedPHIs) {
197 for (auto VI : PHI->operand_values()) {
198 auto V = DbgValueMap.find(VI);
199 if (V != DbgValueMap.end()) {
200 auto *DbgII = cast<DbgInfoIntrinsic>(V->second);
201 Instruction *NewDbgII = DbgII->clone();
202 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
203 NewDbgII->setOperand(0, PhiMAV);
204 BasicBlock *Parent = PHI->getParent();
205 NewDbgII->insertBefore(Parent->getFirstNonPHIOrDbgOrLifetime());
211 /// Rotate loop LP. Return true if the loop is rotated.
213 /// \param SimplifiedLatch is true if the latch was just folded into the final
214 /// loop exit. In this case we may want to rotate even though the new latch is
215 /// now an exiting branch. This rotation would have happened had the latch not
216 /// been simplified. However, if SimplifiedLatch is false, then we avoid
217 /// rotating loops in which the latch exits to avoid excessive or endless
218 /// rotation. LoopRotate should be repeatable and converge to a canonical
219 /// form. This property is satisfied because simplifying the loop latch can only
220 /// happen once across multiple invocations of the LoopRotate pass.
221 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
222 // If the loop has only one block then there is not much to rotate.
223 if (L->getBlocks().size() == 1)
226 BasicBlock *OrigHeader = L->getHeader();
227 BasicBlock *OrigLatch = L->getLoopLatch();
229 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
230 if (!BI || BI->isUnconditional())
233 // If the loop header is not one of the loop exiting blocks then
234 // either this loop is already rotated or it is not
235 // suitable for loop rotation transformations.
236 if (!L->isLoopExiting(OrigHeader))
239 // If the loop latch already contains a branch that leaves the loop then the
240 // loop is already rotated.
244 // Rotate if either the loop latch does *not* exit the loop, or if the loop
245 // latch was just simplified.
246 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
249 // Check size of original header and reject loop if it is very big or we can't
250 // duplicate blocks inside it.
252 SmallPtrSet<const Value *, 32> EphValues;
253 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
256 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
257 if (Metrics.notDuplicatable) {
258 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
259 << " instructions: ";
263 if (Metrics.convergent) {
264 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
269 if (Metrics.NumInsts > MaxHeaderSize)
273 // Now, this loop is suitable for rotation.
274 BasicBlock *OrigPreheader = L->getLoopPreheader();
276 // If the loop could not be converted to canonical form, it must have an
277 // indirectbr in it, just give up.
281 // Anything ScalarEvolution may know about this loop or the PHI nodes
282 // in its header will soon be invalidated.
286 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
288 // Find new Loop header. NewHeader is a Header's one and only successor
289 // that is inside loop. Header's other successor is outside the
290 // loop. Otherwise loop is not suitable for rotation.
291 BasicBlock *Exit = BI->getSuccessor(0);
292 BasicBlock *NewHeader = BI->getSuccessor(1);
293 if (L->contains(Exit))
294 std::swap(Exit, NewHeader);
295 assert(NewHeader && "Unable to determine new loop header");
296 assert(L->contains(NewHeader) && !L->contains(Exit) &&
297 "Unable to determine loop header and exit blocks");
299 // This code assumes that the new header has exactly one predecessor.
300 // Remove any single-entry PHI nodes in it.
301 assert(NewHeader->getSinglePredecessor() &&
302 "New header doesn't have one pred!");
303 FoldSingleEntryPHINodes(NewHeader);
305 // Begin by walking OrigHeader and populating ValueMap with an entry for
307 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
308 ValueToValueMapTy ValueMap;
310 // For PHI nodes, the value available in OldPreHeader is just the
311 // incoming value from OldPreHeader.
312 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
313 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
315 // For the rest of the instructions, either hoist to the OrigPreheader if
316 // possible or create a clone in the OldPreHeader if not.
317 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
319 Instruction *Inst = &*I++;
321 // If the instruction's operands are invariant and it doesn't read or write
322 // memory, then it is safe to hoist. Doing this doesn't change the order of
323 // execution in the preheader, but does prevent the instruction from
324 // executing in each iteration of the loop. This means it is safe to hoist
325 // something that might trap, but isn't safe to hoist something that reads
326 // memory (without proving that the loop doesn't write).
327 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
328 !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
329 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
330 Inst->moveBefore(LoopEntryBranch);
334 // Otherwise, create a duplicate of the instruction.
335 Instruction *C = Inst->clone();
337 // Eagerly remap the operands of the instruction.
338 RemapInstruction(C, ValueMap,
339 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
341 // With the operands remapped, see if the instruction constant folds or is
342 // otherwise simplifyable. This commonly occurs because the entry from PHI
343 // nodes allows icmps and other instructions to fold.
344 Value *V = SimplifyInstruction(C, SQ);
345 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
346 // If so, then delete the temporary instruction and stick the folded value
349 if (!C->mayHaveSideEffects()) {
357 // Otherwise, stick the new instruction into the new block!
358 C->setName(Inst->getName());
359 C->insertBefore(LoopEntryBranch);
361 if (auto *II = dyn_cast<IntrinsicInst>(C))
362 if (II->getIntrinsicID() == Intrinsic::assume)
363 AC->registerAssumption(II);
367 // Along with all the other instructions, we just cloned OrigHeader's
368 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
369 // successors by duplicating their incoming values for OrigHeader.
370 TerminatorInst *TI = OrigHeader->getTerminator();
371 for (BasicBlock *SuccBB : TI->successors())
372 for (BasicBlock::iterator BI = SuccBB->begin();
373 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
374 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
376 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
377 // OrigPreHeader's old terminator (the original branch into the loop), and
378 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
379 LoopEntryBranch->eraseFromParent();
382 SmallVector<PHINode*, 2> InsertedPHIs;
383 // If there were any uses of instructions in the duplicated block outside the
384 // loop, update them, inserting PHI nodes as required
385 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
388 // Attach dbg.value intrinsics to the new phis if that phi uses a value that
389 // previously had debug metadata attached. This keeps the debug info
390 // up-to-date in the loop body.
391 if (!InsertedPHIs.empty())
392 insertDebugValues(OrigHeader, InsertedPHIs);
394 // NewHeader is now the header of the loop.
395 L->moveToHeader(NewHeader);
396 assert(L->getHeader() == NewHeader && "Latch block is our new header");
398 // At this point, we've finished our major CFG changes. As part of cloning
399 // the loop into the preheader we've simplified instructions and the
400 // duplicated conditional branch may now be branching on a constant. If it is
401 // branching on a constant and if that constant means that we enter the loop,
402 // then we fold away the cond branch to an uncond branch. This simplifies the
403 // loop in cases important for nested loops, and it also means we don't have
404 // to split as many edges.
405 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
406 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
407 if (!isa<ConstantInt>(PHBI->getCondition()) ||
408 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
410 // The conditional branch can't be folded, handle the general case.
411 // Update DominatorTree to reflect the CFG change we just made. Then split
412 // edges as necessary to preserve LoopSimplify form.
414 // Everything that was dominated by the old loop header is now dominated
415 // by the original loop preheader. Conceptually the header was merged
416 // into the preheader, even though we reuse the actual block as a new
418 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
419 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
420 OrigHeaderNode->end());
421 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
422 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
423 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
425 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
426 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
428 // Update OrigHeader to be dominated by the new header block.
429 DT->changeImmediateDominator(OrigHeader, OrigLatch);
432 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
433 // thus is not a preheader anymore.
434 // Split the edge to form a real preheader.
435 BasicBlock *NewPH = SplitCriticalEdge(
436 OrigPreheader, NewHeader,
437 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
438 NewPH->setName(NewHeader->getName() + ".lr.ph");
440 // Preserve canonical loop form, which means that 'Exit' should have only
441 // one predecessor. Note that Exit could be an exit block for multiple
442 // nested loops, causing both of the edges to now be critical and need to
444 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
445 bool SplitLatchEdge = false;
446 for (BasicBlock *ExitPred : ExitPreds) {
447 // We only need to split loop exit edges.
448 Loop *PredLoop = LI->getLoopFor(ExitPred);
449 if (!PredLoop || PredLoop->contains(Exit))
451 if (isa<IndirectBrInst>(ExitPred->getTerminator()))
453 SplitLatchEdge |= L->getLoopLatch() == ExitPred;
454 BasicBlock *ExitSplit = SplitCriticalEdge(
456 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
457 ExitSplit->moveBefore(Exit);
459 assert(SplitLatchEdge &&
460 "Despite splitting all preds, failed to split latch exit?");
462 // We can fold the conditional branch in the preheader, this makes things
463 // simpler. The first step is to remove the extra edge to the Exit block.
464 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
465 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
466 NewBI->setDebugLoc(PHBI->getDebugLoc());
467 PHBI->eraseFromParent();
469 // With our CFG finalized, update DomTree if it is available.
471 // Update OrigHeader to be dominated by the new header block.
472 DT->changeImmediateDominator(NewHeader, OrigPreheader);
473 DT->changeImmediateDominator(OrigHeader, OrigLatch);
475 // Brute force incremental dominator tree update. Call
476 // findNearestCommonDominator on all CFG predecessors of each child of the
478 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
479 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
480 OrigHeaderNode->end());
484 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
485 DomTreeNode *Node = HeaderChildren[I];
486 BasicBlock *BB = Node->getBlock();
488 BasicBlock *NearestDom = nullptr;
489 for (BasicBlock *Pred : predecessors(BB)) {
490 // Consider only reachable basic blocks.
491 if (!DT->getNode(Pred))
499 NearestDom = DT->findNearestCommonDominator(NearestDom, Pred);
500 assert(NearestDom && "No NearestCommonDominator found");
503 assert(NearestDom && "Nearest dominator not found");
505 // Remember if this changes the DomTree.
506 if (Node->getIDom()->getBlock() != NearestDom) {
507 DT->changeImmediateDominator(BB, NearestDom);
512 // If the dominator changed, this may have an effect on other
513 // predecessors, continue until we reach a fixpoint.
518 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
519 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
521 // Now that the CFG and DomTree are in a consistent state again, try to merge
522 // the OrigHeader block into OrigLatch. This will succeed if they are
523 // connected by an unconditional branch. This is just a cleanup so the
524 // emitted code isn't too gross in this common case.
525 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
527 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
533 /// Determine whether the instructions in this range may be safely and cheaply
534 /// speculated. This is not an important enough situation to develop complex
535 /// heuristics. We handle a single arithmetic instruction along with any type
537 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
538 BasicBlock::iterator End, Loop *L) {
539 bool seenIncrement = false;
540 bool MultiExitLoop = false;
542 if (!L->getExitingBlock())
543 MultiExitLoop = true;
545 for (BasicBlock::iterator I = Begin; I != End; ++I) {
547 if (!isSafeToSpeculativelyExecute(&*I))
550 if (isa<DbgInfoIntrinsic>(I))
553 switch (I->getOpcode()) {
556 case Instruction::GetElementPtr:
557 // GEPs are cheap if all indices are constant.
558 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
560 // fall-thru to increment case
562 case Instruction::Add:
563 case Instruction::Sub:
564 case Instruction::And:
565 case Instruction::Or:
566 case Instruction::Xor:
567 case Instruction::Shl:
568 case Instruction::LShr:
569 case Instruction::AShr: {
571 !isa<Constant>(I->getOperand(0))
573 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
577 // If increment operand is used outside of the loop, this speculation
578 // could cause extra live range interference.
580 for (User *UseI : IVOpnd->users()) {
581 auto *UserInst = cast<Instruction>(UseI);
582 if (!L->contains(UserInst))
589 seenIncrement = true;
592 case Instruction::Trunc:
593 case Instruction::ZExt:
594 case Instruction::SExt:
595 // ignore type conversions
602 /// Fold the loop tail into the loop exit by speculating the loop tail
603 /// instructions. Typically, this is a single post-increment. In the case of a
604 /// simple 2-block loop, hoisting the increment can be much better than
605 /// duplicating the entire loop header. In the case of loops with early exits,
606 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
607 /// canonical form so downstream passes can handle it.
609 /// I don't believe this invalidates SCEV.
610 bool LoopRotate::simplifyLoopLatch(Loop *L) {
611 BasicBlock *Latch = L->getLoopLatch();
612 if (!Latch || Latch->hasAddressTaken())
615 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
616 if (!Jmp || !Jmp->isUnconditional())
619 BasicBlock *LastExit = Latch->getSinglePredecessor();
620 if (!LastExit || !L->isLoopExiting(LastExit))
623 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
627 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
630 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
631 << LastExit->getName() << "\n");
633 // Hoist the instructions from Latch into LastExit.
634 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
635 Latch->begin(), Jmp->getIterator());
637 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
638 BasicBlock *Header = Jmp->getSuccessor(0);
639 assert(Header == L->getHeader() && "expected a backward branch");
641 // Remove Latch from the CFG so that LastExit becomes the new Latch.
642 BI->setSuccessor(FallThruPath, Header);
643 Latch->replaceSuccessorsPhiUsesWith(LastExit);
644 Jmp->eraseFromParent();
646 // Nuke the Latch block.
647 assert(Latch->empty() && "unable to evacuate Latch");
648 LI->removeBlock(Latch);
650 DT->eraseNode(Latch);
651 Latch->eraseFromParent();
655 /// Rotate \c L, and return true if any modification was made.
656 bool LoopRotate::processLoop(Loop *L) {
657 // Save the loop metadata.
658 MDNode *LoopMD = L->getLoopID();
660 // Simplify the loop latch before attempting to rotate the header
661 // upward. Rotation may not be needed if the loop tail can be folded into the
663 bool SimplifiedLatch = simplifyLoopLatch(L);
665 bool MadeChange = rotateLoop(L, SimplifiedLatch);
666 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
667 "Loop latch should be exiting after loop-rotate.");
669 // Restore the loop metadata.
670 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
671 if ((MadeChange || SimplifiedLatch) && LoopMD)
672 L->setLoopID(LoopMD);
677 LoopRotatePass::LoopRotatePass(bool EnableHeaderDuplication)
678 : EnableHeaderDuplication(EnableHeaderDuplication) {}
680 PreservedAnalyses LoopRotatePass::run(Loop &L, LoopAnalysisManager &AM,
681 LoopStandardAnalysisResults &AR,
683 int Threshold = EnableHeaderDuplication ? DefaultRotationThreshold : 0;
684 const DataLayout &DL = L.getHeader()->getModule()->getDataLayout();
685 const SimplifyQuery SQ = getBestSimplifyQuery(AR, DL);
686 LoopRotate LR(Threshold, &AR.LI, &AR.TTI, &AR.AC, &AR.DT, &AR.SE,
689 bool Changed = LR.processLoop(&L);
691 return PreservedAnalyses::all();
693 return getLoopPassPreservedAnalyses();
698 class LoopRotateLegacyPass : public LoopPass {
699 unsigned MaxHeaderSize;
702 static char ID; // Pass ID, replacement for typeid
703 LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
704 initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
705 if (SpecifiedMaxHeaderSize == -1)
706 MaxHeaderSize = DefaultRotationThreshold;
708 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
711 // LCSSA form makes instruction renaming easier.
712 void getAnalysisUsage(AnalysisUsage &AU) const override {
713 AU.addRequired<AssumptionCacheTracker>();
714 AU.addRequired<TargetTransformInfoWrapperPass>();
715 getLoopAnalysisUsage(AU);
718 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
721 Function &F = *L->getHeader()->getParent();
723 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
724 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
725 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
726 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
727 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
728 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
729 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
730 const SimplifyQuery SQ = getBestSimplifyQuery(*this, F);
731 LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE, SQ);
732 return LR.processLoop(L);
737 char LoopRotateLegacyPass::ID = 0;
738 INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
740 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
741 INITIALIZE_PASS_DEPENDENCY(LoopPass)
742 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
743 INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
746 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
747 return new LoopRotateLegacyPass(MaxHeaderSize);