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 delete C; 316 ValueMap[Inst] = V; 317 } else { 318 // Otherwise, stick the new instruction into the new block! 319 C->setName(Inst->getName()); 320 C->insertBefore(LoopEntryBranch); 321 ValueMap[Inst] = C; 322 } 323 } 324 325 // Along with all the other instructions, we just cloned OrigHeader's 326 // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's 327 // successors by duplicating their incoming values for OrigHeader. 328 TerminatorInst *TI = OrigHeader->getTerminator(); 329 for (BasicBlock *SuccBB : TI->successors()) 330 for (BasicBlock::iterator BI = SuccBB->begin(); 331 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) 332 PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader); 333 334 // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove 335 // OrigPreHeader's old terminator (the original branch into the loop), and 336 // remove the corresponding incoming values from the PHI nodes in OrigHeader. 337 LoopEntryBranch->eraseFromParent(); 338 339 // If there were any uses of instructions in the duplicated block outside the 340 // loop, update them, inserting PHI nodes as required 341 RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap); 342 343 // NewHeader is now the header of the loop. 344 L->moveToHeader(NewHeader); 345 assert(L->getHeader() == NewHeader && "Latch block is our new header"); 346 347 // At this point, we've finished our major CFG changes. As part of cloning 348 // the loop into the preheader we've simplified instructions and the 349 // duplicated conditional branch may now be branching on a constant. If it is 350 // branching on a constant and if that constant means that we enter the loop, 351 // then we fold away the cond branch to an uncond branch. This simplifies the 352 // loop in cases important for nested loops, and it also means we don't have 353 // to split as many edges. 354 BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator()); 355 assert(PHBI->isConditional() && "Should be clone of BI condbr!"); 356 if (!isa<ConstantInt>(PHBI->getCondition()) || 357 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) != 358 NewHeader) { 359 // The conditional branch can't be folded, handle the general case. 360 // Update DominatorTree to reflect the CFG change we just made. Then split 361 // edges as necessary to preserve LoopSimplify form. 362 if (DT) { 363 // Everything that was dominated by the old loop header is now dominated 364 // by the original loop preheader. Conceptually the header was merged 365 // into the preheader, even though we reuse the actual block as a new 366 // loop latch. 367 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader); 368 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), 369 OrigHeaderNode->end()); 370 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader); 371 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) 372 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode); 373 374 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode); 375 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode); 376 377 // Update OrigHeader to be dominated by the new header block. 378 DT->changeImmediateDominator(OrigHeader, OrigLatch); 379 } 380 381 // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and 382 // thus is not a preheader anymore. 383 // Split the edge to form a real preheader. 384 BasicBlock *NewPH = SplitCriticalEdge( 385 OrigPreheader, NewHeader, 386 CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA()); 387 NewPH->setName(NewHeader->getName() + ".lr.ph"); 388 389 // Preserve canonical loop form, which means that 'Exit' should have only 390 // one predecessor. Note that Exit could be an exit block for multiple 391 // nested loops, causing both of the edges to now be critical and need to 392 // be split. 393 SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit)); 394 bool SplitLatchEdge = false; 395 for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(), 396 PE = ExitPreds.end(); 397 PI != PE; ++PI) { 398 // We only need to split loop exit edges. 399 Loop *PredLoop = LI->getLoopFor(*PI); 400 if (!PredLoop || PredLoop->contains(Exit)) 401 continue; 402 if (isa<IndirectBrInst>((*PI)->getTerminator())) 403 continue; 404 SplitLatchEdge |= L->getLoopLatch() == *PI; 405 BasicBlock *ExitSplit = SplitCriticalEdge( 406 *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA()); 407 ExitSplit->moveBefore(Exit); 408 } 409 assert(SplitLatchEdge && 410 "Despite splitting all preds, failed to split latch exit?"); 411 } else { 412 // We can fold the conditional branch in the preheader, this makes things 413 // simpler. The first step is to remove the extra edge to the Exit block. 414 Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/); 415 BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI); 416 NewBI->setDebugLoc(PHBI->getDebugLoc()); 417 PHBI->eraseFromParent(); 418 419 // With our CFG finalized, update DomTree if it is available. 420 if (DT) { 421 // Update OrigHeader to be dominated by the new header block. 422 DT->changeImmediateDominator(NewHeader, OrigPreheader); 423 DT->changeImmediateDominator(OrigHeader, OrigLatch); 424 425 // Brute force incremental dominator tree update. Call 426 // findNearestCommonDominator on all CFG predecessors of each child of the 427 // original header. 428 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader); 429 SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(), 430 OrigHeaderNode->end()); 431 bool Changed; 432 do { 433 Changed = false; 434 for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) { 435 DomTreeNode *Node = HeaderChildren[I]; 436 BasicBlock *BB = Node->getBlock(); 437 438 pred_iterator PI = pred_begin(BB); 439 BasicBlock *NearestDom = *PI; 440 for (pred_iterator PE = pred_end(BB); PI != PE; ++PI) 441 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI); 442 443 // Remember if this changes the DomTree. 444 if (Node->getIDom()->getBlock() != NearestDom) { 445 DT->changeImmediateDominator(BB, NearestDom); 446 Changed = true; 447 } 448 } 449 450 // If the dominator changed, this may have an effect on other 451 // predecessors, continue until we reach a fixpoint. 452 } while (Changed); 453 } 454 } 455 456 assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation"); 457 assert(L->getLoopLatch() && "Invalid loop latch after loop rotation"); 458 459 // Now that the CFG and DomTree are in a consistent state again, try to merge 460 // the OrigHeader block into OrigLatch. This will succeed if they are 461 // connected by an unconditional branch. This is just a cleanup so the 462 // emitted code isn't too gross in this common case. 463 MergeBlockIntoPredecessor(OrigHeader, DT, LI); 464 465 DEBUG(dbgs() << "LoopRotation: into "; L->dump()); 466 467 ++NumRotated; 468 return true; 469 } 470 471 /// Determine whether the instructions in this range may be safely and cheaply 472 /// speculated. This is not an important enough situation to develop complex 473 /// heuristics. We handle a single arithmetic instruction along with any type 474 /// conversions. 475 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, 476 BasicBlock::iterator End, Loop *L) { 477 bool seenIncrement = false; 478 bool MultiExitLoop = false; 479 480 if (!L->getExitingBlock()) 481 MultiExitLoop = true; 482 483 for (BasicBlock::iterator I = Begin; I != End; ++I) { 484 485 if (!isSafeToSpeculativelyExecute(&*I)) 486 return false; 487 488 if (isa<DbgInfoIntrinsic>(I)) 489 continue; 490 491 switch (I->getOpcode()) { 492 default: 493 return false; 494 case Instruction::GetElementPtr: 495 // GEPs are cheap if all indices are constant. 496 if (!cast<GEPOperator>(I)->hasAllConstantIndices()) 497 return false; 498 // fall-thru to increment case 499 case Instruction::Add: 500 case Instruction::Sub: 501 case Instruction::And: 502 case Instruction::Or: 503 case Instruction::Xor: 504 case Instruction::Shl: 505 case Instruction::LShr: 506 case Instruction::AShr: { 507 Value *IVOpnd = 508 !isa<Constant>(I->getOperand(0)) 509 ? I->getOperand(0) 510 : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr; 511 if (!IVOpnd) 512 return false; 513 514 // If increment operand is used outside of the loop, this speculation 515 // could cause extra live range interference. 516 if (MultiExitLoop) { 517 for (User *UseI : IVOpnd->users()) { 518 auto *UserInst = cast<Instruction>(UseI); 519 if (!L->contains(UserInst)) 520 return false; 521 } 522 } 523 524 if (seenIncrement) 525 return false; 526 seenIncrement = true; 527 break; 528 } 529 case Instruction::Trunc: 530 case Instruction::ZExt: 531 case Instruction::SExt: 532 // ignore type conversions 533 break; 534 } 535 } 536 return true; 537 } 538 539 /// Fold the loop tail into the loop exit by speculating the loop tail 540 /// instructions. Typically, this is a single post-increment. In the case of a 541 /// simple 2-block loop, hoisting the increment can be much better than 542 /// duplicating the entire loop header. In the case of loops with early exits, 543 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in 544 /// canonical form so downstream passes can handle it. 545 /// 546 /// I don't believe this invalidates SCEV. 547 bool LoopRotate::simplifyLoopLatch(Loop *L) { 548 BasicBlock *Latch = L->getLoopLatch(); 549 if (!Latch || Latch->hasAddressTaken()) 550 return false; 551 552 BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator()); 553 if (!Jmp || !Jmp->isUnconditional()) 554 return false; 555 556 BasicBlock *LastExit = Latch->getSinglePredecessor(); 557 if (!LastExit || !L->isLoopExiting(LastExit)) 558 return false; 559 560 BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator()); 561 if (!BI) 562 return false; 563 564 if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L)) 565 return false; 566 567 DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into " 568 << LastExit->getName() << "\n"); 569 570 // Hoist the instructions from Latch into LastExit. 571 LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(), 572 Latch->begin(), Jmp->getIterator()); 573 574 unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1; 575 BasicBlock *Header = Jmp->getSuccessor(0); 576 assert(Header == L->getHeader() && "expected a backward branch"); 577 578 // Remove Latch from the CFG so that LastExit becomes the new Latch. 579 BI->setSuccessor(FallThruPath, Header); 580 Latch->replaceSuccessorsPhiUsesWith(LastExit); 581 Jmp->eraseFromParent(); 582 583 // Nuke the Latch block. 584 assert(Latch->empty() && "unable to evacuate Latch"); 585 LI->removeBlock(Latch); 586 if (DT) 587 DT->eraseNode(Latch); 588 Latch->eraseFromParent(); 589 return true; 590 } 591 592 /// Rotate \c L, and return true if any modification was made. 593 bool LoopRotate::processLoop(Loop *L) { 594 // Save the loop metadata. 595 MDNode *LoopMD = L->getLoopID(); 596 597 // Simplify the loop latch before attempting to rotate the header 598 // upward. Rotation may not be needed if the loop tail can be folded into the 599 // loop exit. 600 bool SimplifiedLatch = simplifyLoopLatch(L); 601 602 bool MadeChange = rotateLoop(L, SimplifiedLatch); 603 assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) && 604 "Loop latch should be exiting after loop-rotate."); 605 606 // Restore the loop metadata. 607 // NB! We presume LoopRotation DOESN'T ADD its own metadata. 608 if ((MadeChange || SimplifiedLatch) && LoopMD) 609 L->setLoopID(LoopMD); 610 611 return MadeChange; 612 } 613 614 LoopRotatePass::LoopRotatePass() {} 615 616 PreservedAnalyses LoopRotatePass::run(Loop &L, AnalysisManager<Loop> &AM) { 617 auto &FAM = AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager(); 618 Function *F = L.getHeader()->getParent(); 619 620 auto *LI = FAM.getCachedResult<LoopAnalysis>(*F); 621 const auto *TTI = FAM.getCachedResult<TargetIRAnalysis>(*F); 622 auto *AC = FAM.getCachedResult<AssumptionAnalysis>(*F); 623 assert((LI && TTI && AC) && "Analyses for loop rotation not available"); 624 625 // Optional analyses. 626 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F); 627 auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F); 628 LoopRotate LR(DefaultRotationThreshold, LI, TTI, AC, DT, SE); 629 630 bool Changed = LR.processLoop(&L); 631 if (!Changed) 632 return PreservedAnalyses::all(); 633 return getLoopPassPreservedAnalyses(); 634 } 635 636 namespace { 637 638 class LoopRotateLegacyPass : public LoopPass { 639 unsigned MaxHeaderSize; 640 641 public: 642 static char ID; // Pass ID, replacement for typeid 643 LoopRotateLegacyPass(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) { 644 initializeLoopRotateLegacyPassPass(*PassRegistry::getPassRegistry()); 645 if (SpecifiedMaxHeaderSize == -1) 646 MaxHeaderSize = DefaultRotationThreshold; 647 else 648 MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize); 649 } 650 651 // LCSSA form makes instruction renaming easier. 652 void getAnalysisUsage(AnalysisUsage &AU) const override { 653 AU.addRequired<AssumptionCacheTracker>(); 654 AU.addRequired<TargetTransformInfoWrapperPass>(); 655 getLoopAnalysisUsage(AU); 656 } 657 658 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 659 if (skipLoop(L)) 660 return false; 661 Function &F = *L->getHeader()->getParent(); 662 663 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 664 const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 665 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 666 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 667 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; 668 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 669 auto *SE = SEWP ? &SEWP->getSE() : nullptr; 670 LoopRotate LR(MaxHeaderSize, LI, TTI, AC, DT, SE); 671 return LR.processLoop(L); 672 } 673 }; 674 } 675 676 char LoopRotateLegacyPass::ID = 0; 677 INITIALIZE_PASS_BEGIN(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", 678 false, false) 679 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 680 INITIALIZE_PASS_DEPENDENCY(LoopPass) 681 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 682 INITIALIZE_PASS_END(LoopRotateLegacyPass, "loop-rotate", "Rotate Loops", false, 683 false) 684 685 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) { 686 return new LoopRotateLegacyPass(MaxHeaderSize); 687 } 688