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