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/AssumptionCache.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<AssumptionCacheTracker>();
58 AU.addPreserved<DominatorTreeWrapperPass>();
59 AU.addRequired<LoopInfoWrapperPass>();
60 AU.addPreserved<LoopInfoWrapperPass>();
61 AU.addRequiredID(LoopSimplifyID);
62 AU.addPreservedID(LoopSimplifyID);
63 AU.addRequiredID(LCSSAID);
64 AU.addPreservedID(LCSSAID);
65 AU.addPreserved<ScalarEvolution>();
66 AU.addRequired<TargetTransformInfoWrapperPass>();
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;
82 char LoopRotate::ID = 0;
83 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
84 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
85 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
86 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
87 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
88 INITIALIZE_PASS_DEPENDENCY(LCSSA)
89 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
91 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
92 return new LoopRotate(MaxHeaderSize);
95 /// Rotate Loop L as many times as possible. Return true if
96 /// the loop is rotated at least once.
97 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
98 if (skipOptnoneFunction(L))
101 // Save the loop metadata.
102 MDNode *LoopMD = L->getLoopID();
104 Function &F = *L->getHeader()->getParent();
106 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
107 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
108 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
109 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
110 DT = DTWP ? &DTWP->getDomTree() : nullptr;
112 // Simplify the loop latch before attempting to rotate the header
113 // upward. Rotation may not be needed if the loop tail can be folded into the
115 bool SimplifiedLatch = simplifyLoopLatch(L);
117 // One loop can be rotated multiple times.
118 bool MadeChange = false;
119 while (rotateLoop(L, SimplifiedLatch)) {
121 SimplifiedLatch = false;
124 // Restore the loop metadata.
125 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
126 if ((MadeChange || SimplifiedLatch) && LoopMD)
127 L->setLoopID(LoopMD);
132 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
133 /// old header into the preheader. If there were uses of the values produced by
134 /// these instruction that were outside of the loop, we have to insert PHI nodes
135 /// to merge the two values. Do this now.
136 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
137 BasicBlock *OrigPreheader,
138 ValueToValueMapTy &ValueMap) {
139 // Remove PHI node entries that are no longer live.
140 BasicBlock::iterator I, E = OrigHeader->end();
141 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
142 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
144 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
147 for (I = OrigHeader->begin(); I != E; ++I) {
148 Value *OrigHeaderVal = I;
150 // If there are no uses of the value (e.g. because it returns void), there
151 // is nothing to rewrite.
152 if (OrigHeaderVal->use_empty())
155 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
157 // The value now exits in two versions: the initial value in the preheader
158 // and the loop "next" value in the original header.
159 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
160 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
161 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
163 // Visit each use of the OrigHeader instruction.
164 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
165 UE = OrigHeaderVal->use_end(); UI != UE; ) {
166 // Grab the use before incrementing the iterator.
169 // Increment the iterator before removing the use from the list.
172 // SSAUpdater can't handle a non-PHI use in the same block as an
173 // earlier def. We can easily handle those cases manually.
174 Instruction *UserInst = cast<Instruction>(U.getUser());
175 if (!isa<PHINode>(UserInst)) {
176 BasicBlock *UserBB = UserInst->getParent();
178 // The original users in the OrigHeader are already using the
179 // original definitions.
180 if (UserBB == OrigHeader)
183 // Users in the OrigPreHeader need to use the value to which the
184 // original definitions are mapped.
185 if (UserBB == OrigPreheader) {
186 U = OrigPreHeaderVal;
191 // Anything else can be handled by SSAUpdater.
197 /// Determine whether the instructions in this range may be safely and cheaply
198 /// speculated. This is not an important enough situation to develop complex
199 /// heuristics. We handle a single arithmetic instruction along with any type
201 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
202 BasicBlock::iterator End, Loop *L) {
203 bool seenIncrement = false;
204 bool MultiExitLoop = false;
206 if (!L->getExitingBlock())
207 MultiExitLoop = true;
209 for (BasicBlock::iterator I = Begin; I != End; ++I) {
211 if (!isSafeToSpeculativelyExecute(I))
214 if (isa<DbgInfoIntrinsic>(I))
217 switch (I->getOpcode()) {
220 case Instruction::GetElementPtr:
221 // GEPs are cheap if all indices are constant.
222 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
224 // fall-thru to increment case
225 case Instruction::Add:
226 case Instruction::Sub:
227 case Instruction::And:
228 case Instruction::Or:
229 case Instruction::Xor:
230 case Instruction::Shl:
231 case Instruction::LShr:
232 case Instruction::AShr: {
233 Value *IVOpnd = !isa<Constant>(I->getOperand(0))
235 : !isa<Constant>(I->getOperand(1))
241 // If increment operand is used outside of the loop, this speculation
242 // could cause extra live range interference.
244 for (User *UseI : IVOpnd->users()) {
245 auto *UserInst = cast<Instruction>(UseI);
246 if (!L->contains(UserInst))
253 seenIncrement = true;
256 case Instruction::Trunc:
257 case Instruction::ZExt:
258 case Instruction::SExt:
259 // ignore type conversions
266 /// Fold the loop tail into the loop exit by speculating the loop tail
267 /// instructions. Typically, this is a single post-increment. In the case of a
268 /// simple 2-block loop, hoisting the increment can be much better than
269 /// duplicating the entire loop header. In the case of loops with early exits,
270 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
271 /// canonical form so downstream passes can handle it.
273 /// I don't believe this invalidates SCEV.
274 bool LoopRotate::simplifyLoopLatch(Loop *L) {
275 BasicBlock *Latch = L->getLoopLatch();
276 if (!Latch || Latch->hasAddressTaken())
279 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
280 if (!Jmp || !Jmp->isUnconditional())
283 BasicBlock *LastExit = Latch->getSinglePredecessor();
284 if (!LastExit || !L->isLoopExiting(LastExit))
287 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
291 if (!shouldSpeculateInstrs(Latch->begin(), Jmp, L))
294 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
295 << LastExit->getName() << "\n");
297 // Hoist the instructions from Latch into LastExit.
298 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
300 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
301 BasicBlock *Header = Jmp->getSuccessor(0);
302 assert(Header == L->getHeader() && "expected a backward branch");
304 // Remove Latch from the CFG so that LastExit becomes the new Latch.
305 BI->setSuccessor(FallThruPath, Header);
306 Latch->replaceSuccessorsPhiUsesWith(LastExit);
307 Jmp->eraseFromParent();
309 // Nuke the Latch block.
310 assert(Latch->empty() && "unable to evacuate Latch");
311 LI->removeBlock(Latch);
313 DT->eraseNode(Latch);
314 Latch->eraseFromParent();
318 /// Rotate loop LP. Return true if the loop is rotated.
320 /// \param SimplifiedLatch is true if the latch was just folded into the final
321 /// loop exit. In this case we may want to rotate even though the new latch is
322 /// now an exiting branch. This rotation would have happened had the latch not
323 /// been simplified. However, if SimplifiedLatch is false, then we avoid
324 /// rotating loops in which the latch exits to avoid excessive or endless
325 /// rotation. LoopRotate should be repeatable and converge to a canonical
326 /// form. This property is satisfied because simplifying the loop latch can only
327 /// happen once across multiple invocations of the LoopRotate pass.
328 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
329 // If the loop has only one block then there is not much to rotate.
330 if (L->getBlocks().size() == 1)
333 BasicBlock *OrigHeader = L->getHeader();
334 BasicBlock *OrigLatch = L->getLoopLatch();
336 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
337 if (!BI || BI->isUnconditional())
340 // If the loop header is not one of the loop exiting blocks then
341 // either this loop is already rotated or it is not
342 // suitable for loop rotation transformations.
343 if (!L->isLoopExiting(OrigHeader))
346 // If the loop latch already contains a branch that leaves the loop then the
347 // loop is already rotated.
351 // Rotate if either the loop latch does *not* exit the loop, or if the loop
352 // latch was just simplified.
353 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
356 // Check size of original header and reject loop if it is very big or we can't
357 // duplicate blocks inside it.
359 SmallPtrSet<const Value *, 32> EphValues;
360 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
363 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
364 if (Metrics.notDuplicatable) {
365 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
366 << " instructions: "; L->dump());
369 if (Metrics.NumInsts > MaxHeaderSize)
373 // Now, this loop is suitable for rotation.
374 BasicBlock *OrigPreheader = L->getLoopPreheader();
376 // If the loop could not be converted to canonical form, it must have an
377 // indirectbr in it, just give up.
381 // Anything ScalarEvolution may know about this loop or the PHI nodes
382 // in its header will soon be invalidated.
383 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
386 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
388 // Find new Loop header. NewHeader is a Header's one and only successor
389 // that is inside loop. Header's other successor is outside the
390 // loop. Otherwise loop is not suitable for rotation.
391 BasicBlock *Exit = BI->getSuccessor(0);
392 BasicBlock *NewHeader = BI->getSuccessor(1);
393 if (L->contains(Exit))
394 std::swap(Exit, NewHeader);
395 assert(NewHeader && "Unable to determine new loop header");
396 assert(L->contains(NewHeader) && !L->contains(Exit) &&
397 "Unable to determine loop header and exit blocks");
399 // This code assumes that the new header has exactly one predecessor.
400 // Remove any single-entry PHI nodes in it.
401 assert(NewHeader->getSinglePredecessor() &&
402 "New header doesn't have one pred!");
403 FoldSingleEntryPHINodes(NewHeader);
405 // Begin by walking OrigHeader and populating ValueMap with an entry for
407 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
408 ValueToValueMapTy ValueMap;
410 // For PHI nodes, the value available in OldPreHeader is just the
411 // incoming value from OldPreHeader.
412 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
413 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
415 // For the rest of the instructions, either hoist to the OrigPreheader if
416 // possible or create a clone in the OldPreHeader if not.
417 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
419 Instruction *Inst = I++;
421 // If the instruction's operands are invariant and it doesn't read or write
422 // memory, then it is safe to hoist. Doing this doesn't change the order of
423 // execution in the preheader, but does prevent the instruction from
424 // executing in each iteration of the loop. This means it is safe to hoist
425 // something that might trap, but isn't safe to hoist something that reads
426 // memory (without proving that the loop doesn't write).
427 if (L->hasLoopInvariantOperands(Inst) &&
428 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
429 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
430 !isa<AllocaInst>(Inst)) {
431 Inst->moveBefore(LoopEntryBranch);
435 // Otherwise, create a duplicate of the instruction.
436 Instruction *C = Inst->clone();
438 // Eagerly remap the operands of the instruction.
439 RemapInstruction(C, ValueMap,
440 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
442 // With the operands remapped, see if the instruction constant folds or is
443 // otherwise simplifyable. This commonly occurs because the entry from PHI
444 // nodes allows icmps and other instructions to fold.
445 // FIXME: Provide DL, TLI, DT, AC to SimplifyInstruction.
446 Value *V = SimplifyInstruction(C);
447 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
448 // If so, then delete the temporary instruction and stick the folded value
453 // Otherwise, stick the new instruction into the new block!
454 C->setName(Inst->getName());
455 C->insertBefore(LoopEntryBranch);
460 // Along with all the other instructions, we just cloned OrigHeader's
461 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
462 // successors by duplicating their incoming values for OrigHeader.
463 TerminatorInst *TI = OrigHeader->getTerminator();
464 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
465 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
466 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
467 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
469 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
470 // OrigPreHeader's old terminator (the original branch into the loop), and
471 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
472 LoopEntryBranch->eraseFromParent();
474 // If there were any uses of instructions in the duplicated block outside the
475 // loop, update them, inserting PHI nodes as required
476 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
478 // NewHeader is now the header of the loop.
479 L->moveToHeader(NewHeader);
480 assert(L->getHeader() == NewHeader && "Latch block is our new header");
483 // At this point, we've finished our major CFG changes. As part of cloning
484 // the loop into the preheader we've simplified instructions and the
485 // duplicated conditional branch may now be branching on a constant. If it is
486 // branching on a constant and if that constant means that we enter the loop,
487 // then we fold away the cond branch to an uncond branch. This simplifies the
488 // loop in cases important for nested loops, and it also means we don't have
489 // to split as many edges.
490 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
491 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
492 if (!isa<ConstantInt>(PHBI->getCondition()) ||
493 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
495 // The conditional branch can't be folded, handle the general case.
496 // Update DominatorTree to reflect the CFG change we just made. Then split
497 // edges as necessary to preserve LoopSimplify form.
499 // Everything that was dominated by the old loop header is now dominated
500 // by the original loop preheader. Conceptually the header was merged
501 // into the preheader, even though we reuse the actual block as a new
503 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
504 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
505 OrigHeaderNode->end());
506 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
507 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
508 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
510 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
511 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
513 // Update OrigHeader to be dominated by the new header block.
514 DT->changeImmediateDominator(OrigHeader, OrigLatch);
517 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
518 // thus is not a preheader anymore.
519 // Split the edge to form a real preheader.
520 BasicBlock *NewPH = SplitCriticalEdge(
521 OrigPreheader, NewHeader,
522 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
523 NewPH->setName(NewHeader->getName() + ".lr.ph");
525 // Preserve canonical loop form, which means that 'Exit' should have only
526 // one predecessor. Note that Exit could be an exit block for multiple
527 // nested loops, causing both of the edges to now be critical and need to
529 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
530 bool SplitLatchEdge = false;
531 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
532 PE = ExitPreds.end();
534 // We only need to split loop exit edges.
535 Loop *PredLoop = LI->getLoopFor(*PI);
536 if (!PredLoop || PredLoop->contains(Exit))
538 SplitLatchEdge |= L->getLoopLatch() == *PI;
539 BasicBlock *ExitSplit = SplitCriticalEdge(
540 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
541 ExitSplit->moveBefore(Exit);
543 assert(SplitLatchEdge &&
544 "Despite splitting all preds, failed to split latch exit?");
546 // We can fold the conditional branch in the preheader, this makes things
547 // simpler. The first step is to remove the extra edge to the Exit block.
548 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
549 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
550 NewBI->setDebugLoc(PHBI->getDebugLoc());
551 PHBI->eraseFromParent();
553 // With our CFG finalized, update DomTree if it is available.
555 // Update OrigHeader to be dominated by the new header block.
556 DT->changeImmediateDominator(NewHeader, OrigPreheader);
557 DT->changeImmediateDominator(OrigHeader, OrigLatch);
559 // Brute force incremental dominator tree update. Call
560 // findNearestCommonDominator on all CFG predecessors of each child of the
562 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
563 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
564 OrigHeaderNode->end());
568 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
569 DomTreeNode *Node = HeaderChildren[I];
570 BasicBlock *BB = Node->getBlock();
572 pred_iterator PI = pred_begin(BB);
573 BasicBlock *NearestDom = *PI;
574 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
575 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
577 // Remember if this changes the DomTree.
578 if (Node->getIDom()->getBlock() != NearestDom) {
579 DT->changeImmediateDominator(BB, NearestDom);
584 // If the dominator changed, this may have an effect on other
585 // predecessors, continue until we reach a fixpoint.
590 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
591 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
593 // Now that the CFG and DomTree are in a consistent state again, try to merge
594 // the OrigHeader block into OrigLatch. This will succeed if they are
595 // connected by an unconditional branch. This is just a cleanup so the
596 // emitted code isn't too gross in this common case.
597 MergeBlockIntoPredecessor(OrigHeader, DT, LI);
599 DEBUG(dbgs() << "LoopRotation: into "; L->dump());