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/AliasAnalysis.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/CodeMetrics.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Transforms/Utils/SSAUpdater.h"
35 #include "llvm/Transforms/Utils/ValueMapper.h"
38 #define DEBUG_TYPE "loop-rotate"
40 static cl::opt<unsigned>
41 DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
42 cl::desc("The default maximum header size for automatic loop rotation"));
44 STATISTIC(NumRotated, "Number of loops rotated");
47 class LoopRotate : public LoopPass {
49 static char ID; // Pass ID, replacement for typeid
50 LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
51 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
52 if (SpecifiedMaxHeaderSize == -1)
53 MaxHeaderSize = DefaultRotationThreshold;
55 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
58 // LCSSA form makes instruction renaming easier.
59 void getAnalysisUsage(AnalysisUsage &AU) const override {
60 AU.addPreserved<AliasAnalysis>();
61 AU.addRequired<AssumptionCacheTracker>();
62 AU.addPreserved<DominatorTreeWrapperPass>();
63 AU.addRequired<LoopInfoWrapperPass>();
64 AU.addPreserved<LoopInfoWrapperPass>();
65 AU.addRequiredID(LoopSimplifyID);
66 AU.addPreservedID(LoopSimplifyID);
67 AU.addRequiredID(LCSSAID);
68 AU.addPreservedID(LCSSAID);
69 AU.addPreserved<ScalarEvolution>();
70 AU.addRequired<TargetTransformInfoWrapperPass>();
73 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
74 bool simplifyLoopLatch(Loop *L);
75 bool rotateLoop(Loop *L, bool SimplifiedLatch);
78 unsigned MaxHeaderSize;
80 const TargetTransformInfo *TTI;
86 char LoopRotate::ID = 0;
87 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
88 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
89 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
90 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
91 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
92 INITIALIZE_PASS_DEPENDENCY(LCSSA)
93 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
95 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
96 return new LoopRotate(MaxHeaderSize);
99 /// Rotate Loop L as many times as possible. Return true if
100 /// the loop is rotated at least once.
101 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
102 if (skipOptnoneFunction(L))
105 // Save the loop metadata.
106 MDNode *LoopMD = L->getLoopID();
108 Function &F = *L->getHeader()->getParent();
110 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
111 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
112 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
113 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
114 DT = DTWP ? &DTWP->getDomTree() : nullptr;
116 // Simplify the loop latch before attempting to rotate the header
117 // upward. Rotation may not be needed if the loop tail can be folded into the
119 bool SimplifiedLatch = simplifyLoopLatch(L);
121 // One loop can be rotated multiple times.
122 bool MadeChange = false;
123 while (rotateLoop(L, SimplifiedLatch)) {
125 SimplifiedLatch = false;
128 // Restore the loop metadata.
129 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
130 if ((MadeChange || SimplifiedLatch) && LoopMD)
131 L->setLoopID(LoopMD);
136 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
137 /// old header into the preheader. If there were uses of the values produced by
138 /// these instruction that were outside of the loop, we have to insert PHI nodes
139 /// to merge the two values. Do this now.
140 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
141 BasicBlock *OrigPreheader,
142 ValueToValueMapTy &ValueMap) {
143 // Remove PHI node entries that are no longer live.
144 BasicBlock::iterator I, E = OrigHeader->end();
145 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
146 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
148 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
151 for (I = OrigHeader->begin(); I != E; ++I) {
152 Value *OrigHeaderVal = I;
154 // If there are no uses of the value (e.g. because it returns void), there
155 // is nothing to rewrite.
156 if (OrigHeaderVal->use_empty())
159 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
161 // The value now exits in two versions: the initial value in the preheader
162 // and the loop "next" value in the original header.
163 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
164 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
165 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
167 // Visit each use of the OrigHeader instruction.
168 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
169 UE = OrigHeaderVal->use_end(); UI != UE; ) {
170 // Grab the use before incrementing the iterator.
173 // Increment the iterator before removing the use from the list.
176 // SSAUpdater can't handle a non-PHI use in the same block as an
177 // earlier def. We can easily handle those cases manually.
178 Instruction *UserInst = cast<Instruction>(U.getUser());
179 if (!isa<PHINode>(UserInst)) {
180 BasicBlock *UserBB = UserInst->getParent();
182 // The original users in the OrigHeader are already using the
183 // original definitions.
184 if (UserBB == OrigHeader)
187 // Users in the OrigPreHeader need to use the value to which the
188 // original definitions are mapped.
189 if (UserBB == OrigPreheader) {
190 U = OrigPreHeaderVal;
195 // Anything else can be handled by SSAUpdater.
201 /// Determine whether the instructions in this range may be safely and cheaply
202 /// speculated. This is not an important enough situation to develop complex
203 /// heuristics. We handle a single arithmetic instruction along with any type
205 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
206 BasicBlock::iterator End, Loop *L) {
207 bool seenIncrement = false;
208 bool MultiExitLoop = false;
210 if (!L->getExitingBlock())
211 MultiExitLoop = true;
213 for (BasicBlock::iterator I = Begin; I != End; ++I) {
215 if (!isSafeToSpeculativelyExecute(I))
218 if (isa<DbgInfoIntrinsic>(I))
221 switch (I->getOpcode()) {
224 case Instruction::GetElementPtr:
225 // GEPs are cheap if all indices are constant.
226 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
228 // fall-thru to increment case
229 case Instruction::Add:
230 case Instruction::Sub:
231 case Instruction::And:
232 case Instruction::Or:
233 case Instruction::Xor:
234 case Instruction::Shl:
235 case Instruction::LShr:
236 case Instruction::AShr: {
237 Value *IVOpnd = !isa<Constant>(I->getOperand(0))
239 : !isa<Constant>(I->getOperand(1))
245 // If increment operand is used outside of the loop, this speculation
246 // could cause extra live range interference.
248 for (User *UseI : IVOpnd->users()) {
249 auto *UserInst = cast<Instruction>(UseI);
250 if (!L->contains(UserInst))
257 seenIncrement = true;
260 case Instruction::Trunc:
261 case Instruction::ZExt:
262 case Instruction::SExt:
263 // ignore type conversions
270 /// Fold the loop tail into the loop exit by speculating the loop tail
271 /// instructions. Typically, this is a single post-increment. In the case of a
272 /// simple 2-block loop, hoisting the increment can be much better than
273 /// duplicating the entire loop header. In the case of loops with early exits,
274 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
275 /// canonical form so downstream passes can handle it.
277 /// I don't believe this invalidates SCEV.
278 bool LoopRotate::simplifyLoopLatch(Loop *L) {
279 BasicBlock *Latch = L->getLoopLatch();
280 if (!Latch || Latch->hasAddressTaken())
283 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
284 if (!Jmp || !Jmp->isUnconditional())
287 BasicBlock *LastExit = Latch->getSinglePredecessor();
288 if (!LastExit || !L->isLoopExiting(LastExit))
291 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
295 if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
298 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
299 << LastExit->getName() << "\n");
301 // Hoist the instructions from Latch into LastExit.
302 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
304 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
305 BasicBlock *Header = Jmp->getSuccessor(0);
306 assert(Header == L->getHeader() && "expected a backward branch");
308 // Remove Latch from the CFG so that LastExit becomes the new Latch.
309 BI->setSuccessor(FallThruPath, Header);
310 Latch->replaceSuccessorsPhiUsesWith(LastExit);
311 Jmp->eraseFromParent();
313 // Nuke the Latch block.
314 assert(Latch->empty() && "unable to evacuate Latch");
315 LI->removeBlock(Latch);
317 DT->eraseNode(Latch);
318 Latch->eraseFromParent();
322 /// Rotate loop LP. Return true if the loop is rotated.
324 /// \param SimplifiedLatch is true if the latch was just folded into the final
325 /// loop exit. In this case we may want to rotate even though the new latch is
326 /// now an exiting branch. This rotation would have happened had the latch not
327 /// been simplified. However, if SimplifiedLatch is false, then we avoid
328 /// rotating loops in which the latch exits to avoid excessive or endless
329 /// rotation. LoopRotate should be repeatable and converge to a canonical
330 /// form. This property is satisfied because simplifying the loop latch can only
331 /// happen once across multiple invocations of the LoopRotate pass.
332 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
333 // If the loop has only one block then there is not much to rotate.
334 if (L->getBlocks().size() == 1)
337 BasicBlock *OrigHeader = L->getHeader();
338 BasicBlock *OrigLatch = L->getLoopLatch();
340 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
341 if (!BI || BI->isUnconditional())
344 // If the loop header is not one of the loop exiting blocks then
345 // either this loop is already rotated or it is not
346 // suitable for loop rotation transformations.
347 if (!L->isLoopExiting(OrigHeader))
350 // If the loop latch already contains a branch that leaves the loop then the
351 // loop is already rotated.
355 // Rotate if either the loop latch does *not* exit the loop, or if the loop
356 // latch was just simplified.
357 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
360 // Check size of original header and reject loop if it is very big or we can't
361 // duplicate blocks inside it.
363 SmallPtrSet<const Value *, 32> EphValues;
364 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
367 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
368 if (Metrics.notDuplicatable) {
369 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
370 << " instructions: "; L->dump());
373 if (Metrics.NumInsts > MaxHeaderSize)
377 // Now, this loop is suitable for rotation.
378 BasicBlock *OrigPreheader = L->getLoopPreheader();
380 // If the loop could not be converted to canonical form, it must have an
381 // indirectbr in it, just give up.
385 // Anything ScalarEvolution may know about this loop or the PHI nodes
386 // in its header will soon be invalidated.
387 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
390 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
392 // Find new Loop header. NewHeader is a Header's one and only successor
393 // that is inside loop. Header's other successor is outside the
394 // loop. Otherwise loop is not suitable for rotation.
395 BasicBlock *Exit = BI->getSuccessor(0);
396 BasicBlock *NewHeader = BI->getSuccessor(1);
397 if (L->contains(Exit))
398 std::swap(Exit, NewHeader);
399 assert(NewHeader && "Unable to determine new loop header");
400 assert(L->contains(NewHeader) && !L->contains(Exit) &&
401 "Unable to determine loop header and exit blocks");
403 // This code assumes that the new header has exactly one predecessor.
404 // Remove any single-entry PHI nodes in it.
405 assert(NewHeader->getSinglePredecessor() &&
406 "New header doesn't have one pred!");
407 FoldSingleEntryPHINodes(NewHeader);
409 // Begin by walking OrigHeader and populating ValueMap with an entry for
411 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
412 ValueToValueMapTy ValueMap;
414 // For PHI nodes, the value available in OldPreHeader is just the
415 // incoming value from OldPreHeader.
416 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
417 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
419 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
421 // For the rest of the instructions, either hoist to the OrigPreheader if
422 // possible or create a clone in the OldPreHeader if not.
423 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
425 Instruction *Inst = I++;
427 // If the instruction's operands are invariant and it doesn't read or write
428 // memory, then it is safe to hoist. Doing this doesn't change the order of
429 // execution in the preheader, but does prevent the instruction from
430 // executing in each iteration of the loop. This means it is safe to hoist
431 // something that might trap, but isn't safe to hoist something that reads
432 // memory (without proving that the loop doesn't write).
433 if (L->hasLoopInvariantOperands(Inst) &&
434 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
435 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
436 !isa<AllocaInst>(Inst)) {
437 Inst->moveBefore(LoopEntryBranch);
441 // Otherwise, create a duplicate of the instruction.
442 Instruction *C = Inst->clone();
444 // Eagerly remap the operands of the instruction.
445 RemapInstruction(C, ValueMap,
446 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
448 // With the operands remapped, see if the instruction constant folds or is
449 // otherwise simplifyable. This commonly occurs because the entry from PHI
450 // nodes allows icmps and other instructions to fold.
451 // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
452 Value *V = SimplifyInstruction(C, DL);
453 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
454 // If so, then delete the temporary instruction and stick the folded value
459 // Otherwise, stick the new instruction into the new block!
460 C->setName(Inst->getName());
461 C->insertBefore(LoopEntryBranch);
466 // Along with all the other instructions, we just cloned OrigHeader's
467 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
468 // successors by duplicating their incoming values for OrigHeader.
469 TerminatorInst *TI = OrigHeader->getTerminator();
470 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
471 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
472 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
473 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
475 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
476 // OrigPreHeader's old terminator (the original branch into the loop), and
477 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
478 LoopEntryBranch->eraseFromParent();
480 // If there were any uses of instructions in the duplicated block outside the
481 // loop, update them, inserting PHI nodes as required
482 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
484 // NewHeader is now the header of the loop.
485 L->moveToHeader(NewHeader);
486 assert(L->getHeader() == NewHeader && "Latch block is our new header");
489 // At this point, we've finished our major CFG changes. As part of cloning
490 // the loop into the preheader we've simplified instructions and the
491 // duplicated conditional branch may now be branching on a constant. If it is
492 // branching on a constant and if that constant means that we enter the loop,
493 // then we fold away the cond branch to an uncond branch. This simplifies the
494 // loop in cases important for nested loops, and it also means we don't have
495 // to split as many edges.
496 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
497 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
498 if (!isa<ConstantInt>(PHBI->getCondition()) ||
499 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
501 // The conditional branch can't be folded, handle the general case.
502 // Update DominatorTree to reflect the CFG change we just made. Then split
503 // edges as necessary to preserve LoopSimplify form.
505 // Everything that was dominated by the old loop header is now dominated
506 // by the original loop preheader. Conceptually the header was merged
507 // into the preheader, even though we reuse the actual block as a new
509 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
510 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
511 OrigHeaderNode->end());
512 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
513 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
514 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
516 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
517 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
519 // Update OrigHeader to be dominated by the new header block.
520 DT->changeImmediateDominator(OrigHeader, OrigLatch);
523 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
524 // thus is not a preheader anymore.
525 // Split the edge to form a real preheader.
526 BasicBlock *NewPH = SplitCriticalEdge(
527 OrigPreheader, NewHeader,
528 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
529 NewPH->setName(NewHeader->getName() + ".lr.ph");
531 // Preserve canonical loop form, which means that 'Exit' should have only
532 // one predecessor. Note that Exit could be an exit block for multiple
533 // nested loops, causing both of the edges to now be critical and need to
535 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
536 bool SplitLatchEdge = false;
537 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
538 PE = ExitPreds.end();
540 // We only need to split loop exit edges.
541 Loop *PredLoop = LI->getLoopFor(*PI);
542 if (!PredLoop || PredLoop->contains(Exit))
544 if (isa<IndirectBrInst>((*PI)->getTerminator()))
546 SplitLatchEdge |= L->getLoopLatch() == *PI;
547 BasicBlock *ExitSplit = SplitCriticalEdge(
548 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
549 ExitSplit->moveBefore(Exit);
551 assert(SplitLatchEdge &&
552 "Despite splitting all preds, failed to split latch exit?");
554 // We can fold the conditional branch in the preheader, this makes things
555 // simpler. The first step is to remove the extra edge to the Exit block.
556 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
557 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
558 NewBI->setDebugLoc(PHBI->getDebugLoc());
559 PHBI->eraseFromParent();
561 // With our CFG finalized, update DomTree if it is available.
563 // Update OrigHeader to be dominated by the new header block.
564 DT->changeImmediateDominator(NewHeader, OrigPreheader);
565 DT->changeImmediateDominator(OrigHeader, OrigLatch);
567 // Brute force incremental dominator tree update. Call
568 // findNearestCommonDominator on all CFG predecessors of each child of the
570 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
571 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
572 OrigHeaderNode->end());
576 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
577 DomTreeNode *Node = HeaderChildren[I];
578 BasicBlock *BB = Node->getBlock();
580 pred_iterator PI = pred_begin(BB);
581 BasicBlock *NearestDom = *PI;
582 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
583 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
585 // Remember if this changes the DomTree.
586 if (Node->getIDom()->getBlock() != NearestDom) {
587 DT->changeImmediateDominator(BB, NearestDom);
592 // If the dominator changed, this may have an effect on other
593 // predecessors, continue until we reach a fixpoint.
598 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
599 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
601 // Now that the CFG and DomTree are in a consistent state again, try to merge
602 // the OrigHeader block into OrigLatch. This will succeed if they are
603 // connected by an unconditional branch. This is just a cleanup so the
604 // emitted code isn't too gross in this common case.
605 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
607 DEBUG(dbgs() << "LoopRotation: into "; L->dump());