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