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