1 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements Loop Rotation Pass. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar/LoopRotation.h" 15 #include "llvm/ADT/Statistic.h" 16 #include "llvm/Analysis/AliasAnalysis.h" 17 #include "llvm/Analysis/BasicAliasAnalysis.h" 18 #include "llvm/Analysis/AssumptionCache.h" 19 #include "llvm/Analysis/CodeMetrics.h" 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/Analysis/GlobalsModRef.h" 22 #include "llvm/Analysis/LoopPass.h" 23 #include "llvm/Analysis/LoopPassManager.h" 24 #include "llvm/Analysis/ScalarEvolution.h" 25 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 26 #include "llvm/Analysis/TargetTransformInfo.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/CFG.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/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" 42 using namespace llvm; 43 44 #define DEBUG_TYPE "loop-rotate" 45 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")); 49 50 STATISTIC(NumRotated, "Number of loops rotated"); 51 52 /// A simple loop rotation transformation. 53 class LoopRotate { 54 const unsigned MaxHeaderSize; 55 LoopInfo *LI; 56 const TargetTransformInfo *TTI; 57 AssumptionCache *AC; 58 DominatorTree *DT; 59 ScalarEvolution *SE; 60 61 public: 62 LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI, 63 const TargetTransformInfo *TTI, AssumptionCache *AC, 64 DominatorTree *DT, ScalarEvolution *SE) 65 : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE) { 66 } 67 bool processLoop(Loop *L); 68 69 private: 70 bool rotateLoop(Loop *L, bool SimplifiedLatch); 71 bool simplifyLoopLatch(Loop *L); 72 }; 73 74 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the 75 /// old header into the preheader. If there were uses of the values produced by 76 /// these instruction that were outside of the loop, we have to insert PHI nodes 77 /// to merge the two values. Do this now. 78 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, 79 BasicBlock *OrigPreheader, 80 ValueToValueMapTy &ValueMap) { 81 // Remove PHI node entries that are no longer live. 82 BasicBlock::iterator I, E = OrigHeader->end(); 83 for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I) 84 PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader)); 85 86 // Now fix up users of the instructions in OrigHeader, inserting PHI nodes 87 // as necessary. 88 SSAUpdater SSA; 89 for (I = OrigHeader->begin(); I != E; ++I) { 90 Value *OrigHeaderVal = &*I; 91 92 // If there are no uses of the value (e.g. because it returns void), there 93 // is nothing to rewrite. 94 if (OrigHeaderVal->use_empty()) 95 continue; 96 97 Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal); 98 99 // The value now exits in two versions: the initial value in the preheader 100 // and the loop "next" value in the original header. 101 SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName()); 102 SSA.AddAvailableValue(OrigHeader, OrigHeaderVal); 103 SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal); 104 105 // Visit each use of the OrigHeader instruction. 106 for (Value::use_iterator UI = OrigHeaderVal->use_begin(), 107 UE = OrigHeaderVal->use_end(); 108 UI != UE;) { 109 // Grab the use before incrementing the iterator. 110 Use &U = *UI; 111 112 // Increment the iterator before removing the use from the list. 113 ++UI; 114 115 // SSAUpdater can't handle a non-PHI use in the same block as an 116 // earlier def. We can easily handle those cases manually. 117 Instruction *UserInst = cast<Instruction>(U.getUser()); 118 if (!isa<PHINode>(UserInst)) { 119 BasicBlock *UserBB = UserInst->getParent(); 120 121 // The original users in the OrigHeader are already using the 122 // original definitions. 123 if (UserBB == OrigHeader) 124 continue; 125 126 // Users in the OrigPreHeader need to use the value to which the 127 // original definitions are mapped. 128 if (UserBB == OrigPreheader) { 129 U = OrigPreHeaderVal; 130 continue; 131 } 132 } 133 134 // Anything else can be handled by SSAUpdater. 135 SSA.RewriteUse(U); 136 } 137 138 // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug 139 // intrinsics. 140 LLVMContext &C = OrigHeader->getContext(); 141 if (auto *VAM = ValueAsMetadata::getIfExists(OrigHeaderVal)) { 142 if (auto *MAV = MetadataAsValue::getIfExists(C, VAM)) { 143 for (auto UI = MAV->use_begin(), E = MAV->use_end(); UI != E;) { 144 // Grab the use before incrementing the iterator. Otherwise, altering 145 // the Use will invalidate the iterator. 146 Use &U = *UI++; 147 DbgInfoIntrinsic *UserInst = dyn_cast<DbgInfoIntrinsic>(U.getUser()); 148 if (!UserInst) 149 continue; 150 151 // The original users in the OrigHeader are already using the original 152 // definitions. 153 BasicBlock *UserBB = UserInst->getParent(); 154 if (UserBB == OrigHeader) 155 continue; 156 157 // Users in the OrigPreHeader need to use the value to which the 158 // original definitions are mapped and anything else can be handled by 159 // the SSAUpdater. To avoid adding PHINodes, check if the value is 160 // available in UserBB, if not substitute undef. 161 Value *NewVal; 162 if (UserBB == OrigPreheader) 163 NewVal = OrigPreHeaderVal; 164 else if (SSA.HasValueForBlock(UserBB)) 165 NewVal = SSA.GetValueInMiddleOfBlock(UserBB); 166 else 167 NewVal = UndefValue::get(OrigHeaderVal->getType()); 168 U = MetadataAsValue::get(C, ValueAsMetadata::get(NewVal)); 169 } 170 } 171 } 172 } 173 } 174 175 /// Rotate loop LP. Return true if the loop is rotated. 176 /// 177 /// \param SimplifiedLatch is true if the latch was just folded into the final 178 /// loop exit. In this case we may want to rotate even though the new latch is 179 /// now an exiting branch. This rotation would have happened had the latch not 180 /// been simplified. However, if SimplifiedLatch is false, then we avoid 181 /// rotating loops in which the latch exits to avoid excessive or endless 182 /// rotation. LoopRotate should be repeatable and converge to a canonical 183 /// form. This property is satisfied because simplifying the loop latch can only 184 /// happen once across multiple invocations of the LoopRotate pass. 185 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) { 186 // If the loop has only one block then there is not much to rotate. 187 if (L->getBlocks().size() == 1) 188 return false; 189 190 BasicBlock *OrigHeader = L->getHeader(); 191 BasicBlock *OrigLatch = L->getLoopLatch(); 192 193 BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator()); 194 if (!BI || BI->isUnconditional()) 195 return false; 196 197 // If the loop header is not one of the loop exiting blocks then 198 // either this loop is already rotated or it is not 199 // suitable for loop rotation transformations. 200 if (!L->isLoopExiting(OrigHeader)) 201 return false; 202 203 // If the loop latch already contains a branch that leaves the loop then the 204 // loop is already rotated. 205 if (!OrigLatch) 206 return false; 207 208 // Rotate if either the loop latch does *not* exit the loop, or if the loop 209 // latch was just simplified. 210 if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch) 211 return false; 212 213 // Check size of original header and reject loop if it is very big or we can't 214 // duplicate blocks inside it. 215 { 216 SmallPtrSet<const Value *, 32> EphValues; 217 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 218 219 CodeMetrics Metrics; 220 Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues); 221 if (Metrics.notDuplicatable) { 222 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable" 223 << " instructions: "; 224 L->dump()); 225 return false; 226 } 227 if (Metrics.convergent) { 228 DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent " 229 "instructions: "; 230 L->dump()); 231 return false; 232 } 233 if (Metrics.NumInsts > MaxHeaderSize) 234 return false; 235 } 236 237 // Now, this loop is suitable for rotation. 238 BasicBlock *OrigPreheader = L->getLoopPreheader(); 239 240 // If the loop could not be converted to canonical form, it must have an 241 // indirectbr in it, just give up. 242 if (!OrigPreheader) 243 return false; 244 245 // Anything ScalarEvolution may know about this loop or the PHI nodes 246 // in its header will soon be invalidated. 247 if (SE) 248 SE->forgetLoop(L); 249 250 DEBUG(dbgs() << "LoopRotation: rotating "; L->dump()); 251 252 // Find new Loop header. NewHeader is a Header's one and only successor 253 // that is inside loop. Header's other successor is outside the 254 // loop. Otherwise loop is not suitable for rotation. 255 BasicBlock *Exit = BI->getSuccessor(0); 256 BasicBlock *NewHeader = BI->getSuccessor(1); 257 if (L->contains(Exit)) 258 std::swap(Exit, NewHeader); 259 assert(NewHeader && "Unable to determine new loop header"); 260 assert(L->contains(NewHeader) && !L->contains(Exit) && 261 "Unable to determine loop header and exit blocks"); 262 263 // This code assumes that the new header has exactly one predecessor. 264 // Remove any single-entry PHI nodes in it. 265 assert(NewHeader->getSinglePredecessor() && 266 "New header doesn't have one pred!"); 267 FoldSingleEntryPHINodes(NewHeader); 268 269 // Begin by walking OrigHeader and populating ValueMap with an entry for 270 // each Instruction. 271 BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end(); 272 ValueToValueMapTy ValueMap; 273 274 // For PHI nodes, the value available in OldPreHeader is just the 275 // incoming value from OldPreHeader. 276 for (; PHINode *PN = dyn_cast<PHINode>(I); ++I) 277 ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader); 278 279 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 280 281 // For the rest of the instructions, either hoist to the OrigPreheader if 282 // possible or create a clone in the OldPreHeader if not. 283 TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator(); 284 while (I != E) { 285 Instruction *Inst = &*I++; 286 287 // If the instruction's operands are invariant and it doesn't read or write 288 // memory, then it is safe to hoist. Doing this doesn't change the order of 289 // execution in the preheader, but does prevent the instruction from 290 // executing in each iteration of the loop. This means it is safe to hoist 291 // something that might trap, but isn't safe to hoist something that reads 292 // memory (without proving that the loop doesn't write). 293 if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() && 294 !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) && 295 !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) { 296 Inst->moveBefore(LoopEntryBranch); 297 continue; 298 } 299 300 // Otherwise, create a duplicate of the instruction. 301 Instruction *C = Inst->clone(); 302 303 // Eagerly remap the operands of the instruction. 304 RemapInstruction(C, ValueMap, 305 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 306 307 // With the operands remapped, see if the instruction constant folds or is 308 // otherwise simplifyable. This commonly occurs because the entry from PHI 309 // nodes allows icmps and other instructions to fold. 310 // FIXME: Provide TLI, DT, AC to SimplifyInstruction. 311 Value *V = SimplifyInstruction(C, DL); 312 if (V && LI->replacementPreservesLCSSAForm(C, V)) { 313 // If so, then delete the temporary instruction and stick the folded value 314 // in the map. 315 ValueMap[Inst] = V; 316 if (!C->mayHaveSideEffects()) { 317 delete C; 318 C = nullptr; 319 } 320 } else { 321 ValueMap[Inst] = C; 322 } 323 if (C) { 324 // Otherwise, stick the new instruction into the new block! 325 C->setName(Inst->getName()); 326 C->insertBefore(LoopEntryBranch); 327 } 328 } 329 330 // Along with all the other instructions, we just cloned OrigHeader's 331 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's 332 // successors by duplicating their incoming values for OrigHeader. 333 TerminatorInst *TI = OrigHeader->getTerminator(); 334 for (BasicBlock *SuccBB : TI->successors()) 335 for (BasicBlock::iterator BI = SuccBB->begin(); 336 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 337 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader); 338 339 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove 340 // OrigPreHeader's old terminator (the original branch into the loop), and 341 // remove the corresponding incoming values from the PHI nodes in OrigHeader. 342 LoopEntryBranch->eraseFromParent(); 343 344 // If there were any uses of instructions in the duplicated block outside the 345 // loop, update them, inserting PHI nodes as required 346 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap); 347 348 // NewHeader is now the header of the loop. 349 L->moveToHeader(NewHeader); 350 assert(L->getHeader() == NewHeader && "Latch block is our new header"); 351 352 // At this point, we've finished our major CFG changes. As part of cloning 353 // the loop into the preheader we've simplified instructions and the 354 // duplicated conditional branch may now be branching on a constant. If it is 355 // branching on a constant and if that constant means that we enter the loop, 356 // then we fold away the cond branch to an uncond branch. This simplifies the 357 // loop in cases important for nested loops, and it also means we don't have 358 // to split as many edges. 359 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator()); 360 assert(PHBI->isConditional() && "Should be clone of BI condbr!"); 361 if (!isa<ConstantInt>(PHBI->getCondition()) || 362 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) != 363 NewHeader) { 364 // The conditional branch can't be folded, handle the general case. 365 // Update DominatorTree to reflect the CFG change we just made. Then split 366 // edges as necessary to preserve LoopSimplify form. 367 if (DT) { 368 // Everything that was dominated by the old loop header is now dominated 369 // by the original loop preheader. Conceptually the header was merged 370 // into the preheader, even though we reuse the actual block as a new 371 // loop latch. 372 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader); 373 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), 374 OrigHeaderNode->end()); 375 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader); 376 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) 377 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode); 378 379 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode); 380 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode); 381 382 // Update OrigHeader to be dominated by the new header block. 383 DT->changeImmediateDominator(OrigHeader, OrigLatch); 384 } 385 386 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and 387 // thus is not a preheader anymore. 388 // Split the edge to form a real preheader. 389 BasicBlock *NewPH = SplitCriticalEdge( 390 OrigPreheader, NewHeader, 391 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA()); 392 NewPH->setName(NewHeader->getName() + ".lr.ph"); 393 394 // Preserve canonical loop form, which means that 'Exit' should have only 395 // one predecessor. Note that Exit could be an exit block for multiple 396 // nested loops, causing both of the edges to now be critical and need to 397 // be split. 398 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit)); 399 bool SplitLatchEdge = false; 400 for (BasicBlock *ExitPred : ExitPreds) { 401 // We only need to split loop exit edges. 402 Loop *PredLoop = LI->getLoopFor(ExitPred); 403 if (!PredLoop || PredLoop->contains(Exit)) 404 continue; 405 if (isa<IndirectBrInst>(ExitPred->getTerminator())) 406 continue; 407 SplitLatchEdge |= L->getLoopLatch() == ExitPred; 408 BasicBlock *ExitSplit = SplitCriticalEdge( 409 ExitPred, Exit, 410 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA()); 411 ExitSplit->moveBefore(Exit); 412 } 413 assert(SplitLatchEdge && 414 "Despite splitting all preds, failed to split latch exit?"); 415 } else { 416 // We can fold the conditional branch in the preheader, this makes things 417 // simpler. The first step is to remove the extra edge to the Exit block. 418 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/); 419 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI); 420 NewBI->setDebugLoc(PHBI->getDebugLoc()); 421 PHBI->eraseFromParent(); 422 423 // With our CFG finalized, update DomTree if it is available. 424 if (DT) { 425 // Update OrigHeader to be dominated by the new header block. 426 DT->changeImmediateDominator(NewHeader, OrigPreheader); 427 DT->changeImmediateDominator(OrigHeader, OrigLatch); 428 429 // Brute force incremental dominator tree update. Call 430 // findNearestCommonDominator on all CFG predecessors of each child of the 431 // original header. 432 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader); 433 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), 434 OrigHeaderNode->end()); 435 bool Changed; 436 do { 437 Changed = false; 438 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) { 439 DomTreeNode *Node = HeaderChildren[I]; 440 BasicBlock *BB = Node->getBlock(); 441 442 pred_iterator PI = pred_begin(BB); 443 BasicBlock *NearestDom = *PI; 444 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI) 445 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI); 446 447 // Remember if this changes the DomTree. 448 if (Node->getIDom()->getBlock() != NearestDom) { 449 DT->changeImmediateDominator(BB, NearestDom); 450 Changed = true; 451 } 452 } 453 454 // If the dominator changed, this may have an effect on other 455 // predecessors, continue until we reach a fixpoint. 456 } while (Changed); 457 } 458 } 459 460 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation"); 461 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation"); 462 463 // Now that the CFG and DomTree are in a consistent state again, try to merge 464 // the OrigHeader block into OrigLatch. This will succeed if they are 465 // connected by an unconditional branch. This is just a cleanup so the 466 // emitted code isn't too gross in this common case. 467 MergeBlockIntoPredecessor(OrigHeader, DT, LI); 468 469 DEBUG(dbgs() << "LoopRotation: into "; L->dump()); 470 471 ++NumRotated; 472 return true; 473 } 474 475 /// Determine whether the instructions in this range may be safely and cheaply 476 /// speculated. This is not an important enough situation to develop complex 477 /// heuristics. We handle a single arithmetic instruction along with any type 478 /// conversions. 479 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, 480 BasicBlock::iterator End, Loop *L) { 481 bool seenIncrement = false; 482 bool MultiExitLoop = false; 483 484 if (!L->getExitingBlock()) 485 MultiExitLoop = true; 486 487 for (BasicBlock::iterator I = Begin; I != End; ++I) { 488 489 if (!isSafeToSpeculativelyExecute(&*I)) 490 return false; 491 492 if (isa<DbgInfoIntrinsic>(I)) 493 continue; 494 495 switch (I->getOpcode()) { 496 default: 497 return false; 498 case Instruction::GetElementPtr: 499 // GEPs are cheap if all indices are constant. 500 if (!cast<GEPOperator>(I)->hasAllConstantIndices()) 501 return false; 502 // fall-thru to increment case 503 case Instruction::Add: 504 case Instruction::Sub: 505 case Instruction::And: 506 case Instruction::Or: 507 case Instruction::Xor: 508 case Instruction::Shl: 509 case Instruction::LShr: 510 case Instruction::AShr: { 511 Value *IVOpnd = 512 !isa<Constant>(I->getOperand(0)) 513 ? I->getOperand(0) 514 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr; 515 if (!IVOpnd) 516 return false; 517 518 // If increment operand is used outside of the loop, this speculation 519 // could cause extra live range interference. 520 if (MultiExitLoop) { 521 for (User *UseI : IVOpnd->users()) { 522 auto *UserInst = cast<Instruction>(UseI); 523 if (!L->contains(UserInst)) 524 return false; 525 } 526 } 527 528 if (seenIncrement) 529 return false; 530 seenIncrement = true; 531 break; 532 } 533 case Instruction::Trunc: 534 case Instruction::ZExt: 535 case Instruction::SExt: 536 // ignore type conversions 537 break; 538 } 539 } 540 return true; 541 } 542 543 /// Fold the loop tail into the loop exit by speculating the loop tail 544 /// instructions. Typically, this is a single post-increment. In the case of a 545 /// simple 2-block loop, hoisting the increment can be much better than 546 /// duplicating the entire loop header. In the case of loops with early exits, 547 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in 548 /// canonical form so downstream passes can handle it. 549 /// 550 /// I don't believe this invalidates SCEV. 551 bool LoopRotate::simplifyLoopLatch(Loop *L) { 552 BasicBlock *Latch = L->getLoopLatch(); 553 if (!Latch || Latch->hasAddressTaken()) 554 return false; 555 556 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator()); 557 if (!Jmp || !Jmp->isUnconditional()) 558 return false; 559 560 BasicBlock *LastExit = Latch->getSinglePredecessor(); 561 if (!LastExit || !L->isLoopExiting(LastExit)) 562 return false; 563 564 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator()); 565 if (!BI) 566 return false; 567 568 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L)) 569 return false; 570 571 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into " 572 << LastExit->getName() << "\n"); 573 574 // Hoist the instructions from Latch into LastExit. 575 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(), 576 Latch->begin(), Jmp->getIterator()); 577 578 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1; 579 BasicBlock *Header = Jmp->getSuccessor(0); 580 assert(Header == L->getHeader() && "expected a backward branch"); 581 582 // Remove Latch from the CFG so that LastExit becomes the new Latch. 583 BI->setSuccessor(FallThruPath, Header); 584 Latch->replaceSuccessorsPhiUsesWith(LastExit); 585 Jmp->eraseFromParent(); 586 587 // Nuke the Latch block. 588 assert(Latch->empty() && "unable to evacuate Latch"); 589 LI->removeBlock(Latch); 590 if (DT) 591 DT->eraseNode(Latch); 592 Latch->eraseFromParent(); 593 return true; 594 } 595 596 /// Rotate \c L, and return true if any modification was made. 597 bool LoopRotate::processLoop(Loop *L) { 598 // Save the loop metadata. 599 MDNode *LoopMD = L->getLoopID(); 600 601 // Simplify the loop latch before attempting to rotate the header 602 // upward. Rotation may not be needed if the loop tail can be folded into the 603 // loop exit. 604 bool SimplifiedLatch = simplifyLoopLatch(L); 605 606 bool MadeChange = rotateLoop(L, SimplifiedLatch); 607 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) && 608 "Loop latch should be exiting after loop-rotate."); 609 610 // Restore the loop metadata. 611 // NB! We presume LoopRotation DOESN'T ADD its own metadata. 612 if ((MadeChange || SimplifiedLatch) && LoopMD) 613 L->setLoopID(LoopMD); 614 615 return MadeChange; 616 } 617 618 LoopRotatePass::LoopRotatePass() {} 619 620 PreservedAnalyses LoopRotatePass::run(Loop &L, AnalysisManager<Loop> &AM) { 621 auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager(); 622 Function *F = L.getHeader()->getParent(); 623 624 auto *LI = FAM.getCachedResult<LoopAnalysis>(*F); 625 const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F); 626 auto *AC = FAM.getCachedResult<AssumptionAnalysis>(*F); 627 assert((LI && TTI && AC) && "Analyses for loop rotation not available"); 628 629 // Optional analyses. 630 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F); 631 auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F); 632 LoopRotate LR(DefaultRotationThreshold, LI, TTI, AC, DT, SE); 633 634 bool Changed = LR.processLoop(&L); 635 if (!Changed) 636 return PreservedAnalyses::all(); 637 return getLoopPassPreservedAnalyses(); 638 } 639 640 namespace { 641 642 class LoopRotateLegacyPass : public LoopPass { 643 unsigned MaxHeaderSize; 644 645 public: 646 static char ID; // Pass ID, replacement for typeid 647 LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) { 648 initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry()); 649 if (SpecifiedMaxHeaderSize == -1) 650 MaxHeaderSize = DefaultRotationThreshold; 651 else 652 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize); 653 } 654 655 // LCSSA form makes instruction renaming easier. 656 void getAnalysisUsage(AnalysisUsage &AU) const override { 657 AU.addRequired<AssumptionCacheTracker>(); 658 AU.addRequired<TargetTransformInfoWrapperPass>(); 659 getLoopAnalysisUsage(AU); 660 } 661 662 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 663 if (skipLoop(L)) 664 return false; 665 Function &F = *L->getHeader()->getParent(); 666 667 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 668 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 669 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 670 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 671 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; 672 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 673 auto *SE = SEWP ? &SEWP->getSE() : nullptr; 674 LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE); 675 return LR.processLoop(L); 676 } 677 }; 678 } 679 680 char LoopRotateLegacyPass::ID = 0; 681 INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", 682 false, false) 683 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 684 INITIALIZE_PASS_DEPENDENCY(LoopPass) 685 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 686 INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false, 687 false) 688 689 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) { 690 return new LoopRotateLegacyPass(MaxHeaderSize); 691 } 692