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