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/DebugInfoMetadata.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Scalar/LoopPassManager.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Utils/LoopUtils.h"
41 #include "llvm/Transforms/Utils/SSAUpdater.h"
42 #include "llvm/Transforms/Utils/ValueMapper.h"
45 #define DEBUG_TYPE "loop-rotate"
47 static cl::opt<unsigned> DefaultRotationThreshold(
48 "rotation-max-header-size", cl::init(16), cl::Hidden,
49 cl::desc("The default maximum header size for automatic loop rotation"));
51 STATISTIC(NumRotated, "Number of loops rotated");
54 /// A simple loop rotation transformation.
56 const unsigned MaxHeaderSize;
58 const TargetTransformInfo *TTI;
62 const SimplifyQuery &SQ;
65 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
66 const TargetTransformInfo *TTI, AssumptionCache *AC,
67 DominatorTree *DT, ScalarEvolution *SE, const SimplifyQuery &SQ)
68 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
70 bool processLoop(Loop *L);
73 bool rotateLoop(Loop *L, bool SimplifiedLatch);
74 bool simplifyLoopLatch(Loop *L);
76 } // end anonymous namespace
78 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
79 /// old header into the preheader. If there were uses of the values produced by
80 /// these instruction that were outside of the loop, we have to insert PHI nodes
81 /// to merge the two values. Do this now.
82 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
83 BasicBlock *OrigPreheader,
84 ValueToValueMapTy &ValueMap,
85 SmallVectorImpl<PHINode*> *InsertedPHIs) {
86 // Remove PHI node entries that are no longer live.
87 BasicBlock::iterator I, E = OrigHeader->end();
88 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
89 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
91 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
93 SSAUpdater SSA(InsertedPHIs);
94 for (I = OrigHeader->begin(); I != E; ++I) {
95 Value *OrigHeaderVal = &*I;
97 // If there are no uses of the value (e.g. because it returns void), there
98 // is nothing to rewrite.
99 if (OrigHeaderVal->use_empty())
102 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
104 // The value now exits in two versions: the initial value in the preheader
105 // and the loop "next" value in the original header.
106 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
107 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
108 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
110 // Visit each use of the OrigHeader instruction.
111 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
112 UE = OrigHeaderVal->use_end();
114 // Grab the use before incrementing the iterator.
117 // Increment the iterator before removing the use from the list.
120 // SSAUpdater can't handle a non-PHI use in the same block as an
121 // earlier def. We can easily handle those cases manually.
122 Instruction *UserInst = cast<Instruction>(U.getUser());
123 if (!isa<PHINode>(UserInst)) {
124 BasicBlock *UserBB = UserInst->getParent();
126 // The original users in the OrigHeader are already using the
127 // original definitions.
128 if (UserBB == OrigHeader)
131 // Users in the OrigPreHeader need to use the value to which the
132 // original definitions are mapped.
133 if (UserBB == OrigPreheader) {
134 U = OrigPreHeaderVal;
139 // Anything else can be handled by SSAUpdater.
143 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
145 SmallVector<DbgValueInst *, 1> DbgValues;
146 llvm::findDbgValues(DbgValues, OrigHeaderVal);
147 for (auto &DbgValue : DbgValues) {
148 // The original users in the OrigHeader are already using the original
150 BasicBlock *UserBB = DbgValue->getParent();
151 if (UserBB == OrigHeader)
154 // Users in the OrigPreHeader need to use the value to which the
155 // original definitions are mapped and anything else can be handled by
156 // the SSAUpdater. To avoid adding PHINodes, check if the value is
157 // available in UserBB, if not substitute undef.
159 if (UserBB == OrigPreheader)
160 NewVal = OrigPreHeaderVal;
161 else if (SSA.HasValueForBlock(UserBB))
162 NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
164 NewVal = UndefValue::get(OrigHeaderVal->getType());
165 DbgValue->setOperand(0,
166 MetadataAsValue::get(OrigHeaderVal->getContext(),
167 ValueAsMetadata::get(NewVal)));
172 /// Propagate dbg.value intrinsics through the newly inserted Phis.
173 static void insertDebugValues(BasicBlock *OrigHeader,
174 SmallVectorImpl<PHINode*> &InsertedPHIs) {
175 ValueToValueMapTy DbgValueMap;
177 // Map existing PHI nodes to their dbg.values.
178 for (auto &I : *OrigHeader) {
179 if (auto DbgII = dyn_cast<DbgInfoIntrinsic>(&I)) {
180 if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
181 DbgValueMap.insert({Loc, DbgII});
185 // Then iterate through the new PHIs and look to see if they use one of the
186 // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
187 // propagate the info through the new PHI.
188 LLVMContext &C = OrigHeader->getContext();
189 for (auto PHI : InsertedPHIs) {
190 for (auto VI : PHI->operand_values()) {
191 auto V = DbgValueMap.find(VI);
192 if (V != DbgValueMap.end()) {
193 auto *DbgII = cast<DbgInfoIntrinsic>(V->second);
194 Instruction *NewDbgII = DbgII->clone();
195 auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
196 NewDbgII->setOperand(0, PhiMAV);
197 BasicBlock *Parent = PHI->getParent();
198 NewDbgII->insertBefore(Parent->getFirstNonPHIOrDbgOrLifetime());
204 /// Rotate loop LP. Return true if the loop is rotated.
206 /// \param SimplifiedLatch is true if the latch was just folded into the final
207 /// loop exit. In this case we may want to rotate even though the new latch is
208 /// now an exiting branch. This rotation would have happened had the latch not
209 /// been simplified. However, if SimplifiedLatch is false, then we avoid
210 /// rotating loops in which the latch exits to avoid excessive or endless
211 /// rotation. LoopRotate should be repeatable and converge to a canonical
212 /// form. This property is satisfied because simplifying the loop latch can only
213 /// happen once across multiple invocations of the LoopRotate pass.
214 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
215 // If the loop has only one block then there is not much to rotate.
216 if (L->getBlocks().size() == 1)
219 BasicBlock *OrigHeader = L->getHeader();
220 BasicBlock *OrigLatch = L->getLoopLatch();
222 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
223 if (!BI || BI->isUnconditional())
226 // If the loop header is not one of the loop exiting blocks then
227 // either this loop is already rotated or it is not
228 // suitable for loop rotation transformations.
229 if (!L->isLoopExiting(OrigHeader))
232 // If the loop latch already contains a branch that leaves the loop then the
233 // loop is already rotated.
237 // Rotate if either the loop latch does *not* exit the loop, or if the loop
238 // latch was just simplified.
239 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
242 // Check size of original header and reject loop if it is very big or we can't
243 // duplicate blocks inside it.
245 SmallPtrSet<const Value *, 32> EphValues;
246 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
249 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
250 if (Metrics.notDuplicatable) {
251 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
252 << " instructions: ";
256 if (Metrics.convergent) {
257 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
262 if (Metrics.NumInsts > MaxHeaderSize)
266 // Now, this loop is suitable for rotation.
267 BasicBlock *OrigPreheader = L->getLoopPreheader();
269 // If the loop could not be converted to canonical form, it must have an
270 // indirectbr in it, just give up.
274 // Anything ScalarEvolution may know about this loop or the PHI nodes
275 // in its header will soon be invalidated.
279 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
281 // Find new Loop header. NewHeader is a Header's one and only successor
282 // that is inside loop. Header's other successor is outside the
283 // loop. Otherwise loop is not suitable for rotation.
284 BasicBlock *Exit = BI->getSuccessor(0);
285 BasicBlock *NewHeader = BI->getSuccessor(1);
286 if (L->contains(Exit))
287 std::swap(Exit, NewHeader);
288 assert(NewHeader && "Unable to determine new loop header");
289 assert(L->contains(NewHeader) && !L->contains(Exit) &&
290 "Unable to determine loop header and exit blocks");
292 // This code assumes that the new header has exactly one predecessor.
293 // Remove any single-entry PHI nodes in it.
294 assert(NewHeader->getSinglePredecessor() &&
295 "New header doesn't have one pred!");
296 FoldSingleEntryPHINodes(NewHeader);
298 // Begin by walking OrigHeader and populating ValueMap with an entry for
300 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
301 ValueToValueMapTy ValueMap;
303 // For PHI nodes, the value available in OldPreHeader is just the
304 // incoming value from OldPreHeader.
305 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
306 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
308 // For the rest of the instructions, either hoist to the OrigPreheader if
309 // possible or create a clone in the OldPreHeader if not.
310 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
312 // Record all debug intrinsics preceding LoopEntryBranch to avoid duplication.
313 using DbgIntrinsicHash =
314 std::pair<std::pair<Value *, DILocalVariable *>, DIExpression *>;
315 auto makeHash = [](DbgInfoIntrinsic *D) -> DbgIntrinsicHash {
316 return {{D->getVariableLocation(), D->getVariable()}, D->getExpression()};
318 SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
319 for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
321 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&*I))
322 DbgIntrinsics.insert(makeHash(DII));
328 Instruction *Inst = &*I++;
330 // If the instruction's operands are invariant and it doesn't read or write
331 // memory, then it is safe to hoist. Doing this doesn't change the order of
332 // execution in the preheader, but does prevent the instruction from
333 // executing in each iteration of the loop. This means it is safe to hoist
334 // something that might trap, but isn't safe to hoist something that reads
335 // memory (without proving that the loop doesn't write).
336 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
337 !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
338 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
339 Inst->moveBefore(LoopEntryBranch);
343 // Otherwise, create a duplicate of the instruction.
344 Instruction *C = Inst->clone();
346 // Eagerly remap the operands of the instruction.
347 RemapInstruction(C, ValueMap,
348 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
350 // Avoid inserting the same intrinsic twice.
351 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(C))
352 if (DbgIntrinsics.count(makeHash(DII))) {
357 // With the operands remapped, see if the instruction constant folds or is
358 // otherwise simplifyable. This commonly occurs because the entry from PHI
359 // nodes allows icmps and other instructions to fold.
360 Value *V = SimplifyInstruction(C, SQ);
361 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
362 // If so, then delete the temporary instruction and stick the folded value
365 if (!C->mayHaveSideEffects()) {
373 // Otherwise, stick the new instruction into the new block!
374 C->setName(Inst->getName());
375 C->insertBefore(LoopEntryBranch);
377 if (auto *II = dyn_cast<IntrinsicInst>(C))
378 if (II->getIntrinsicID() == Intrinsic::assume)
379 AC->registerAssumption(II);
383 // Along with all the other instructions, we just cloned OrigHeader's
384 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
385 // successors by duplicating their incoming values for OrigHeader.
386 TerminatorInst *TI = OrigHeader->getTerminator();
387 for (BasicBlock *SuccBB : TI->successors())
388 for (BasicBlock::iterator BI = SuccBB->begin();
389 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
390 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
392 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
393 // OrigPreHeader's old terminator (the original branch into the loop), and
394 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
395 LoopEntryBranch->eraseFromParent();
398 SmallVector<PHINode*, 2> InsertedPHIs;
399 // If there were any uses of instructions in the duplicated block outside the
400 // loop, update them, inserting PHI nodes as required
401 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
404 // Attach dbg.value intrinsics to the new phis if that phi uses a value that
405 // previously had debug metadata attached. This keeps the debug info
406 // up-to-date in the loop body.
407 if (!InsertedPHIs.empty())
408 insertDebugValues(OrigHeader, InsertedPHIs);
410 // NewHeader is now the header of the loop.
411 L->moveToHeader(NewHeader);
412 assert(L->getHeader() == NewHeader && "Latch block is our new header");
414 // Inform DT about changes to the CFG.
416 // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
417 // the DT about the removed edge to the OrigHeader (that got removed).
418 SmallVector<DominatorTree::UpdateType, 3> Updates;
419 Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
420 Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
421 Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
422 DT->applyUpdates(Updates);
425 // At this point, we've finished our major CFG changes. As part of cloning
426 // the loop into the preheader we've simplified instructions and the
427 // duplicated conditional branch may now be branching on a constant. If it is
428 // branching on a constant and if that constant means that we enter the loop,
429 // then we fold away the cond branch to an uncond branch. This simplifies the
430 // loop in cases important for nested loops, and it also means we don't have
431 // to split as many edges.
432 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
433 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
434 if (!isa<ConstantInt>(PHBI->getCondition()) ||
435 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
437 // The conditional branch can't be folded, handle the general case.
438 // Split edges as necessary to preserve LoopSimplify form.
440 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
441 // thus is not a preheader anymore.
442 // Split the edge to form a real preheader.
443 BasicBlock *NewPH = SplitCriticalEdge(
444 OrigPreheader, NewHeader,
445 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
446 NewPH->setName(NewHeader->getName() + ".lr.ph");
448 // Preserve canonical loop form, which means that 'Exit' should have only
449 // one predecessor. Note that Exit could be an exit block for multiple
450 // nested loops, causing both of the edges to now be critical and need to
452 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
453 bool SplitLatchEdge = false;
454 for (BasicBlock *ExitPred : ExitPreds) {
455 // We only need to split loop exit edges.
456 Loop *PredLoop = LI->getLoopFor(ExitPred);
457 if (!PredLoop || PredLoop->contains(Exit))
459 if (isa<IndirectBrInst>(ExitPred->getTerminator()))
461 SplitLatchEdge |= L->getLoopLatch() == ExitPred;
462 BasicBlock *ExitSplit = SplitCriticalEdge(
464 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
465 ExitSplit->moveBefore(Exit);
467 assert(SplitLatchEdge &&
468 "Despite splitting all preds, failed to split latch exit?");
470 // We can fold the conditional branch in the preheader, this makes things
471 // simpler. The first step is to remove the extra edge to the Exit block.
472 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
473 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
474 NewBI->setDebugLoc(PHBI->getDebugLoc());
475 PHBI->eraseFromParent();
477 // With our CFG finalized, update DomTree if it is available.
478 if (DT) DT->deleteEdge(OrigPreheader, Exit);
481 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
482 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
484 // Now that the CFG and DomTree are in a consistent state again, try to merge
485 // the OrigHeader block into OrigLatch. This will succeed if they are
486 // connected by an unconditional branch. This is just a cleanup so the
487 // emitted code isn't too gross in this common case.
488 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
490 DEBUG(dbgs() << "LoopRotation: into "; L->dump());
496 /// Determine whether the instructions in this range may be safely and cheaply
497 /// speculated. This is not an important enough situation to develop complex
498 /// heuristics. We handle a single arithmetic instruction along with any type
500 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
501 BasicBlock::iterator End, Loop *L) {
502 bool seenIncrement = false;
503 bool MultiExitLoop = false;
505 if (!L->getExitingBlock())
506 MultiExitLoop = true;
508 for (BasicBlock::iterator I = Begin; I != End; ++I) {
510 if (!isSafeToSpeculativelyExecute(&*I))
513 if (isa<DbgInfoIntrinsic>(I))
516 switch (I->getOpcode()) {
519 case Instruction::GetElementPtr:
520 // GEPs are cheap if all indices are constant.
521 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
523 // fall-thru to increment case
525 case Instruction::Add:
526 case Instruction::Sub:
527 case Instruction::And:
528 case Instruction::Or:
529 case Instruction::Xor:
530 case Instruction::Shl:
531 case Instruction::LShr:
532 case Instruction::AShr: {
534 !isa<Constant>(I->getOperand(0))
536 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
540 // If increment operand is used outside of the loop, this speculation
541 // could cause extra live range interference.
543 for (User *UseI : IVOpnd->users()) {
544 auto *UserInst = cast<Instruction>(UseI);
545 if (!L->contains(UserInst))
552 seenIncrement = true;
555 case Instruction::Trunc:
556 case Instruction::ZExt:
557 case Instruction::SExt:
558 // ignore type conversions
565 /// Fold the loop tail into the loop exit by speculating the loop tail
566 /// instructions. Typically, this is a single post-increment. In the case of a
567 /// simple 2-block loop, hoisting the increment can be much better than
568 /// duplicating the entire loop header. In the case of loops with early exits,
569 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
570 /// canonical form so downstream passes can handle it.
572 /// I don't believe this invalidates SCEV.
573 bool LoopRotate::simplifyLoopLatch(Loop *L) {
574 BasicBlock *Latch = L->getLoopLatch();
575 if (!Latch || Latch->hasAddressTaken())
578 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
579 if (!Jmp || !Jmp->isUnconditional())
582 BasicBlock *LastExit = Latch->getSinglePredecessor();
583 if (!LastExit || !L->isLoopExiting(LastExit))
586 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
590 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
593 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
594 << LastExit->getName() << "\n");
596 // Hoist the instructions from Latch into LastExit.
597 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
598 Latch->begin(), Jmp->getIterator());
600 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
601 BasicBlock *Header = Jmp->getSuccessor(0);
602 assert(Header == L->getHeader() && "expected a backward branch");
604 // Remove Latch from the CFG so that LastExit becomes the new Latch.
605 BI->setSuccessor(FallThruPath, Header);
606 Latch->replaceSuccessorsPhiUsesWith(LastExit);
607 Jmp->eraseFromParent();
609 // Nuke the Latch block.
610 assert(Latch->empty() && "unable to evacuate Latch");
611 LI->removeBlock(Latch);
613 DT->eraseNode(Latch);
614 Latch->eraseFromParent();
618 /// Rotate \c L, and return true if any modification was made.
619 bool LoopRotate::processLoop(Loop *L) {
620 // Save the loop metadata.
621 MDNode *LoopMD = L->getLoopID();
623 // Simplify the loop latch before attempting to rotate the header
624 // upward. Rotation may not be needed if the loop tail can be folded into the
626 bool SimplifiedLatch = simplifyLoopLatch(L);
628 bool MadeChange = rotateLoop(L, SimplifiedLatch);
629 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
630 "Loop latch should be exiting after loop-rotate.");
632 // Restore the loop metadata.
633 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
634 if ((MadeChange || SimplifiedLatch) && LoopMD)
635 L->setLoopID(LoopMD);
637 return MadeChange || SimplifiedLatch;
640 LoopRotatePass::LoopRotatePass(bool EnableHeaderDuplication)
641 : EnableHeaderDuplication(EnableHeaderDuplication) {}
643 PreservedAnalyses LoopRotatePass::run(Loop &L, LoopAnalysisManager &AM,
644 LoopStandardAnalysisResults &AR,
646 int Threshold = EnableHeaderDuplication ? DefaultRotationThreshold : 0;
647 const DataLayout &DL = L.getHeader()->getModule()->getDataLayout();
648 const SimplifyQuery SQ = getBestSimplifyQuery(AR, DL);
649 LoopRotate LR(Threshold, &AR.LI, &AR.TTI, &AR.AC, &AR.DT, &AR.SE,
652 bool Changed = LR.processLoop(&L);
654 return PreservedAnalyses::all();
656 return getLoopPassPreservedAnalyses();
661 class LoopRotateLegacyPass : public LoopPass {
662 unsigned MaxHeaderSize;
665 static char ID; // Pass ID, replacement for typeid
666 LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
667 initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry());
668 if (SpecifiedMaxHeaderSize == -1)
669 MaxHeaderSize = DefaultRotationThreshold;
671 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
674 // LCSSA form makes instruction renaming easier.
675 void getAnalysisUsage(AnalysisUsage &AU) const override {
676 AU.addRequired<AssumptionCacheTracker>();
677 AU.addRequired<TargetTransformInfoWrapperPass>();
678 getLoopAnalysisUsage(AU);
681 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
684 Function &F = *L->getHeader()->getParent();
686 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
687 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
688 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
689 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
690 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
691 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
692 auto *SE = SEWP ? &SEWP->getSE() : nullptr;
693 const SimplifyQuery SQ = getBestSimplifyQuery(*this, F);
694 LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE, SQ);
695 return LR.processLoop(L);
700 char LoopRotateLegacyPass::ID = 0;
701 INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops",
703 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
704 INITIALIZE_PASS_DEPENDENCY(LoopPass)
705 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
706 INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false,
709 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
710 return new LoopRotateLegacyPass(MaxHeaderSize);