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