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/CodeMetrics.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolution.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Transforms/Utils/SSAUpdater.h"
30 #include "llvm/Transforms/Utils/ValueMapper.h"
33 #define DEBUG_TYPE "loop-rotate"
35 #define MAX_HEADER_SIZE 16
37 STATISTIC(NumRotated, "Number of loops rotated");
40 class LoopRotate : public LoopPass {
42 static char ID; // Pass ID, replacement for typeid
43 LoopRotate() : LoopPass(ID) {
44 initializeLoopRotatePass(*PassRegistry::getPassRegistry());
47 // LCSSA form makes instruction renaming easier.
48 void getAnalysisUsage(AnalysisUsage &AU) const override {
49 AU.addPreserved<DominatorTreeWrapperPass>();
50 AU.addRequired<LoopInfo>();
51 AU.addPreserved<LoopInfo>();
52 AU.addRequiredID(LoopSimplifyID);
53 AU.addPreservedID(LoopSimplifyID);
54 AU.addRequiredID(LCSSAID);
55 AU.addPreservedID(LCSSAID);
56 AU.addPreserved<ScalarEvolution>();
57 AU.addRequired<TargetTransformInfo>();
60 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
61 bool simplifyLoopLatch(Loop *L);
62 bool rotateLoop(Loop *L, bool SimplifiedLatch);
66 const TargetTransformInfo *TTI;
70 char LoopRotate::ID = 0;
71 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
72 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
73 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
74 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
75 INITIALIZE_PASS_DEPENDENCY(LCSSA)
76 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
78 Pass *llvm::createLoopRotatePass() { return new LoopRotate(); }
80 /// Rotate Loop L as many times as possible. Return true if
81 /// the loop is rotated at least once.
82 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
83 if (skipOptnoneFunction(L))
86 // Save the loop metadata.
87 MDNode *LoopMD = L->getLoopID();
89 LI = &getAnalysis<LoopInfo>();
90 TTI = &getAnalysis<TargetTransformInfo>();
92 // Simplify the loop latch before attempting to rotate the header
93 // upward. Rotation may not be needed if the loop tail can be folded into the
95 bool SimplifiedLatch = simplifyLoopLatch(L);
97 // One loop can be rotated multiple times.
98 bool MadeChange = false;
99 while (rotateLoop(L, SimplifiedLatch)) {
101 SimplifiedLatch = false;
104 // Restore the loop metadata.
105 // NB! We presume LoopRotation DOESN'T ADD its own metadata.
106 if ((MadeChange || SimplifiedLatch) && LoopMD)
107 L->setLoopID(LoopMD);
112 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
113 /// old header into the preheader. If there were uses of the values produced by
114 /// these instruction that were outside of the loop, we have to insert PHI nodes
115 /// to merge the two values. Do this now.
116 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
117 BasicBlock *OrigPreheader,
118 ValueToValueMapTy &ValueMap) {
119 // Remove PHI node entries that are no longer live.
120 BasicBlock::iterator I, E = OrigHeader->end();
121 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
122 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
124 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
127 for (I = OrigHeader->begin(); I != E; ++I) {
128 Value *OrigHeaderVal = I;
130 // If there are no uses of the value (e.g. because it returns void), there
131 // is nothing to rewrite.
132 if (OrigHeaderVal->use_empty())
135 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
137 // The value now exits in two versions: the initial value in the preheader
138 // and the loop "next" value in the original header.
139 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
140 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
141 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
143 // Visit each use of the OrigHeader instruction.
144 for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
145 UE = OrigHeaderVal->use_end(); UI != UE; ) {
146 // Grab the use before incrementing the iterator.
149 // Increment the iterator before removing the use from the list.
152 // SSAUpdater can't handle a non-PHI use in the same block as an
153 // earlier def. We can easily handle those cases manually.
154 Instruction *UserInst = cast<Instruction>(U.getUser());
155 if (!isa<PHINode>(UserInst)) {
156 BasicBlock *UserBB = UserInst->getParent();
158 // The original users in the OrigHeader are already using the
159 // original definitions.
160 if (UserBB == OrigHeader)
163 // Users in the OrigPreHeader need to use the value to which the
164 // original definitions are mapped.
165 if (UserBB == OrigPreheader) {
166 U = OrigPreHeaderVal;
171 // Anything else can be handled by SSAUpdater.
177 /// Determine whether the instructions in this range my be safely and cheaply
178 /// speculated. This is not an important enough situation to develop complex
179 /// heuristics. We handle a single arithmetic instruction along with any type
181 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
182 BasicBlock::iterator End) {
183 bool seenIncrement = false;
184 for (BasicBlock::iterator I = Begin; I != End; ++I) {
186 if (!isSafeToSpeculativelyExecute(I))
189 if (isa<DbgInfoIntrinsic>(I))
192 switch (I->getOpcode()) {
195 case Instruction::GetElementPtr:
196 // GEPs are cheap if all indices are constant.
197 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
199 // fall-thru to increment case
200 case Instruction::Add:
201 case Instruction::Sub:
202 case Instruction::And:
203 case Instruction::Or:
204 case Instruction::Xor:
205 case Instruction::Shl:
206 case Instruction::LShr:
207 case Instruction::AShr:
210 seenIncrement = true;
212 case Instruction::Trunc:
213 case Instruction::ZExt:
214 case Instruction::SExt:
215 // ignore type conversions
222 /// Fold the loop tail into the loop exit by speculating the loop tail
223 /// instructions. Typically, this is a single post-increment. In the case of a
224 /// simple 2-block loop, hoisting the increment can be much better than
225 /// duplicating the entire loop header. In the cast of loops with early exits,
226 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
227 /// canonical form so downstream passes can handle it.
229 /// I don't believe this invalidates SCEV.
230 bool LoopRotate::simplifyLoopLatch(Loop *L) {
231 BasicBlock *Latch = L->getLoopLatch();
232 if (!Latch || Latch->hasAddressTaken())
235 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
236 if (!Jmp || !Jmp->isUnconditional())
239 BasicBlock *LastExit = Latch->getSinglePredecessor();
240 if (!LastExit || !L->isLoopExiting(LastExit))
243 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
247 if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
250 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
251 << LastExit->getName() << "\n");
253 // Hoist the instructions from Latch into LastExit.
254 LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(), Jmp);
256 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
257 BasicBlock *Header = Jmp->getSuccessor(0);
258 assert(Header == L->getHeader() && "expected a backward branch");
260 // Remove Latch from the CFG so that LastExit becomes the new Latch.
261 BI->setSuccessor(FallThruPath, Header);
262 Latch->replaceSuccessorsPhiUsesWith(LastExit);
263 Jmp->eraseFromParent();
265 // Nuke the Latch block.
266 assert(Latch->empty() && "unable to evacuate Latch");
267 LI->removeBlock(Latch);
268 if (DominatorTreeWrapperPass *DTWP =
269 getAnalysisIfAvailable<DominatorTreeWrapperPass>())
270 DTWP->getDomTree().eraseNode(Latch);
271 Latch->eraseFromParent();
275 /// Rotate loop LP. Return true if the loop is rotated.
277 /// \param SimplifiedLatch is true if the latch was just folded into the final
278 /// loop exit. In this case we may want to rotate even though the new latch is
279 /// now an exiting branch. This rotation would have happened had the latch not
280 /// been simplified. However, if SimplifiedLatch is false, then we avoid
281 /// rotating loops in which the latch exits to avoid excessive or endless
282 /// rotation. LoopRotate should be repeatable and converge to a canonical
283 /// form. This property is satisfied because simplifying the loop latch can only
284 /// happen once across multiple invocations of the LoopRotate pass.
285 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
286 // If the loop has only one block then there is not much to rotate.
287 if (L->getBlocks().size() == 1)
290 BasicBlock *OrigHeader = L->getHeader();
291 BasicBlock *OrigLatch = L->getLoopLatch();
293 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
294 if (BI == 0 || BI->isUnconditional())
297 // If the loop header is not one of the loop exiting blocks then
298 // either this loop is already rotated or it is not
299 // suitable for loop rotation transformations.
300 if (!L->isLoopExiting(OrigHeader))
303 // If the loop latch already contains a branch that leaves the loop then the
304 // loop is already rotated.
308 // Rotate if either the loop latch does *not* exit the loop, or if the loop
309 // latch was just simplified.
310 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
313 // Check size of original header and reject loop if it is very big or we can't
314 // duplicate blocks inside it.
317 Metrics.analyzeBasicBlock(OrigHeader, *TTI);
318 if (Metrics.notDuplicatable) {
319 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
320 << " instructions: "; L->dump());
323 if (Metrics.NumInsts > MAX_HEADER_SIZE)
327 // Now, this loop is suitable for rotation.
328 BasicBlock *OrigPreheader = L->getLoopPreheader();
330 // If the loop could not be converted to canonical form, it must have an
331 // indirectbr in it, just give up.
332 if (OrigPreheader == 0)
335 // Anything ScalarEvolution may know about this loop or the PHI nodes
336 // in its header will soon be invalidated.
337 if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
340 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
342 // Find new Loop header. NewHeader is a Header's one and only successor
343 // that is inside loop. Header's other successor is outside the
344 // loop. Otherwise loop is not suitable for rotation.
345 BasicBlock *Exit = BI->getSuccessor(0);
346 BasicBlock *NewHeader = BI->getSuccessor(1);
347 if (L->contains(Exit))
348 std::swap(Exit, NewHeader);
349 assert(NewHeader && "Unable to determine new loop header");
350 assert(L->contains(NewHeader) && !L->contains(Exit) &&
351 "Unable to determine loop header and exit blocks");
353 // This code assumes that the new header has exactly one predecessor.
354 // Remove any single-entry PHI nodes in it.
355 assert(NewHeader->getSinglePredecessor() &&
356 "New header doesn't have one pred!");
357 FoldSingleEntryPHINodes(NewHeader);
359 // Begin by walking OrigHeader and populating ValueMap with an entry for
361 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
362 ValueToValueMapTy ValueMap;
364 // For PHI nodes, the value available in OldPreHeader is just the
365 // incoming value from OldPreHeader.
366 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
367 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
369 // For the rest of the instructions, either hoist to the OrigPreheader if
370 // possible or create a clone in the OldPreHeader if not.
371 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
373 Instruction *Inst = I++;
375 // If the instruction's operands are invariant and it doesn't read or write
376 // memory, then it is safe to hoist. Doing this doesn't change the order of
377 // execution in the preheader, but does prevent the instruction from
378 // executing in each iteration of the loop. This means it is safe to hoist
379 // something that might trap, but isn't safe to hoist something that reads
380 // memory (without proving that the loop doesn't write).
381 if (L->hasLoopInvariantOperands(Inst) &&
382 !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
383 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
384 !isa<AllocaInst>(Inst)) {
385 Inst->moveBefore(LoopEntryBranch);
389 // Otherwise, create a duplicate of the instruction.
390 Instruction *C = Inst->clone();
392 // Eagerly remap the operands of the instruction.
393 RemapInstruction(C, ValueMap,
394 RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
396 // With the operands remapped, see if the instruction constant folds or is
397 // otherwise simplifyable. This commonly occurs because the entry from PHI
398 // nodes allows icmps and other instructions to fold.
399 Value *V = SimplifyInstruction(C);
400 if (V && LI->replacementPreservesLCSSAForm(C, V)) {
401 // If so, then delete the temporary instruction and stick the folded value
406 // Otherwise, stick the new instruction into the new block!
407 C->setName(Inst->getName());
408 C->insertBefore(LoopEntryBranch);
413 // Along with all the other instructions, we just cloned OrigHeader's
414 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
415 // successors by duplicating their incoming values for OrigHeader.
416 TerminatorInst *TI = OrigHeader->getTerminator();
417 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
418 for (BasicBlock::iterator BI = TI->getSuccessor(i)->begin();
419 PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
420 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
422 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
423 // OrigPreHeader's old terminator (the original branch into the loop), and
424 // remove the corresponding incoming values from the PHI nodes in OrigHeader.
425 LoopEntryBranch->eraseFromParent();
427 // If there were any uses of instructions in the duplicated block outside the
428 // loop, update them, inserting PHI nodes as required
429 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
431 // NewHeader is now the header of the loop.
432 L->moveToHeader(NewHeader);
433 assert(L->getHeader() == NewHeader && "Latch block is our new header");
436 // At this point, we've finished our major CFG changes. As part of cloning
437 // the loop into the preheader we've simplified instructions and the
438 // duplicated conditional branch may now be branching on a constant. If it is
439 // branching on a constant and if that constant means that we enter the loop,
440 // then we fold away the cond branch to an uncond branch. This simplifies the
441 // loop in cases important for nested loops, and it also means we don't have
442 // to split as many edges.
443 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
444 assert(PHBI->isConditional() && "Should be clone of BI condbr!");
445 if (!isa<ConstantInt>(PHBI->getCondition()) ||
446 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
448 // The conditional branch can't be folded, handle the general case.
449 // Update DominatorTree to reflect the CFG change we just made. Then split
450 // edges as necessary to preserve LoopSimplify form.
451 if (DominatorTreeWrapperPass *DTWP =
452 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
453 DominatorTree &DT = DTWP->getDomTree();
454 // Everything that was dominated by the old loop header is now dominated
455 // by the original loop preheader. Conceptually the header was merged
456 // into the preheader, even though we reuse the actual block as a new
458 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
459 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
460 OrigHeaderNode->end());
461 DomTreeNode *OrigPreheaderNode = DT.getNode(OrigPreheader);
462 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
463 DT.changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
465 assert(DT.getNode(Exit)->getIDom() == OrigPreheaderNode);
466 assert(DT.getNode(NewHeader)->getIDom() == OrigPreheaderNode);
468 // Update OrigHeader to be dominated by the new header block.
469 DT.changeImmediateDominator(OrigHeader, OrigLatch);
472 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
473 // thus is not a preheader anymore.
474 // Split the edge to form a real preheader.
475 BasicBlock *NewPH = SplitCriticalEdge(OrigPreheader, NewHeader, this);
476 NewPH->setName(NewHeader->getName() + ".lr.ph");
478 // Preserve canonical loop form, which means that 'Exit' should have only
479 // one predecessor. Note that Exit could be an exit block for multiple
480 // nested loops, causing both of the edges to now be critical and need to
482 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
483 bool SplitLatchEdge = false;
484 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
485 PE = ExitPreds.end();
487 // We only need to split loop exit edges.
488 Loop *PredLoop = LI->getLoopFor(*PI);
489 if (!PredLoop || PredLoop->contains(Exit))
491 SplitLatchEdge |= L->getLoopLatch() == *PI;
492 BasicBlock *ExitSplit = SplitCriticalEdge(*PI, Exit, this);
493 ExitSplit->moveBefore(Exit);
495 assert(SplitLatchEdge &&
496 "Despite splitting all preds, failed to split latch exit?");
498 // We can fold the conditional branch in the preheader, this makes things
499 // simpler. The first step is to remove the extra edge to the Exit block.
500 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
501 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
502 NewBI->setDebugLoc(PHBI->getDebugLoc());
503 PHBI->eraseFromParent();
505 // With our CFG finalized, update DomTree if it is available.
506 if (DominatorTreeWrapperPass *DTWP =
507 getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
508 DominatorTree &DT = DTWP->getDomTree();
509 // Update OrigHeader to be dominated by the new header block.
510 DT.changeImmediateDominator(NewHeader, OrigPreheader);
511 DT.changeImmediateDominator(OrigHeader, OrigLatch);
513 // Brute force incremental dominator tree update. Call
514 // findNearestCommonDominator on all CFG predecessors of each child of the
516 DomTreeNode *OrigHeaderNode = DT.getNode(OrigHeader);
517 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
518 OrigHeaderNode->end());
522 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
523 DomTreeNode *Node = HeaderChildren[I];
524 BasicBlock *BB = Node->getBlock();
526 pred_iterator PI = pred_begin(BB);
527 BasicBlock *NearestDom = *PI;
528 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
529 NearestDom = DT.findNearestCommonDominator(NearestDom, *PI);
531 // Remember if this changes the DomTree.
532 if (Node->getIDom()->getBlock() != NearestDom) {
533 DT.changeImmediateDominator(BB, NearestDom);
538 // If the dominator changed, this may have an effect on other
539 // predecessors, continue until we reach a fixpoint.
544 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
545 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
547 // Now that the CFG and DomTree are in a consistent state again, try to merge
548 // the OrigHeader block into OrigLatch. This will succeed if they are
549 // connected by an unconditional branch. This is just a cleanup so the
550 // emitted code isn't too gross in this common case.
551 MergeBlockIntoPredecessor(OrigHeader, this);
553 DEBUG(dbgs() << "LoopRotation: into "; L->dump());