1 ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===// 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 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 10 #include "llvm/ADT/DenseMap.h" 11 #include "llvm/ADT/STLExtras.h" 12 #include "llvm/ADT/Sequence.h" 13 #include "llvm/ADT/SetVector.h" 14 #include "llvm/ADT/SmallPtrSet.h" 15 #include "llvm/ADT/SmallVector.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/ADT/Twine.h" 18 #include "llvm/Analysis/AssumptionCache.h" 19 #include "llvm/Analysis/BlockFrequencyInfo.h" 20 #include "llvm/Analysis/CFG.h" 21 #include "llvm/Analysis/CodeMetrics.h" 22 #include "llvm/Analysis/GuardUtils.h" 23 #include "llvm/Analysis/LoopAnalysisManager.h" 24 #include "llvm/Analysis/LoopInfo.h" 25 #include "llvm/Analysis/LoopIterator.h" 26 #include "llvm/Analysis/LoopPass.h" 27 #include "llvm/Analysis/MemorySSA.h" 28 #include "llvm/Analysis/MemorySSAUpdater.h" 29 #include "llvm/Analysis/MustExecute.h" 30 #include "llvm/Analysis/ProfileSummaryInfo.h" 31 #include "llvm/Analysis/ScalarEvolution.h" 32 #include "llvm/Analysis/TargetTransformInfo.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/IR/BasicBlock.h" 35 #include "llvm/IR/Constant.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/Dominators.h" 38 #include "llvm/IR/Function.h" 39 #include "llvm/IR/IRBuilder.h" 40 #include "llvm/IR/InstrTypes.h" 41 #include "llvm/IR/Instruction.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/IntrinsicInst.h" 44 #include "llvm/IR/PatternMatch.h" 45 #include "llvm/IR/Use.h" 46 #include "llvm/IR/Value.h" 47 #include "llvm/InitializePasses.h" 48 #include "llvm/Pass.h" 49 #include "llvm/Support/Casting.h" 50 #include "llvm/Support/CommandLine.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/GenericDomTree.h" 54 #include "llvm/Support/InstructionCost.h" 55 #include "llvm/Support/raw_ostream.h" 56 #include "llvm/Transforms/Scalar/LoopPassManager.h" 57 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 58 #include "llvm/Transforms/Utils/Cloning.h" 59 #include "llvm/Transforms/Utils/Local.h" 60 #include "llvm/Transforms/Utils/LoopUtils.h" 61 #include "llvm/Transforms/Utils/ValueMapper.h" 62 #include <algorithm> 63 #include <cassert> 64 #include <iterator> 65 #include <numeric> 66 #include <utility> 67 68 #define DEBUG_TYPE "simple-loop-unswitch" 69 70 using namespace llvm; 71 using namespace llvm::PatternMatch; 72 73 STATISTIC(NumBranches, "Number of branches unswitched"); 74 STATISTIC(NumSwitches, "Number of switches unswitched"); 75 STATISTIC(NumGuards, "Number of guards turned into branches for unswitching"); 76 STATISTIC(NumTrivial, "Number of unswitches that are trivial"); 77 STATISTIC( 78 NumCostMultiplierSkipped, 79 "Number of unswitch candidates that had their cost multiplier skipped"); 80 81 static cl::opt<bool> EnableNonTrivialUnswitch( 82 "enable-nontrivial-unswitch", cl::init(false), cl::Hidden, 83 cl::desc("Forcibly enables non-trivial loop unswitching rather than " 84 "following the configuration passed into the pass.")); 85 86 static cl::opt<int> 87 UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden, 88 cl::desc("The cost threshold for unswitching a loop.")); 89 90 static cl::opt<bool> EnableUnswitchCostMultiplier( 91 "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden, 92 cl::desc("Enable unswitch cost multiplier that prohibits exponential " 93 "explosion in nontrivial unswitch.")); 94 static cl::opt<int> UnswitchSiblingsToplevelDiv( 95 "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden, 96 cl::desc("Toplevel siblings divisor for cost multiplier.")); 97 static cl::opt<int> UnswitchNumInitialUnscaledCandidates( 98 "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden, 99 cl::desc("Number of unswitch candidates that are ignored when calculating " 100 "cost multiplier.")); 101 static cl::opt<bool> UnswitchGuards( 102 "simple-loop-unswitch-guards", cl::init(true), cl::Hidden, 103 cl::desc("If enabled, simple loop unswitching will also consider " 104 "llvm.experimental.guard intrinsics as unswitch candidates.")); 105 static cl::opt<bool> DropNonTrivialImplicitNullChecks( 106 "simple-loop-unswitch-drop-non-trivial-implicit-null-checks", 107 cl::init(false), cl::Hidden, 108 cl::desc("If enabled, drop make.implicit metadata in unswitched implicit " 109 "null checks to save time analyzing if we can keep it.")); 110 static cl::opt<unsigned> 111 MSSAThreshold("simple-loop-unswitch-memoryssa-threshold", 112 cl::desc("Max number of memory uses to explore during " 113 "partial unswitching analysis"), 114 cl::init(100), cl::Hidden); 115 static cl::opt<bool> FreezeLoopUnswitchCond( 116 "freeze-loop-unswitch-cond", cl::init(true), cl::Hidden, 117 cl::desc("If enabled, the freeze instruction will be added to condition " 118 "of loop unswitch to prevent miscompilation.")); 119 120 namespace { 121 struct NonTrivialUnswitchCandidate { 122 Instruction *TI = nullptr; 123 TinyPtrVector<Value *> Invariants; 124 Optional<InstructionCost> Cost; 125 NonTrivialUnswitchCandidate(Instruction *TI, ArrayRef<Value *> Invariants, 126 Optional<InstructionCost> Cost = None) 127 : TI(TI), Invariants(Invariants), Cost(Cost) {}; 128 }; 129 } // end anonymous namespace. 130 131 // Helper to skip (select x, true, false), which matches both a logical AND and 132 // OR and can confuse code that tries to determine if \p Cond is either a 133 // logical AND or OR but not both. 134 static Value *skipTrivialSelect(Value *Cond) { 135 Value *CondNext; 136 while (match(Cond, m_Select(m_Value(CondNext), m_One(), m_Zero()))) 137 Cond = CondNext; 138 return Cond; 139 } 140 141 /// Collect all of the loop invariant input values transitively used by the 142 /// homogeneous instruction graph from a given root. 143 /// 144 /// This essentially walks from a root recursively through loop variant operands 145 /// which have perform the same logical operation (AND or OR) and finds all 146 /// inputs which are loop invariant. For some operations these can be 147 /// re-associated and unswitched out of the loop entirely. 148 static TinyPtrVector<Value *> 149 collectHomogenousInstGraphLoopInvariants(const Loop &L, Instruction &Root, 150 const LoopInfo &LI) { 151 assert(!L.isLoopInvariant(&Root) && 152 "Only need to walk the graph if root itself is not invariant."); 153 TinyPtrVector<Value *> Invariants; 154 155 bool IsRootAnd = match(&Root, m_LogicalAnd()); 156 bool IsRootOr = match(&Root, m_LogicalOr()); 157 158 // Build a worklist and recurse through operators collecting invariants. 159 SmallVector<Instruction *, 4> Worklist; 160 SmallPtrSet<Instruction *, 8> Visited; 161 Worklist.push_back(&Root); 162 Visited.insert(&Root); 163 do { 164 Instruction &I = *Worklist.pop_back_val(); 165 for (Value *OpV : I.operand_values()) { 166 // Skip constants as unswitching isn't interesting for them. 167 if (isa<Constant>(OpV)) 168 continue; 169 170 // Add it to our result if loop invariant. 171 if (L.isLoopInvariant(OpV)) { 172 Invariants.push_back(OpV); 173 continue; 174 } 175 176 // If not an instruction with the same opcode, nothing we can do. 177 Instruction *OpI = dyn_cast<Instruction>(skipTrivialSelect(OpV)); 178 179 if (OpI && ((IsRootAnd && match(OpI, m_LogicalAnd())) || 180 (IsRootOr && match(OpI, m_LogicalOr())))) { 181 // Visit this operand. 182 if (Visited.insert(OpI).second) 183 Worklist.push_back(OpI); 184 } 185 } 186 } while (!Worklist.empty()); 187 188 return Invariants; 189 } 190 191 static void replaceLoopInvariantUses(const Loop &L, Value *Invariant, 192 Constant &Replacement) { 193 assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?"); 194 195 // Replace uses of LIC in the loop with the given constant. 196 // We use make_early_inc_range as set invalidates the iterator. 197 for (Use &U : llvm::make_early_inc_range(Invariant->uses())) { 198 Instruction *UserI = dyn_cast<Instruction>(U.getUser()); 199 200 // Replace this use within the loop body. 201 if (UserI && L.contains(UserI)) 202 U.set(&Replacement); 203 } 204 } 205 206 /// Check that all the LCSSA PHI nodes in the loop exit block have trivial 207 /// incoming values along this edge. 208 static bool areLoopExitPHIsLoopInvariant(const Loop &L, 209 const BasicBlock &ExitingBB, 210 const BasicBlock &ExitBB) { 211 for (const Instruction &I : ExitBB) { 212 auto *PN = dyn_cast<PHINode>(&I); 213 if (!PN) 214 // No more PHIs to check. 215 return true; 216 217 // If the incoming value for this edge isn't loop invariant the unswitch 218 // won't be trivial. 219 if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB))) 220 return false; 221 } 222 llvm_unreachable("Basic blocks should never be empty!"); 223 } 224 225 /// Copy a set of loop invariant values \p ToDuplicate and insert them at the 226 /// end of \p BB and conditionally branch on the copied condition. We only 227 /// branch on a single value. 228 static void buildPartialUnswitchConditionalBranch( 229 BasicBlock &BB, ArrayRef<Value *> Invariants, bool Direction, 230 BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, bool InsertFreeze, 231 const Instruction *I, AssumptionCache *AC, const DominatorTree &DT) { 232 IRBuilder<> IRB(&BB); 233 234 SmallVector<Value *> FrozenInvariants; 235 for (Value *Inv : Invariants) { 236 if (InsertFreeze && !isGuaranteedNotToBeUndefOrPoison(Inv, AC, I, &DT)) 237 Inv = IRB.CreateFreeze(Inv, Inv->getName() + ".fr"); 238 FrozenInvariants.push_back(Inv); 239 } 240 241 Value *Cond = Direction ? IRB.CreateOr(FrozenInvariants) 242 : IRB.CreateAnd(FrozenInvariants); 243 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc, 244 Direction ? &NormalSucc : &UnswitchedSucc); 245 } 246 247 /// Copy a set of loop invariant values, and conditionally branch on them. 248 static void buildPartialInvariantUnswitchConditionalBranch( 249 BasicBlock &BB, ArrayRef<Value *> ToDuplicate, bool Direction, 250 BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, Loop &L, 251 MemorySSAUpdater *MSSAU) { 252 ValueToValueMapTy VMap; 253 for (auto *Val : reverse(ToDuplicate)) { 254 Instruction *Inst = cast<Instruction>(Val); 255 Instruction *NewInst = Inst->clone(); 256 BB.getInstList().insert(BB.end(), NewInst); 257 RemapInstruction(NewInst, VMap, 258 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 259 VMap[Val] = NewInst; 260 261 if (!MSSAU) 262 continue; 263 264 MemorySSA *MSSA = MSSAU->getMemorySSA(); 265 if (auto *MemUse = 266 dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(Inst))) { 267 auto *DefiningAccess = MemUse->getDefiningAccess(); 268 // Get the first defining access before the loop. 269 while (L.contains(DefiningAccess->getBlock())) { 270 // If the defining access is a MemoryPhi, get the incoming 271 // value for the pre-header as defining access. 272 if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess)) 273 DefiningAccess = 274 MemPhi->getIncomingValueForBlock(L.getLoopPreheader()); 275 else 276 DefiningAccess = cast<MemoryDef>(DefiningAccess)->getDefiningAccess(); 277 } 278 MSSAU->createMemoryAccessInBB(NewInst, DefiningAccess, 279 NewInst->getParent(), 280 MemorySSA::BeforeTerminator); 281 } 282 } 283 284 IRBuilder<> IRB(&BB); 285 Value *Cond = VMap[ToDuplicate[0]]; 286 IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc, 287 Direction ? &NormalSucc : &UnswitchedSucc); 288 } 289 290 /// Rewrite the PHI nodes in an unswitched loop exit basic block. 291 /// 292 /// Requires that the loop exit and unswitched basic block are the same, and 293 /// that the exiting block was a unique predecessor of that block. Rewrites the 294 /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial 295 /// PHI nodes from the old preheader that now contains the unswitched 296 /// terminator. 297 static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB, 298 BasicBlock &OldExitingBB, 299 BasicBlock &OldPH) { 300 for (PHINode &PN : UnswitchedBB.phis()) { 301 // When the loop exit is directly unswitched we just need to update the 302 // incoming basic block. We loop to handle weird cases with repeated 303 // incoming blocks, but expect to typically only have one operand here. 304 for (auto i : seq<int>(0, PN.getNumOperands())) { 305 assert(PN.getIncomingBlock(i) == &OldExitingBB && 306 "Found incoming block different from unique predecessor!"); 307 PN.setIncomingBlock(i, &OldPH); 308 } 309 } 310 } 311 312 /// Rewrite the PHI nodes in the loop exit basic block and the split off 313 /// unswitched block. 314 /// 315 /// Because the exit block remains an exit from the loop, this rewrites the 316 /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI 317 /// nodes into the unswitched basic block to select between the value in the 318 /// old preheader and the loop exit. 319 static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB, 320 BasicBlock &UnswitchedBB, 321 BasicBlock &OldExitingBB, 322 BasicBlock &OldPH, 323 bool FullUnswitch) { 324 assert(&ExitBB != &UnswitchedBB && 325 "Must have different loop exit and unswitched blocks!"); 326 Instruction *InsertPt = &*UnswitchedBB.begin(); 327 for (PHINode &PN : ExitBB.phis()) { 328 auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2, 329 PN.getName() + ".split", InsertPt); 330 331 // Walk backwards over the old PHI node's inputs to minimize the cost of 332 // removing each one. We have to do this weird loop manually so that we 333 // create the same number of new incoming edges in the new PHI as we expect 334 // each case-based edge to be included in the unswitched switch in some 335 // cases. 336 // FIXME: This is really, really gross. It would be much cleaner if LLVM 337 // allowed us to create a single entry for a predecessor block without 338 // having separate entries for each "edge" even though these edges are 339 // required to produce identical results. 340 for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) { 341 if (PN.getIncomingBlock(i) != &OldExitingBB) 342 continue; 343 344 Value *Incoming = PN.getIncomingValue(i); 345 if (FullUnswitch) 346 // No more edge from the old exiting block to the exit block. 347 PN.removeIncomingValue(i); 348 349 NewPN->addIncoming(Incoming, &OldPH); 350 } 351 352 // Now replace the old PHI with the new one and wire the old one in as an 353 // input to the new one. 354 PN.replaceAllUsesWith(NewPN); 355 NewPN->addIncoming(&PN, &ExitBB); 356 } 357 } 358 359 /// Hoist the current loop up to the innermost loop containing a remaining exit. 360 /// 361 /// Because we've removed an exit from the loop, we may have changed the set of 362 /// loops reachable and need to move the current loop up the loop nest or even 363 /// to an entirely separate nest. 364 static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader, 365 DominatorTree &DT, LoopInfo &LI, 366 MemorySSAUpdater *MSSAU, ScalarEvolution *SE) { 367 // If the loop is already at the top level, we can't hoist it anywhere. 368 Loop *OldParentL = L.getParentLoop(); 369 if (!OldParentL) 370 return; 371 372 SmallVector<BasicBlock *, 4> Exits; 373 L.getExitBlocks(Exits); 374 Loop *NewParentL = nullptr; 375 for (auto *ExitBB : Exits) 376 if (Loop *ExitL = LI.getLoopFor(ExitBB)) 377 if (!NewParentL || NewParentL->contains(ExitL)) 378 NewParentL = ExitL; 379 380 if (NewParentL == OldParentL) 381 return; 382 383 // The new parent loop (if different) should always contain the old one. 384 if (NewParentL) 385 assert(NewParentL->contains(OldParentL) && 386 "Can only hoist this loop up the nest!"); 387 388 // The preheader will need to move with the body of this loop. However, 389 // because it isn't in this loop we also need to update the primary loop map. 390 assert(OldParentL == LI.getLoopFor(&Preheader) && 391 "Parent loop of this loop should contain this loop's preheader!"); 392 LI.changeLoopFor(&Preheader, NewParentL); 393 394 // Remove this loop from its old parent. 395 OldParentL->removeChildLoop(&L); 396 397 // Add the loop either to the new parent or as a top-level loop. 398 if (NewParentL) 399 NewParentL->addChildLoop(&L); 400 else 401 LI.addTopLevelLoop(&L); 402 403 // Remove this loops blocks from the old parent and every other loop up the 404 // nest until reaching the new parent. Also update all of these 405 // no-longer-containing loops to reflect the nesting change. 406 for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL; 407 OldContainingL = OldContainingL->getParentLoop()) { 408 llvm::erase_if(OldContainingL->getBlocksVector(), 409 [&](const BasicBlock *BB) { 410 return BB == &Preheader || L.contains(BB); 411 }); 412 413 OldContainingL->getBlocksSet().erase(&Preheader); 414 for (BasicBlock *BB : L.blocks()) 415 OldContainingL->getBlocksSet().erase(BB); 416 417 // Because we just hoisted a loop out of this one, we have essentially 418 // created new exit paths from it. That means we need to form LCSSA PHI 419 // nodes for values used in the no-longer-nested loop. 420 formLCSSA(*OldContainingL, DT, &LI, SE); 421 422 // We shouldn't need to form dedicated exits because the exit introduced 423 // here is the (just split by unswitching) preheader. However, after trivial 424 // unswitching it is possible to get new non-dedicated exits out of parent 425 // loop so let's conservatively form dedicated exit blocks and figure out 426 // if we can optimize later. 427 formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU, 428 /*PreserveLCSSA*/ true); 429 } 430 } 431 432 // Return the top-most loop containing ExitBB and having ExitBB as exiting block 433 // or the loop containing ExitBB, if there is no parent loop containing ExitBB 434 // as exiting block. 435 static const Loop *getTopMostExitingLoop(const BasicBlock *ExitBB, 436 const LoopInfo &LI) { 437 const Loop *TopMost = LI.getLoopFor(ExitBB); 438 const Loop *Current = TopMost; 439 while (Current) { 440 if (Current->isLoopExiting(ExitBB)) 441 TopMost = Current; 442 Current = Current->getParentLoop(); 443 } 444 return TopMost; 445 } 446 447 /// Unswitch a trivial branch if the condition is loop invariant. 448 /// 449 /// This routine should only be called when loop code leading to the branch has 450 /// been validated as trivial (no side effects). This routine checks if the 451 /// condition is invariant and one of the successors is a loop exit. This 452 /// allows us to unswitch without duplicating the loop, making it trivial. 453 /// 454 /// If this routine fails to unswitch the branch it returns false. 455 /// 456 /// If the branch can be unswitched, this routine splits the preheader and 457 /// hoists the branch above that split. Preserves loop simplified form 458 /// (splitting the exit block as necessary). It simplifies the branch within 459 /// the loop to an unconditional branch but doesn't remove it entirely. Further 460 /// cleanup can be done with some simplifycfg like pass. 461 /// 462 /// If `SE` is not null, it will be updated based on the potential loop SCEVs 463 /// invalidated by this. 464 static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, 465 LoopInfo &LI, ScalarEvolution *SE, 466 MemorySSAUpdater *MSSAU) { 467 assert(BI.isConditional() && "Can only unswitch a conditional branch!"); 468 LLVM_DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n"); 469 470 // The loop invariant values that we want to unswitch. 471 TinyPtrVector<Value *> Invariants; 472 473 // When true, we're fully unswitching the branch rather than just unswitching 474 // some input conditions to the branch. 475 bool FullUnswitch = false; 476 477 Value *Cond = skipTrivialSelect(BI.getCondition()); 478 if (L.isLoopInvariant(Cond)) { 479 Invariants.push_back(Cond); 480 FullUnswitch = true; 481 } else { 482 if (auto *CondInst = dyn_cast<Instruction>(Cond)) 483 Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI); 484 if (Invariants.empty()) { 485 LLVM_DEBUG(dbgs() << " Couldn't find invariant inputs!\n"); 486 return false; 487 } 488 } 489 490 // Check that one of the branch's successors exits, and which one. 491 bool ExitDirection = true; 492 int LoopExitSuccIdx = 0; 493 auto *LoopExitBB = BI.getSuccessor(0); 494 if (L.contains(LoopExitBB)) { 495 ExitDirection = false; 496 LoopExitSuccIdx = 1; 497 LoopExitBB = BI.getSuccessor(1); 498 if (L.contains(LoopExitBB)) { 499 LLVM_DEBUG(dbgs() << " Branch doesn't exit the loop!\n"); 500 return false; 501 } 502 } 503 auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx); 504 auto *ParentBB = BI.getParent(); 505 if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) { 506 LLVM_DEBUG(dbgs() << " Loop exit PHI's aren't loop-invariant!\n"); 507 return false; 508 } 509 510 // When unswitching only part of the branch's condition, we need the exit 511 // block to be reached directly from the partially unswitched input. This can 512 // be done when the exit block is along the true edge and the branch condition 513 // is a graph of `or` operations, or the exit block is along the false edge 514 // and the condition is a graph of `and` operations. 515 if (!FullUnswitch) { 516 if (ExitDirection ? !match(Cond, m_LogicalOr()) 517 : !match(Cond, m_LogicalAnd())) { 518 LLVM_DEBUG(dbgs() << " Branch condition is in improper form for " 519 "non-full unswitch!\n"); 520 return false; 521 } 522 } 523 524 LLVM_DEBUG({ 525 dbgs() << " unswitching trivial invariant conditions for: " << BI 526 << "\n"; 527 for (Value *Invariant : Invariants) { 528 dbgs() << " " << *Invariant << " == true"; 529 if (Invariant != Invariants.back()) 530 dbgs() << " ||"; 531 dbgs() << "\n"; 532 } 533 }); 534 535 // If we have scalar evolutions, we need to invalidate them including this 536 // loop, the loop containing the exit block and the topmost parent loop 537 // exiting via LoopExitBB. 538 if (SE) { 539 if (const Loop *ExitL = getTopMostExitingLoop(LoopExitBB, LI)) 540 SE->forgetLoop(ExitL); 541 else 542 // Forget the entire nest as this exits the entire nest. 543 SE->forgetTopmostLoop(&L); 544 } 545 546 if (MSSAU && VerifyMemorySSA) 547 MSSAU->getMemorySSA()->verifyMemorySSA(); 548 549 // Split the preheader, so that we know that there is a safe place to insert 550 // the conditional branch. We will change the preheader to have a conditional 551 // branch on LoopCond. 552 BasicBlock *OldPH = L.getLoopPreheader(); 553 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU); 554 555 // Now that we have a place to insert the conditional branch, create a place 556 // to branch to: this is the exit block out of the loop that we are 557 // unswitching. We need to split this if there are other loop predecessors. 558 // Because the loop is in simplified form, *any* other predecessor is enough. 559 BasicBlock *UnswitchedBB; 560 if (FullUnswitch && LoopExitBB->getUniquePredecessor()) { 561 assert(LoopExitBB->getUniquePredecessor() == BI.getParent() && 562 "A branch's parent isn't a predecessor!"); 563 UnswitchedBB = LoopExitBB; 564 } else { 565 UnswitchedBB = 566 SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU); 567 } 568 569 if (MSSAU && VerifyMemorySSA) 570 MSSAU->getMemorySSA()->verifyMemorySSA(); 571 572 // Actually move the invariant uses into the unswitched position. If possible, 573 // we do this by moving the instructions, but when doing partial unswitching 574 // we do it by building a new merge of the values in the unswitched position. 575 OldPH->getTerminator()->eraseFromParent(); 576 if (FullUnswitch) { 577 // If fully unswitching, we can use the existing branch instruction. 578 // Splice it into the old PH to gate reaching the new preheader and re-point 579 // its successors. 580 OldPH->getInstList().splice(OldPH->end(), BI.getParent()->getInstList(), 581 BI); 582 BI.setCondition(Cond); 583 if (MSSAU) { 584 // Temporarily clone the terminator, to make MSSA update cheaper by 585 // separating "insert edge" updates from "remove edge" ones. 586 ParentBB->getInstList().push_back(BI.clone()); 587 } else { 588 // Create a new unconditional branch that will continue the loop as a new 589 // terminator. 590 BranchInst::Create(ContinueBB, ParentBB); 591 } 592 BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB); 593 BI.setSuccessor(1 - LoopExitSuccIdx, NewPH); 594 } else { 595 // Only unswitching a subset of inputs to the condition, so we will need to 596 // build a new branch that merges the invariant inputs. 597 if (ExitDirection) 598 assert(match(skipTrivialSelect(BI.getCondition()), m_LogicalOr()) && 599 "Must have an `or` of `i1`s or `select i1 X, true, Y`s for the " 600 "condition!"); 601 else 602 assert(match(skipTrivialSelect(BI.getCondition()), m_LogicalAnd()) && 603 "Must have an `and` of `i1`s or `select i1 X, Y, false`s for the" 604 " condition!"); 605 buildPartialUnswitchConditionalBranch( 606 *OldPH, Invariants, ExitDirection, *UnswitchedBB, *NewPH, 607 FreezeLoopUnswitchCond, OldPH->getTerminator(), nullptr, DT); 608 } 609 610 // Update the dominator tree with the added edge. 611 DT.insertEdge(OldPH, UnswitchedBB); 612 613 // After the dominator tree was updated with the added edge, update MemorySSA 614 // if available. 615 if (MSSAU) { 616 SmallVector<CFGUpdate, 1> Updates; 617 Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB}); 618 MSSAU->applyInsertUpdates(Updates, DT); 619 } 620 621 // Finish updating dominator tree and memory ssa for full unswitch. 622 if (FullUnswitch) { 623 if (MSSAU) { 624 // Remove the cloned branch instruction. 625 ParentBB->getTerminator()->eraseFromParent(); 626 // Create unconditional branch now. 627 BranchInst::Create(ContinueBB, ParentBB); 628 MSSAU->removeEdge(ParentBB, LoopExitBB); 629 } 630 DT.deleteEdge(ParentBB, LoopExitBB); 631 } 632 633 if (MSSAU && VerifyMemorySSA) 634 MSSAU->getMemorySSA()->verifyMemorySSA(); 635 636 // Rewrite the relevant PHI nodes. 637 if (UnswitchedBB == LoopExitBB) 638 rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH); 639 else 640 rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB, 641 *ParentBB, *OldPH, FullUnswitch); 642 643 // The constant we can replace all of our invariants with inside the loop 644 // body. If any of the invariants have a value other than this the loop won't 645 // be entered. 646 ConstantInt *Replacement = ExitDirection 647 ? ConstantInt::getFalse(BI.getContext()) 648 : ConstantInt::getTrue(BI.getContext()); 649 650 // Since this is an i1 condition we can also trivially replace uses of it 651 // within the loop with a constant. 652 for (Value *Invariant : Invariants) 653 replaceLoopInvariantUses(L, Invariant, *Replacement); 654 655 // If this was full unswitching, we may have changed the nesting relationship 656 // for this loop so hoist it to its correct parent if needed. 657 if (FullUnswitch) 658 hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE); 659 660 if (MSSAU && VerifyMemorySSA) 661 MSSAU->getMemorySSA()->verifyMemorySSA(); 662 663 LLVM_DEBUG(dbgs() << " done: unswitching trivial branch...\n"); 664 ++NumTrivial; 665 ++NumBranches; 666 return true; 667 } 668 669 /// Unswitch a trivial switch if the condition is loop invariant. 670 /// 671 /// This routine should only be called when loop code leading to the switch has 672 /// been validated as trivial (no side effects). This routine checks if the 673 /// condition is invariant and that at least one of the successors is a loop 674 /// exit. This allows us to unswitch without duplicating the loop, making it 675 /// trivial. 676 /// 677 /// If this routine fails to unswitch the switch it returns false. 678 /// 679 /// If the switch can be unswitched, this routine splits the preheader and 680 /// copies the switch above that split. If the default case is one of the 681 /// exiting cases, it copies the non-exiting cases and points them at the new 682 /// preheader. If the default case is not exiting, it copies the exiting cases 683 /// and points the default at the preheader. It preserves loop simplified form 684 /// (splitting the exit blocks as necessary). It simplifies the switch within 685 /// the loop by removing now-dead cases. If the default case is one of those 686 /// unswitched, it replaces its destination with a new basic block containing 687 /// only unreachable. Such basic blocks, while technically loop exits, are not 688 /// considered for unswitching so this is a stable transform and the same 689 /// switch will not be revisited. If after unswitching there is only a single 690 /// in-loop successor, the switch is further simplified to an unconditional 691 /// branch. Still more cleanup can be done with some simplifycfg like pass. 692 /// 693 /// If `SE` is not null, it will be updated based on the potential loop SCEVs 694 /// invalidated by this. 695 static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, 696 LoopInfo &LI, ScalarEvolution *SE, 697 MemorySSAUpdater *MSSAU) { 698 LLVM_DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n"); 699 Value *LoopCond = SI.getCondition(); 700 701 // If this isn't switching on an invariant condition, we can't unswitch it. 702 if (!L.isLoopInvariant(LoopCond)) 703 return false; 704 705 auto *ParentBB = SI.getParent(); 706 707 // The same check must be used both for the default and the exit cases. We 708 // should never leave edges from the switch instruction to a basic block that 709 // we are unswitching, hence the condition used to determine the default case 710 // needs to also be used to populate ExitCaseIndices, which is then used to 711 // remove cases from the switch. 712 auto IsTriviallyUnswitchableExitBlock = [&](BasicBlock &BBToCheck) { 713 // BBToCheck is not an exit block if it is inside loop L. 714 if (L.contains(&BBToCheck)) 715 return false; 716 // BBToCheck is not trivial to unswitch if its phis aren't loop invariant. 717 if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, BBToCheck)) 718 return false; 719 // We do not unswitch a block that only has an unreachable statement, as 720 // it's possible this is a previously unswitched block. Only unswitch if 721 // either the terminator is not unreachable, or, if it is, it's not the only 722 // instruction in the block. 723 auto *TI = BBToCheck.getTerminator(); 724 bool isUnreachable = isa<UnreachableInst>(TI); 725 return !isUnreachable || 726 (isUnreachable && (BBToCheck.getFirstNonPHIOrDbg() != TI)); 727 }; 728 729 SmallVector<int, 4> ExitCaseIndices; 730 for (auto Case : SI.cases()) 731 if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor())) 732 ExitCaseIndices.push_back(Case.getCaseIndex()); 733 BasicBlock *DefaultExitBB = nullptr; 734 SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight = 735 SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0); 736 if (IsTriviallyUnswitchableExitBlock(*SI.getDefaultDest())) { 737 DefaultExitBB = SI.getDefaultDest(); 738 } else if (ExitCaseIndices.empty()) 739 return false; 740 741 LLVM_DEBUG(dbgs() << " unswitching trivial switch...\n"); 742 743 if (MSSAU && VerifyMemorySSA) 744 MSSAU->getMemorySSA()->verifyMemorySSA(); 745 746 // We may need to invalidate SCEVs for the outermost loop reached by any of 747 // the exits. 748 Loop *OuterL = &L; 749 750 if (DefaultExitBB) { 751 // Clear out the default destination temporarily to allow accurate 752 // predecessor lists to be examined below. 753 SI.setDefaultDest(nullptr); 754 // Check the loop containing this exit. 755 Loop *ExitL = LI.getLoopFor(DefaultExitBB); 756 if (!ExitL || ExitL->contains(OuterL)) 757 OuterL = ExitL; 758 } 759 760 // Store the exit cases into a separate data structure and remove them from 761 // the switch. 762 SmallVector<std::tuple<ConstantInt *, BasicBlock *, 763 SwitchInstProfUpdateWrapper::CaseWeightOpt>, 764 4> ExitCases; 765 ExitCases.reserve(ExitCaseIndices.size()); 766 SwitchInstProfUpdateWrapper SIW(SI); 767 // We walk the case indices backwards so that we remove the last case first 768 // and don't disrupt the earlier indices. 769 for (unsigned Index : reverse(ExitCaseIndices)) { 770 auto CaseI = SI.case_begin() + Index; 771 // Compute the outer loop from this exit. 772 Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor()); 773 if (!ExitL || ExitL->contains(OuterL)) 774 OuterL = ExitL; 775 // Save the value of this case. 776 auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex()); 777 ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W); 778 // Delete the unswitched cases. 779 SIW.removeCase(CaseI); 780 } 781 782 if (SE) { 783 if (OuterL) 784 SE->forgetLoop(OuterL); 785 else 786 SE->forgetTopmostLoop(&L); 787 } 788 789 // Check if after this all of the remaining cases point at the same 790 // successor. 791 BasicBlock *CommonSuccBB = nullptr; 792 if (SI.getNumCases() > 0 && 793 all_of(drop_begin(SI.cases()), [&SI](const SwitchInst::CaseHandle &Case) { 794 return Case.getCaseSuccessor() == SI.case_begin()->getCaseSuccessor(); 795 })) 796 CommonSuccBB = SI.case_begin()->getCaseSuccessor(); 797 if (!DefaultExitBB) { 798 // If we're not unswitching the default, we need it to match any cases to 799 // have a common successor or if we have no cases it is the common 800 // successor. 801 if (SI.getNumCases() == 0) 802 CommonSuccBB = SI.getDefaultDest(); 803 else if (SI.getDefaultDest() != CommonSuccBB) 804 CommonSuccBB = nullptr; 805 } 806 807 // Split the preheader, so that we know that there is a safe place to insert 808 // the switch. 809 BasicBlock *OldPH = L.getLoopPreheader(); 810 BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU); 811 OldPH->getTerminator()->eraseFromParent(); 812 813 // Now add the unswitched switch. 814 auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH); 815 SwitchInstProfUpdateWrapper NewSIW(*NewSI); 816 817 // Rewrite the IR for the unswitched basic blocks. This requires two steps. 818 // First, we split any exit blocks with remaining in-loop predecessors. Then 819 // we update the PHIs in one of two ways depending on if there was a split. 820 // We walk in reverse so that we split in the same order as the cases 821 // appeared. This is purely for convenience of reading the resulting IR, but 822 // it doesn't cost anything really. 823 SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs; 824 SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap; 825 // Handle the default exit if necessary. 826 // FIXME: It'd be great if we could merge this with the loop below but LLVM's 827 // ranges aren't quite powerful enough yet. 828 if (DefaultExitBB) { 829 if (pred_empty(DefaultExitBB)) { 830 UnswitchedExitBBs.insert(DefaultExitBB); 831 rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH); 832 } else { 833 auto *SplitBB = 834 SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU); 835 rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB, 836 *ParentBB, *OldPH, 837 /*FullUnswitch*/ true); 838 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB; 839 } 840 } 841 // Note that we must use a reference in the for loop so that we update the 842 // container. 843 for (auto &ExitCase : reverse(ExitCases)) { 844 // Grab a reference to the exit block in the pair so that we can update it. 845 BasicBlock *ExitBB = std::get<1>(ExitCase); 846 847 // If this case is the last edge into the exit block, we can simply reuse it 848 // as it will no longer be a loop exit. No mapping necessary. 849 if (pred_empty(ExitBB)) { 850 // Only rewrite once. 851 if (UnswitchedExitBBs.insert(ExitBB).second) 852 rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH); 853 continue; 854 } 855 856 // Otherwise we need to split the exit block so that we retain an exit 857 // block from the loop and a target for the unswitched condition. 858 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB]; 859 if (!SplitExitBB) { 860 // If this is the first time we see this, do the split and remember it. 861 SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU); 862 rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB, 863 *ParentBB, *OldPH, 864 /*FullUnswitch*/ true); 865 } 866 // Update the case pair to point to the split block. 867 std::get<1>(ExitCase) = SplitExitBB; 868 } 869 870 // Now add the unswitched cases. We do this in reverse order as we built them 871 // in reverse order. 872 for (auto &ExitCase : reverse(ExitCases)) { 873 ConstantInt *CaseVal = std::get<0>(ExitCase); 874 BasicBlock *UnswitchedBB = std::get<1>(ExitCase); 875 876 NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase)); 877 } 878 879 // If the default was unswitched, re-point it and add explicit cases for 880 // entering the loop. 881 if (DefaultExitBB) { 882 NewSIW->setDefaultDest(DefaultExitBB); 883 NewSIW.setSuccessorWeight(0, DefaultCaseWeight); 884 885 // We removed all the exit cases, so we just copy the cases to the 886 // unswitched switch. 887 for (const auto &Case : SI.cases()) 888 NewSIW.addCase(Case.getCaseValue(), NewPH, 889 SIW.getSuccessorWeight(Case.getSuccessorIndex())); 890 } else if (DefaultCaseWeight) { 891 // We have to set branch weight of the default case. 892 uint64_t SW = *DefaultCaseWeight; 893 for (const auto &Case : SI.cases()) { 894 auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex()); 895 assert(W && 896 "case weight must be defined as default case weight is defined"); 897 SW += *W; 898 } 899 NewSIW.setSuccessorWeight(0, SW); 900 } 901 902 // If we ended up with a common successor for every path through the switch 903 // after unswitching, rewrite it to an unconditional branch to make it easy 904 // to recognize. Otherwise we potentially have to recognize the default case 905 // pointing at unreachable and other complexity. 906 if (CommonSuccBB) { 907 BasicBlock *BB = SI.getParent(); 908 // We may have had multiple edges to this common successor block, so remove 909 // them as predecessors. We skip the first one, either the default or the 910 // actual first case. 911 bool SkippedFirst = DefaultExitBB == nullptr; 912 for (auto Case : SI.cases()) { 913 assert(Case.getCaseSuccessor() == CommonSuccBB && 914 "Non-common successor!"); 915 (void)Case; 916 if (!SkippedFirst) { 917 SkippedFirst = true; 918 continue; 919 } 920 CommonSuccBB->removePredecessor(BB, 921 /*KeepOneInputPHIs*/ true); 922 } 923 // Now nuke the switch and replace it with a direct branch. 924 SIW.eraseFromParent(); 925 BranchInst::Create(CommonSuccBB, BB); 926 } else if (DefaultExitBB) { 927 assert(SI.getNumCases() > 0 && 928 "If we had no cases we'd have a common successor!"); 929 // Move the last case to the default successor. This is valid as if the 930 // default got unswitched it cannot be reached. This has the advantage of 931 // being simple and keeping the number of edges from this switch to 932 // successors the same, and avoiding any PHI update complexity. 933 auto LastCaseI = std::prev(SI.case_end()); 934 935 SI.setDefaultDest(LastCaseI->getCaseSuccessor()); 936 SIW.setSuccessorWeight( 937 0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex())); 938 SIW.removeCase(LastCaseI); 939 } 940 941 // Walk the unswitched exit blocks and the unswitched split blocks and update 942 // the dominator tree based on the CFG edits. While we are walking unordered 943 // containers here, the API for applyUpdates takes an unordered list of 944 // updates and requires them to not contain duplicates. 945 SmallVector<DominatorTree::UpdateType, 4> DTUpdates; 946 for (auto *UnswitchedExitBB : UnswitchedExitBBs) { 947 DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB}); 948 DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB}); 949 } 950 for (auto SplitUnswitchedPair : SplitExitBBMap) { 951 DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first}); 952 DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second}); 953 } 954 955 if (MSSAU) { 956 MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true); 957 if (VerifyMemorySSA) 958 MSSAU->getMemorySSA()->verifyMemorySSA(); 959 } else { 960 DT.applyUpdates(DTUpdates); 961 } 962 963 assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 964 965 // We may have changed the nesting relationship for this loop so hoist it to 966 // its correct parent if needed. 967 hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE); 968 969 if (MSSAU && VerifyMemorySSA) 970 MSSAU->getMemorySSA()->verifyMemorySSA(); 971 972 ++NumTrivial; 973 ++NumSwitches; 974 LLVM_DEBUG(dbgs() << " done: unswitching trivial switch...\n"); 975 return true; 976 } 977 978 /// This routine scans the loop to find a branch or switch which occurs before 979 /// any side effects occur. These can potentially be unswitched without 980 /// duplicating the loop. If a branch or switch is successfully unswitched the 981 /// scanning continues to see if subsequent branches or switches have become 982 /// trivial. Once all trivial candidates have been unswitched, this routine 983 /// returns. 984 /// 985 /// The return value indicates whether anything was unswitched (and therefore 986 /// changed). 987 /// 988 /// If `SE` is not null, it will be updated based on the potential loop SCEVs 989 /// invalidated by this. 990 static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT, 991 LoopInfo &LI, ScalarEvolution *SE, 992 MemorySSAUpdater *MSSAU) { 993 bool Changed = false; 994 995 // If loop header has only one reachable successor we should keep looking for 996 // trivial condition candidates in the successor as well. An alternative is 997 // to constant fold conditions and merge successors into loop header (then we 998 // only need to check header's terminator). The reason for not doing this in 999 // LoopUnswitch pass is that it could potentially break LoopPassManager's 1000 // invariants. Folding dead branches could either eliminate the current loop 1001 // or make other loops unreachable. LCSSA form might also not be preserved 1002 // after deleting branches. The following code keeps traversing loop header's 1003 // successors until it finds the trivial condition candidate (condition that 1004 // is not a constant). Since unswitching generates branches with constant 1005 // conditions, this scenario could be very common in practice. 1006 BasicBlock *CurrentBB = L.getHeader(); 1007 SmallPtrSet<BasicBlock *, 8> Visited; 1008 Visited.insert(CurrentBB); 1009 do { 1010 // Check if there are any side-effecting instructions (e.g. stores, calls, 1011 // volatile loads) in the part of the loop that the code *would* execute 1012 // without unswitching. 1013 if (MSSAU) // Possible early exit with MSSA 1014 if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB)) 1015 if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end())) 1016 return Changed; 1017 if (llvm::any_of(*CurrentBB, 1018 [](Instruction &I) { return I.mayHaveSideEffects(); })) 1019 return Changed; 1020 1021 Instruction *CurrentTerm = CurrentBB->getTerminator(); 1022 1023 if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) { 1024 // Don't bother trying to unswitch past a switch with a constant 1025 // condition. This should be removed prior to running this pass by 1026 // simplifycfg. 1027 if (isa<Constant>(SI->getCondition())) 1028 return Changed; 1029 1030 if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU)) 1031 // Couldn't unswitch this one so we're done. 1032 return Changed; 1033 1034 // Mark that we managed to unswitch something. 1035 Changed = true; 1036 1037 // If unswitching turned the terminator into an unconditional branch then 1038 // we can continue. The unswitching logic specifically works to fold any 1039 // cases it can into an unconditional branch to make it easier to 1040 // recognize here. 1041 auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator()); 1042 if (!BI || BI->isConditional()) 1043 return Changed; 1044 1045 CurrentBB = BI->getSuccessor(0); 1046 continue; 1047 } 1048 1049 auto *BI = dyn_cast<BranchInst>(CurrentTerm); 1050 if (!BI) 1051 // We do not understand other terminator instructions. 1052 return Changed; 1053 1054 // Don't bother trying to unswitch past an unconditional branch or a branch 1055 // with a constant value. These should be removed by simplifycfg prior to 1056 // running this pass. 1057 if (!BI->isConditional() || 1058 isa<Constant>(skipTrivialSelect(BI->getCondition()))) 1059 return Changed; 1060 1061 // Found a trivial condition candidate: non-foldable conditional branch. If 1062 // we fail to unswitch this, we can't do anything else that is trivial. 1063 if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU)) 1064 return Changed; 1065 1066 // Mark that we managed to unswitch something. 1067 Changed = true; 1068 1069 // If we only unswitched some of the conditions feeding the branch, we won't 1070 // have collapsed it to a single successor. 1071 BI = cast<BranchInst>(CurrentBB->getTerminator()); 1072 if (BI->isConditional()) 1073 return Changed; 1074 1075 // Follow the newly unconditional branch into its successor. 1076 CurrentBB = BI->getSuccessor(0); 1077 1078 // When continuing, if we exit the loop or reach a previous visited block, 1079 // then we can not reach any trivial condition candidates (unfoldable 1080 // branch instructions or switch instructions) and no unswitch can happen. 1081 } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second); 1082 1083 return Changed; 1084 } 1085 1086 /// Build the cloned blocks for an unswitched copy of the given loop. 1087 /// 1088 /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and 1089 /// after the split block (`SplitBB`) that will be used to select between the 1090 /// cloned and original loop. 1091 /// 1092 /// This routine handles cloning all of the necessary loop blocks and exit 1093 /// blocks including rewriting their instructions and the relevant PHI nodes. 1094 /// Any loop blocks or exit blocks which are dominated by a different successor 1095 /// than the one for this clone of the loop blocks can be trivially skipped. We 1096 /// use the `DominatingSucc` map to determine whether a block satisfies that 1097 /// property with a simple map lookup. 1098 /// 1099 /// It also correctly creates the unconditional branch in the cloned 1100 /// unswitched parent block to only point at the unswitched successor. 1101 /// 1102 /// This does not handle most of the necessary updates to `LoopInfo`. Only exit 1103 /// block splitting is correctly reflected in `LoopInfo`, essentially all of 1104 /// the cloned blocks (and their loops) are left without full `LoopInfo` 1105 /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned 1106 /// blocks to them but doesn't create the cloned `DominatorTree` structure and 1107 /// instead the caller must recompute an accurate DT. It *does* correctly 1108 /// update the `AssumptionCache` provided in `AC`. 1109 static BasicBlock *buildClonedLoopBlocks( 1110 Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB, 1111 ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB, 1112 BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB, 1113 const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc, 1114 ValueToValueMapTy &VMap, 1115 SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC, 1116 DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU) { 1117 SmallVector<BasicBlock *, 4> NewBlocks; 1118 NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size()); 1119 1120 // We will need to clone a bunch of blocks, wrap up the clone operation in 1121 // a helper. 1122 auto CloneBlock = [&](BasicBlock *OldBB) { 1123 // Clone the basic block and insert it before the new preheader. 1124 BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent()); 1125 NewBB->moveBefore(LoopPH); 1126 1127 // Record this block and the mapping. 1128 NewBlocks.push_back(NewBB); 1129 VMap[OldBB] = NewBB; 1130 1131 return NewBB; 1132 }; 1133 1134 // We skip cloning blocks when they have a dominating succ that is not the 1135 // succ we are cloning for. 1136 auto SkipBlock = [&](BasicBlock *BB) { 1137 auto It = DominatingSucc.find(BB); 1138 return It != DominatingSucc.end() && It->second != UnswitchedSuccBB; 1139 }; 1140 1141 // First, clone the preheader. 1142 auto *ClonedPH = CloneBlock(LoopPH); 1143 1144 // Then clone all the loop blocks, skipping the ones that aren't necessary. 1145 for (auto *LoopBB : L.blocks()) 1146 if (!SkipBlock(LoopBB)) 1147 CloneBlock(LoopBB); 1148 1149 // Split all the loop exit edges so that when we clone the exit blocks, if 1150 // any of the exit blocks are *also* a preheader for some other loop, we 1151 // don't create multiple predecessors entering the loop header. 1152 for (auto *ExitBB : ExitBlocks) { 1153 if (SkipBlock(ExitBB)) 1154 continue; 1155 1156 // When we are going to clone an exit, we don't need to clone all the 1157 // instructions in the exit block and we want to ensure we have an easy 1158 // place to merge the CFG, so split the exit first. This is always safe to 1159 // do because there cannot be any non-loop predecessors of a loop exit in 1160 // loop simplified form. 1161 auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU); 1162 1163 // Rearrange the names to make it easier to write test cases by having the 1164 // exit block carry the suffix rather than the merge block carrying the 1165 // suffix. 1166 MergeBB->takeName(ExitBB); 1167 ExitBB->setName(Twine(MergeBB->getName()) + ".split"); 1168 1169 // Now clone the original exit block. 1170 auto *ClonedExitBB = CloneBlock(ExitBB); 1171 assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 && 1172 "Exit block should have been split to have one successor!"); 1173 assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB && 1174 "Cloned exit block has the wrong successor!"); 1175 1176 // Remap any cloned instructions and create a merge phi node for them. 1177 for (auto ZippedInsts : llvm::zip_first( 1178 llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())), 1179 llvm::make_range(ClonedExitBB->begin(), 1180 std::prev(ClonedExitBB->end())))) { 1181 Instruction &I = std::get<0>(ZippedInsts); 1182 Instruction &ClonedI = std::get<1>(ZippedInsts); 1183 1184 // The only instructions in the exit block should be PHI nodes and 1185 // potentially a landing pad. 1186 assert( 1187 (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) && 1188 "Bad instruction in exit block!"); 1189 // We should have a value map between the instruction and its clone. 1190 assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!"); 1191 1192 auto *MergePN = 1193 PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi", 1194 &*MergeBB->getFirstInsertionPt()); 1195 I.replaceAllUsesWith(MergePN); 1196 MergePN->addIncoming(&I, ExitBB); 1197 MergePN->addIncoming(&ClonedI, ClonedExitBB); 1198 } 1199 } 1200 1201 // Rewrite the instructions in the cloned blocks to refer to the instructions 1202 // in the cloned blocks. We have to do this as a second pass so that we have 1203 // everything available. Also, we have inserted new instructions which may 1204 // include assume intrinsics, so we update the assumption cache while 1205 // processing this. 1206 for (auto *ClonedBB : NewBlocks) 1207 for (Instruction &I : *ClonedBB) { 1208 RemapInstruction(&I, VMap, 1209 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 1210 if (auto *II = dyn_cast<AssumeInst>(&I)) 1211 AC.registerAssumption(II); 1212 } 1213 1214 // Update any PHI nodes in the cloned successors of the skipped blocks to not 1215 // have spurious incoming values. 1216 for (auto *LoopBB : L.blocks()) 1217 if (SkipBlock(LoopBB)) 1218 for (auto *SuccBB : successors(LoopBB)) 1219 if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB))) 1220 for (PHINode &PN : ClonedSuccBB->phis()) 1221 PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false); 1222 1223 // Remove the cloned parent as a predecessor of any successor we ended up 1224 // cloning other than the unswitched one. 1225 auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB)); 1226 for (auto *SuccBB : successors(ParentBB)) { 1227 if (SuccBB == UnswitchedSuccBB) 1228 continue; 1229 1230 auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)); 1231 if (!ClonedSuccBB) 1232 continue; 1233 1234 ClonedSuccBB->removePredecessor(ClonedParentBB, 1235 /*KeepOneInputPHIs*/ true); 1236 } 1237 1238 // Replace the cloned branch with an unconditional branch to the cloned 1239 // unswitched successor. 1240 auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB)); 1241 Instruction *ClonedTerminator = ClonedParentBB->getTerminator(); 1242 // Trivial Simplification. If Terminator is a conditional branch and 1243 // condition becomes dead - erase it. 1244 Value *ClonedConditionToErase = nullptr; 1245 if (auto *BI = dyn_cast<BranchInst>(ClonedTerminator)) 1246 ClonedConditionToErase = BI->getCondition(); 1247 else if (auto *SI = dyn_cast<SwitchInst>(ClonedTerminator)) 1248 ClonedConditionToErase = SI->getCondition(); 1249 1250 ClonedTerminator->eraseFromParent(); 1251 BranchInst::Create(ClonedSuccBB, ClonedParentBB); 1252 1253 if (ClonedConditionToErase) 1254 RecursivelyDeleteTriviallyDeadInstructions(ClonedConditionToErase, nullptr, 1255 MSSAU); 1256 1257 // If there are duplicate entries in the PHI nodes because of multiple edges 1258 // to the unswitched successor, we need to nuke all but one as we replaced it 1259 // with a direct branch. 1260 for (PHINode &PN : ClonedSuccBB->phis()) { 1261 bool Found = false; 1262 // Loop over the incoming operands backwards so we can easily delete as we 1263 // go without invalidating the index. 1264 for (int i = PN.getNumOperands() - 1; i >= 0; --i) { 1265 if (PN.getIncomingBlock(i) != ClonedParentBB) 1266 continue; 1267 if (!Found) { 1268 Found = true; 1269 continue; 1270 } 1271 PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false); 1272 } 1273 } 1274 1275 // Record the domtree updates for the new blocks. 1276 SmallPtrSet<BasicBlock *, 4> SuccSet; 1277 for (auto *ClonedBB : NewBlocks) { 1278 for (auto *SuccBB : successors(ClonedBB)) 1279 if (SuccSet.insert(SuccBB).second) 1280 DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB}); 1281 SuccSet.clear(); 1282 } 1283 1284 return ClonedPH; 1285 } 1286 1287 /// Recursively clone the specified loop and all of its children. 1288 /// 1289 /// The target parent loop for the clone should be provided, or can be null if 1290 /// the clone is a top-level loop. While cloning, all the blocks are mapped 1291 /// with the provided value map. The entire original loop must be present in 1292 /// the value map. The cloned loop is returned. 1293 static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL, 1294 const ValueToValueMapTy &VMap, LoopInfo &LI) { 1295 auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) { 1296 assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!"); 1297 ClonedL.reserveBlocks(OrigL.getNumBlocks()); 1298 for (auto *BB : OrigL.blocks()) { 1299 auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB)); 1300 ClonedL.addBlockEntry(ClonedBB); 1301 if (LI.getLoopFor(BB) == &OrigL) 1302 LI.changeLoopFor(ClonedBB, &ClonedL); 1303 } 1304 }; 1305 1306 // We specially handle the first loop because it may get cloned into 1307 // a different parent and because we most commonly are cloning leaf loops. 1308 Loop *ClonedRootL = LI.AllocateLoop(); 1309 if (RootParentL) 1310 RootParentL->addChildLoop(ClonedRootL); 1311 else 1312 LI.addTopLevelLoop(ClonedRootL); 1313 AddClonedBlocksToLoop(OrigRootL, *ClonedRootL); 1314 1315 if (OrigRootL.isInnermost()) 1316 return ClonedRootL; 1317 1318 // If we have a nest, we can quickly clone the entire loop nest using an 1319 // iterative approach because it is a tree. We keep the cloned parent in the 1320 // data structure to avoid repeatedly querying through a map to find it. 1321 SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone; 1322 // Build up the loops to clone in reverse order as we'll clone them from the 1323 // back. 1324 for (Loop *ChildL : llvm::reverse(OrigRootL)) 1325 LoopsToClone.push_back({ClonedRootL, ChildL}); 1326 do { 1327 Loop *ClonedParentL, *L; 1328 std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val(); 1329 Loop *ClonedL = LI.AllocateLoop(); 1330 ClonedParentL->addChildLoop(ClonedL); 1331 AddClonedBlocksToLoop(*L, *ClonedL); 1332 for (Loop *ChildL : llvm::reverse(*L)) 1333 LoopsToClone.push_back({ClonedL, ChildL}); 1334 } while (!LoopsToClone.empty()); 1335 1336 return ClonedRootL; 1337 } 1338 1339 /// Build the cloned loops of an original loop from unswitching. 1340 /// 1341 /// Because unswitching simplifies the CFG of the loop, this isn't a trivial 1342 /// operation. We need to re-verify that there even is a loop (as the backedge 1343 /// may not have been cloned), and even if there are remaining backedges the 1344 /// backedge set may be different. However, we know that each child loop is 1345 /// undisturbed, we only need to find where to place each child loop within 1346 /// either any parent loop or within a cloned version of the original loop. 1347 /// 1348 /// Because child loops may end up cloned outside of any cloned version of the 1349 /// original loop, multiple cloned sibling loops may be created. All of them 1350 /// are returned so that the newly introduced loop nest roots can be 1351 /// identified. 1352 static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks, 1353 const ValueToValueMapTy &VMap, LoopInfo &LI, 1354 SmallVectorImpl<Loop *> &NonChildClonedLoops) { 1355 Loop *ClonedL = nullptr; 1356 1357 auto *OrigPH = OrigL.getLoopPreheader(); 1358 auto *OrigHeader = OrigL.getHeader(); 1359 1360 auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH)); 1361 auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader)); 1362 1363 // We need to know the loops of the cloned exit blocks to even compute the 1364 // accurate parent loop. If we only clone exits to some parent of the 1365 // original parent, we want to clone into that outer loop. We also keep track 1366 // of the loops that our cloned exit blocks participate in. 1367 Loop *ParentL = nullptr; 1368 SmallVector<BasicBlock *, 4> ClonedExitsInLoops; 1369 SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap; 1370 ClonedExitsInLoops.reserve(ExitBlocks.size()); 1371 for (auto *ExitBB : ExitBlocks) 1372 if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB))) 1373 if (Loop *ExitL = LI.getLoopFor(ExitBB)) { 1374 ExitLoopMap[ClonedExitBB] = ExitL; 1375 ClonedExitsInLoops.push_back(ClonedExitBB); 1376 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) 1377 ParentL = ExitL; 1378 } 1379 assert((!ParentL || ParentL == OrigL.getParentLoop() || 1380 ParentL->contains(OrigL.getParentLoop())) && 1381 "The computed parent loop should always contain (or be) the parent of " 1382 "the original loop."); 1383 1384 // We build the set of blocks dominated by the cloned header from the set of 1385 // cloned blocks out of the original loop. While not all of these will 1386 // necessarily be in the cloned loop, it is enough to establish that they 1387 // aren't in unreachable cycles, etc. 1388 SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks; 1389 for (auto *BB : OrigL.blocks()) 1390 if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB))) 1391 ClonedLoopBlocks.insert(ClonedBB); 1392 1393 // Rebuild the set of blocks that will end up in the cloned loop. We may have 1394 // skipped cloning some region of this loop which can in turn skip some of 1395 // the backedges so we have to rebuild the blocks in the loop based on the 1396 // backedges that remain after cloning. 1397 SmallVector<BasicBlock *, 16> Worklist; 1398 SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop; 1399 for (auto *Pred : predecessors(ClonedHeader)) { 1400 // The only possible non-loop header predecessor is the preheader because 1401 // we know we cloned the loop in simplified form. 1402 if (Pred == ClonedPH) 1403 continue; 1404 1405 // Because the loop was in simplified form, the only non-loop predecessor 1406 // should be the preheader. 1407 assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop " 1408 "header other than the preheader " 1409 "that is not part of the loop!"); 1410 1411 // Insert this block into the loop set and on the first visit (and if it 1412 // isn't the header we're currently walking) put it into the worklist to 1413 // recurse through. 1414 if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader) 1415 Worklist.push_back(Pred); 1416 } 1417 1418 // If we had any backedges then there *is* a cloned loop. Put the header into 1419 // the loop set and then walk the worklist backwards to find all the blocks 1420 // that remain within the loop after cloning. 1421 if (!BlocksInClonedLoop.empty()) { 1422 BlocksInClonedLoop.insert(ClonedHeader); 1423 1424 while (!Worklist.empty()) { 1425 BasicBlock *BB = Worklist.pop_back_val(); 1426 assert(BlocksInClonedLoop.count(BB) && 1427 "Didn't put block into the loop set!"); 1428 1429 // Insert any predecessors that are in the possible set into the cloned 1430 // set, and if the insert is successful, add them to the worklist. Note 1431 // that we filter on the blocks that are definitely reachable via the 1432 // backedge to the loop header so we may prune out dead code within the 1433 // cloned loop. 1434 for (auto *Pred : predecessors(BB)) 1435 if (ClonedLoopBlocks.count(Pred) && 1436 BlocksInClonedLoop.insert(Pred).second) 1437 Worklist.push_back(Pred); 1438 } 1439 1440 ClonedL = LI.AllocateLoop(); 1441 if (ParentL) { 1442 ParentL->addBasicBlockToLoop(ClonedPH, LI); 1443 ParentL->addChildLoop(ClonedL); 1444 } else { 1445 LI.addTopLevelLoop(ClonedL); 1446 } 1447 NonChildClonedLoops.push_back(ClonedL); 1448 1449 ClonedL->reserveBlocks(BlocksInClonedLoop.size()); 1450 // We don't want to just add the cloned loop blocks based on how we 1451 // discovered them. The original order of blocks was carefully built in 1452 // a way that doesn't rely on predecessor ordering. Rather than re-invent 1453 // that logic, we just re-walk the original blocks (and those of the child 1454 // loops) and filter them as we add them into the cloned loop. 1455 for (auto *BB : OrigL.blocks()) { 1456 auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)); 1457 if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB)) 1458 continue; 1459 1460 // Directly add the blocks that are only in this loop. 1461 if (LI.getLoopFor(BB) == &OrigL) { 1462 ClonedL->addBasicBlockToLoop(ClonedBB, LI); 1463 continue; 1464 } 1465 1466 // We want to manually add it to this loop and parents. 1467 // Registering it with LoopInfo will happen when we clone the top 1468 // loop for this block. 1469 for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop()) 1470 PL->addBlockEntry(ClonedBB); 1471 } 1472 1473 // Now add each child loop whose header remains within the cloned loop. All 1474 // of the blocks within the loop must satisfy the same constraints as the 1475 // header so once we pass the header checks we can just clone the entire 1476 // child loop nest. 1477 for (Loop *ChildL : OrigL) { 1478 auto *ClonedChildHeader = 1479 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); 1480 if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader)) 1481 continue; 1482 1483 #ifndef NDEBUG 1484 // We should never have a cloned child loop header but fail to have 1485 // all of the blocks for that child loop. 1486 for (auto *ChildLoopBB : ChildL->blocks()) 1487 assert(BlocksInClonedLoop.count( 1488 cast<BasicBlock>(VMap.lookup(ChildLoopBB))) && 1489 "Child cloned loop has a header within the cloned outer " 1490 "loop but not all of its blocks!"); 1491 #endif 1492 1493 cloneLoopNest(*ChildL, ClonedL, VMap, LI); 1494 } 1495 } 1496 1497 // Now that we've handled all the components of the original loop that were 1498 // cloned into a new loop, we still need to handle anything from the original 1499 // loop that wasn't in a cloned loop. 1500 1501 // Figure out what blocks are left to place within any loop nest containing 1502 // the unswitched loop. If we never formed a loop, the cloned PH is one of 1503 // them. 1504 SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet; 1505 if (BlocksInClonedLoop.empty()) 1506 UnloopedBlockSet.insert(ClonedPH); 1507 for (auto *ClonedBB : ClonedLoopBlocks) 1508 if (!BlocksInClonedLoop.count(ClonedBB)) 1509 UnloopedBlockSet.insert(ClonedBB); 1510 1511 // Copy the cloned exits and sort them in ascending loop depth, we'll work 1512 // backwards across these to process them inside out. The order shouldn't 1513 // matter as we're just trying to build up the map from inside-out; we use 1514 // the map in a more stably ordered way below. 1515 auto OrderedClonedExitsInLoops = ClonedExitsInLoops; 1516 llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) { 1517 return ExitLoopMap.lookup(LHS)->getLoopDepth() < 1518 ExitLoopMap.lookup(RHS)->getLoopDepth(); 1519 }); 1520 1521 // Populate the existing ExitLoopMap with everything reachable from each 1522 // exit, starting from the inner most exit. 1523 while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) { 1524 assert(Worklist.empty() && "Didn't clear worklist!"); 1525 1526 BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val(); 1527 Loop *ExitL = ExitLoopMap.lookup(ExitBB); 1528 1529 // Walk the CFG back until we hit the cloned PH adding everything reachable 1530 // and in the unlooped set to this exit block's loop. 1531 Worklist.push_back(ExitBB); 1532 do { 1533 BasicBlock *BB = Worklist.pop_back_val(); 1534 // We can stop recursing at the cloned preheader (if we get there). 1535 if (BB == ClonedPH) 1536 continue; 1537 1538 for (BasicBlock *PredBB : predecessors(BB)) { 1539 // If this pred has already been moved to our set or is part of some 1540 // (inner) loop, no update needed. 1541 if (!UnloopedBlockSet.erase(PredBB)) { 1542 assert( 1543 (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) && 1544 "Predecessor not mapped to a loop!"); 1545 continue; 1546 } 1547 1548 // We just insert into the loop set here. We'll add these blocks to the 1549 // exit loop after we build up the set in an order that doesn't rely on 1550 // predecessor order (which in turn relies on use list order). 1551 bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second; 1552 (void)Inserted; 1553 assert(Inserted && "Should only visit an unlooped block once!"); 1554 1555 // And recurse through to its predecessors. 1556 Worklist.push_back(PredBB); 1557 } 1558 } while (!Worklist.empty()); 1559 } 1560 1561 // Now that the ExitLoopMap gives as mapping for all the non-looping cloned 1562 // blocks to their outer loops, walk the cloned blocks and the cloned exits 1563 // in their original order adding them to the correct loop. 1564 1565 // We need a stable insertion order. We use the order of the original loop 1566 // order and map into the correct parent loop. 1567 for (auto *BB : llvm::concat<BasicBlock *const>( 1568 makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops)) 1569 if (Loop *OuterL = ExitLoopMap.lookup(BB)) 1570 OuterL->addBasicBlockToLoop(BB, LI); 1571 1572 #ifndef NDEBUG 1573 for (auto &BBAndL : ExitLoopMap) { 1574 auto *BB = BBAndL.first; 1575 auto *OuterL = BBAndL.second; 1576 assert(LI.getLoopFor(BB) == OuterL && 1577 "Failed to put all blocks into outer loops!"); 1578 } 1579 #endif 1580 1581 // Now that all the blocks are placed into the correct containing loop in the 1582 // absence of child loops, find all the potentially cloned child loops and 1583 // clone them into whatever outer loop we placed their header into. 1584 for (Loop *ChildL : OrigL) { 1585 auto *ClonedChildHeader = 1586 cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); 1587 if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader)) 1588 continue; 1589 1590 #ifndef NDEBUG 1591 for (auto *ChildLoopBB : ChildL->blocks()) 1592 assert(VMap.count(ChildLoopBB) && 1593 "Cloned a child loop header but not all of that loops blocks!"); 1594 #endif 1595 1596 NonChildClonedLoops.push_back(cloneLoopNest( 1597 *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI)); 1598 } 1599 } 1600 1601 static void 1602 deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks, 1603 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, 1604 DominatorTree &DT, MemorySSAUpdater *MSSAU) { 1605 // Find all the dead clones, and remove them from their successors. 1606 SmallVector<BasicBlock *, 16> DeadBlocks; 1607 for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks)) 1608 for (const auto &VMap : VMaps) 1609 if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB))) 1610 if (!DT.isReachableFromEntry(ClonedBB)) { 1611 for (BasicBlock *SuccBB : successors(ClonedBB)) 1612 SuccBB->removePredecessor(ClonedBB); 1613 DeadBlocks.push_back(ClonedBB); 1614 } 1615 1616 // Remove all MemorySSA in the dead blocks 1617 if (MSSAU) { 1618 SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(), 1619 DeadBlocks.end()); 1620 MSSAU->removeBlocks(DeadBlockSet); 1621 } 1622 1623 // Drop any remaining references to break cycles. 1624 for (BasicBlock *BB : DeadBlocks) 1625 BB->dropAllReferences(); 1626 // Erase them from the IR. 1627 for (BasicBlock *BB : DeadBlocks) 1628 BB->eraseFromParent(); 1629 } 1630 1631 static void 1632 deleteDeadBlocksFromLoop(Loop &L, 1633 SmallVectorImpl<BasicBlock *> &ExitBlocks, 1634 DominatorTree &DT, LoopInfo &LI, 1635 MemorySSAUpdater *MSSAU, 1636 ScalarEvolution *SE, 1637 function_ref<void(Loop &, StringRef)> DestroyLoopCB) { 1638 // Find all the dead blocks tied to this loop, and remove them from their 1639 // successors. 1640 SmallSetVector<BasicBlock *, 8> DeadBlockSet; 1641 1642 // Start with loop/exit blocks and get a transitive closure of reachable dead 1643 // blocks. 1644 SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(), 1645 ExitBlocks.end()); 1646 DeathCandidates.append(L.blocks().begin(), L.blocks().end()); 1647 while (!DeathCandidates.empty()) { 1648 auto *BB = DeathCandidates.pop_back_val(); 1649 if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) { 1650 for (BasicBlock *SuccBB : successors(BB)) { 1651 SuccBB->removePredecessor(BB); 1652 DeathCandidates.push_back(SuccBB); 1653 } 1654 DeadBlockSet.insert(BB); 1655 } 1656 } 1657 1658 // Remove all MemorySSA in the dead blocks 1659 if (MSSAU) 1660 MSSAU->removeBlocks(DeadBlockSet); 1661 1662 // Filter out the dead blocks from the exit blocks list so that it can be 1663 // used in the caller. 1664 llvm::erase_if(ExitBlocks, 1665 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); }); 1666 1667 // Walk from this loop up through its parents removing all of the dead blocks. 1668 for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) { 1669 for (auto *BB : DeadBlockSet) 1670 ParentL->getBlocksSet().erase(BB); 1671 llvm::erase_if(ParentL->getBlocksVector(), 1672 [&](BasicBlock *BB) { return DeadBlockSet.count(BB); }); 1673 } 1674 1675 // Now delete the dead child loops. This raw delete will clear them 1676 // recursively. 1677 llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) { 1678 if (!DeadBlockSet.count(ChildL->getHeader())) 1679 return false; 1680 1681 assert(llvm::all_of(ChildL->blocks(), 1682 [&](BasicBlock *ChildBB) { 1683 return DeadBlockSet.count(ChildBB); 1684 }) && 1685 "If the child loop header is dead all blocks in the child loop must " 1686 "be dead as well!"); 1687 DestroyLoopCB(*ChildL, ChildL->getName()); 1688 if (SE) 1689 SE->forgetBlockAndLoopDispositions(); 1690 LI.destroy(ChildL); 1691 return true; 1692 }); 1693 1694 // Remove the loop mappings for the dead blocks and drop all the references 1695 // from these blocks to others to handle cyclic references as we start 1696 // deleting the blocks themselves. 1697 for (auto *BB : DeadBlockSet) { 1698 // Check that the dominator tree has already been updated. 1699 assert(!DT.getNode(BB) && "Should already have cleared domtree!"); 1700 LI.changeLoopFor(BB, nullptr); 1701 // Drop all uses of the instructions to make sure we won't have dangling 1702 // uses in other blocks. 1703 for (auto &I : *BB) 1704 if (!I.use_empty()) 1705 I.replaceAllUsesWith(PoisonValue::get(I.getType())); 1706 BB->dropAllReferences(); 1707 } 1708 1709 // Actually delete the blocks now that they've been fully unhooked from the 1710 // IR. 1711 for (auto *BB : DeadBlockSet) 1712 BB->eraseFromParent(); 1713 } 1714 1715 /// Recompute the set of blocks in a loop after unswitching. 1716 /// 1717 /// This walks from the original headers predecessors to rebuild the loop. We 1718 /// take advantage of the fact that new blocks can't have been added, and so we 1719 /// filter by the original loop's blocks. This also handles potentially 1720 /// unreachable code that we don't want to explore but might be found examining 1721 /// the predecessors of the header. 1722 /// 1723 /// If the original loop is no longer a loop, this will return an empty set. If 1724 /// it remains a loop, all the blocks within it will be added to the set 1725 /// (including those blocks in inner loops). 1726 static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L, 1727 LoopInfo &LI) { 1728 SmallPtrSet<const BasicBlock *, 16> LoopBlockSet; 1729 1730 auto *PH = L.getLoopPreheader(); 1731 auto *Header = L.getHeader(); 1732 1733 // A worklist to use while walking backwards from the header. 1734 SmallVector<BasicBlock *, 16> Worklist; 1735 1736 // First walk the predecessors of the header to find the backedges. This will 1737 // form the basis of our walk. 1738 for (auto *Pred : predecessors(Header)) { 1739 // Skip the preheader. 1740 if (Pred == PH) 1741 continue; 1742 1743 // Because the loop was in simplified form, the only non-loop predecessor 1744 // is the preheader. 1745 assert(L.contains(Pred) && "Found a predecessor of the loop header other " 1746 "than the preheader that is not part of the " 1747 "loop!"); 1748 1749 // Insert this block into the loop set and on the first visit and, if it 1750 // isn't the header we're currently walking, put it into the worklist to 1751 // recurse through. 1752 if (LoopBlockSet.insert(Pred).second && Pred != Header) 1753 Worklist.push_back(Pred); 1754 } 1755 1756 // If no backedges were found, we're done. 1757 if (LoopBlockSet.empty()) 1758 return LoopBlockSet; 1759 1760 // We found backedges, recurse through them to identify the loop blocks. 1761 while (!Worklist.empty()) { 1762 BasicBlock *BB = Worklist.pop_back_val(); 1763 assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!"); 1764 1765 // No need to walk past the header. 1766 if (BB == Header) 1767 continue; 1768 1769 // Because we know the inner loop structure remains valid we can use the 1770 // loop structure to jump immediately across the entire nested loop. 1771 // Further, because it is in loop simplified form, we can directly jump 1772 // to its preheader afterward. 1773 if (Loop *InnerL = LI.getLoopFor(BB)) 1774 if (InnerL != &L) { 1775 assert(L.contains(InnerL) && 1776 "Should not reach a loop *outside* this loop!"); 1777 // The preheader is the only possible predecessor of the loop so 1778 // insert it into the set and check whether it was already handled. 1779 auto *InnerPH = InnerL->getLoopPreheader(); 1780 assert(L.contains(InnerPH) && "Cannot contain an inner loop block " 1781 "but not contain the inner loop " 1782 "preheader!"); 1783 if (!LoopBlockSet.insert(InnerPH).second) 1784 // The only way to reach the preheader is through the loop body 1785 // itself so if it has been visited the loop is already handled. 1786 continue; 1787 1788 // Insert all of the blocks (other than those already present) into 1789 // the loop set. We expect at least the block that led us to find the 1790 // inner loop to be in the block set, but we may also have other loop 1791 // blocks if they were already enqueued as predecessors of some other 1792 // outer loop block. 1793 for (auto *InnerBB : InnerL->blocks()) { 1794 if (InnerBB == BB) { 1795 assert(LoopBlockSet.count(InnerBB) && 1796 "Block should already be in the set!"); 1797 continue; 1798 } 1799 1800 LoopBlockSet.insert(InnerBB); 1801 } 1802 1803 // Add the preheader to the worklist so we will continue past the 1804 // loop body. 1805 Worklist.push_back(InnerPH); 1806 continue; 1807 } 1808 1809 // Insert any predecessors that were in the original loop into the new 1810 // set, and if the insert is successful, add them to the worklist. 1811 for (auto *Pred : predecessors(BB)) 1812 if (L.contains(Pred) && LoopBlockSet.insert(Pred).second) 1813 Worklist.push_back(Pred); 1814 } 1815 1816 assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!"); 1817 1818 // We've found all the blocks participating in the loop, return our completed 1819 // set. 1820 return LoopBlockSet; 1821 } 1822 1823 /// Rebuild a loop after unswitching removes some subset of blocks and edges. 1824 /// 1825 /// The removal may have removed some child loops entirely but cannot have 1826 /// disturbed any remaining child loops. However, they may need to be hoisted 1827 /// to the parent loop (or to be top-level loops). The original loop may be 1828 /// completely removed. 1829 /// 1830 /// The sibling loops resulting from this update are returned. If the original 1831 /// loop remains a valid loop, it will be the first entry in this list with all 1832 /// of the newly sibling loops following it. 1833 /// 1834 /// Returns true if the loop remains a loop after unswitching, and false if it 1835 /// is no longer a loop after unswitching (and should not continue to be 1836 /// referenced). 1837 static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks, 1838 LoopInfo &LI, 1839 SmallVectorImpl<Loop *> &HoistedLoops, 1840 ScalarEvolution *SE) { 1841 auto *PH = L.getLoopPreheader(); 1842 1843 // Compute the actual parent loop from the exit blocks. Because we may have 1844 // pruned some exits the loop may be different from the original parent. 1845 Loop *ParentL = nullptr; 1846 SmallVector<Loop *, 4> ExitLoops; 1847 SmallVector<BasicBlock *, 4> ExitsInLoops; 1848 ExitsInLoops.reserve(ExitBlocks.size()); 1849 for (auto *ExitBB : ExitBlocks) 1850 if (Loop *ExitL = LI.getLoopFor(ExitBB)) { 1851 ExitLoops.push_back(ExitL); 1852 ExitsInLoops.push_back(ExitBB); 1853 if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) 1854 ParentL = ExitL; 1855 } 1856 1857 // Recompute the blocks participating in this loop. This may be empty if it 1858 // is no longer a loop. 1859 auto LoopBlockSet = recomputeLoopBlockSet(L, LI); 1860 1861 // If we still have a loop, we need to re-set the loop's parent as the exit 1862 // block set changing may have moved it within the loop nest. Note that this 1863 // can only happen when this loop has a parent as it can only hoist the loop 1864 // *up* the nest. 1865 if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) { 1866 // Remove this loop's (original) blocks from all of the intervening loops. 1867 for (Loop *IL = L.getParentLoop(); IL != ParentL; 1868 IL = IL->getParentLoop()) { 1869 IL->getBlocksSet().erase(PH); 1870 for (auto *BB : L.blocks()) 1871 IL->getBlocksSet().erase(BB); 1872 llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) { 1873 return BB == PH || L.contains(BB); 1874 }); 1875 } 1876 1877 LI.changeLoopFor(PH, ParentL); 1878 L.getParentLoop()->removeChildLoop(&L); 1879 if (ParentL) 1880 ParentL->addChildLoop(&L); 1881 else 1882 LI.addTopLevelLoop(&L); 1883 } 1884 1885 // Now we update all the blocks which are no longer within the loop. 1886 auto &Blocks = L.getBlocksVector(); 1887 auto BlocksSplitI = 1888 LoopBlockSet.empty() 1889 ? Blocks.begin() 1890 : std::stable_partition( 1891 Blocks.begin(), Blocks.end(), 1892 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); }); 1893 1894 // Before we erase the list of unlooped blocks, build a set of them. 1895 SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end()); 1896 if (LoopBlockSet.empty()) 1897 UnloopedBlocks.insert(PH); 1898 1899 // Now erase these blocks from the loop. 1900 for (auto *BB : make_range(BlocksSplitI, Blocks.end())) 1901 L.getBlocksSet().erase(BB); 1902 Blocks.erase(BlocksSplitI, Blocks.end()); 1903 1904 // Sort the exits in ascending loop depth, we'll work backwards across these 1905 // to process them inside out. 1906 llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) { 1907 return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS); 1908 }); 1909 1910 // We'll build up a set for each exit loop. 1911 SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks; 1912 Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop. 1913 1914 auto RemoveUnloopedBlocksFromLoop = 1915 [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) { 1916 for (auto *BB : UnloopedBlocks) 1917 L.getBlocksSet().erase(BB); 1918 llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) { 1919 return UnloopedBlocks.count(BB); 1920 }); 1921 }; 1922 1923 SmallVector<BasicBlock *, 16> Worklist; 1924 while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) { 1925 assert(Worklist.empty() && "Didn't clear worklist!"); 1926 assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!"); 1927 1928 // Grab the next exit block, in decreasing loop depth order. 1929 BasicBlock *ExitBB = ExitsInLoops.pop_back_val(); 1930 Loop &ExitL = *LI.getLoopFor(ExitBB); 1931 assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!"); 1932 1933 // Erase all of the unlooped blocks from the loops between the previous 1934 // exit loop and this exit loop. This works because the ExitInLoops list is 1935 // sorted in increasing order of loop depth and thus we visit loops in 1936 // decreasing order of loop depth. 1937 for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop()) 1938 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); 1939 1940 // Walk the CFG back until we hit the cloned PH adding everything reachable 1941 // and in the unlooped set to this exit block's loop. 1942 Worklist.push_back(ExitBB); 1943 do { 1944 BasicBlock *BB = Worklist.pop_back_val(); 1945 // We can stop recursing at the cloned preheader (if we get there). 1946 if (BB == PH) 1947 continue; 1948 1949 for (BasicBlock *PredBB : predecessors(BB)) { 1950 // If this pred has already been moved to our set or is part of some 1951 // (inner) loop, no update needed. 1952 if (!UnloopedBlocks.erase(PredBB)) { 1953 assert((NewExitLoopBlocks.count(PredBB) || 1954 ExitL.contains(LI.getLoopFor(PredBB))) && 1955 "Predecessor not in a nested loop (or already visited)!"); 1956 continue; 1957 } 1958 1959 // We just insert into the loop set here. We'll add these blocks to the 1960 // exit loop after we build up the set in a deterministic order rather 1961 // than the predecessor-influenced visit order. 1962 bool Inserted = NewExitLoopBlocks.insert(PredBB).second; 1963 (void)Inserted; 1964 assert(Inserted && "Should only visit an unlooped block once!"); 1965 1966 // And recurse through to its predecessors. 1967 Worklist.push_back(PredBB); 1968 } 1969 } while (!Worklist.empty()); 1970 1971 // If blocks in this exit loop were directly part of the original loop (as 1972 // opposed to a child loop) update the map to point to this exit loop. This 1973 // just updates a map and so the fact that the order is unstable is fine. 1974 for (auto *BB : NewExitLoopBlocks) 1975 if (Loop *BBL = LI.getLoopFor(BB)) 1976 if (BBL == &L || !L.contains(BBL)) 1977 LI.changeLoopFor(BB, &ExitL); 1978 1979 // We will remove the remaining unlooped blocks from this loop in the next 1980 // iteration or below. 1981 NewExitLoopBlocks.clear(); 1982 } 1983 1984 // Any remaining unlooped blocks are no longer part of any loop unless they 1985 // are part of some child loop. 1986 for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop()) 1987 RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); 1988 for (auto *BB : UnloopedBlocks) 1989 if (Loop *BBL = LI.getLoopFor(BB)) 1990 if (BBL == &L || !L.contains(BBL)) 1991 LI.changeLoopFor(BB, nullptr); 1992 1993 // Sink all the child loops whose headers are no longer in the loop set to 1994 // the parent (or to be top level loops). We reach into the loop and directly 1995 // update its subloop vector to make this batch update efficient. 1996 auto &SubLoops = L.getSubLoopsVector(); 1997 auto SubLoopsSplitI = 1998 LoopBlockSet.empty() 1999 ? SubLoops.begin() 2000 : std::stable_partition( 2001 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) { 2002 return LoopBlockSet.count(SubL->getHeader()); 2003 }); 2004 for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) { 2005 HoistedLoops.push_back(HoistedL); 2006 HoistedL->setParentLoop(nullptr); 2007 2008 // To compute the new parent of this hoisted loop we look at where we 2009 // placed the preheader above. We can't lookup the header itself because we 2010 // retained the mapping from the header to the hoisted loop. But the 2011 // preheader and header should have the exact same new parent computed 2012 // based on the set of exit blocks from the original loop as the preheader 2013 // is a predecessor of the header and so reached in the reverse walk. And 2014 // because the loops were all in simplified form the preheader of the 2015 // hoisted loop can't be part of some *other* loop. 2016 if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader())) 2017 NewParentL->addChildLoop(HoistedL); 2018 else 2019 LI.addTopLevelLoop(HoistedL); 2020 } 2021 SubLoops.erase(SubLoopsSplitI, SubLoops.end()); 2022 2023 // Actually delete the loop if nothing remained within it. 2024 if (Blocks.empty()) { 2025 assert(SubLoops.empty() && 2026 "Failed to remove all subloops from the original loop!"); 2027 if (Loop *ParentL = L.getParentLoop()) 2028 ParentL->removeChildLoop(llvm::find(*ParentL, &L)); 2029 else 2030 LI.removeLoop(llvm::find(LI, &L)); 2031 // markLoopAsDeleted for L should be triggered by the caller (it is typically 2032 // done by using the UnswitchCB callback). 2033 if (SE) 2034 SE->forgetBlockAndLoopDispositions(); 2035 LI.destroy(&L); 2036 return false; 2037 } 2038 2039 return true; 2040 } 2041 2042 /// Helper to visit a dominator subtree, invoking a callable on each node. 2043 /// 2044 /// Returning false at any point will stop walking past that node of the tree. 2045 template <typename CallableT> 2046 void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) { 2047 SmallVector<DomTreeNode *, 4> DomWorklist; 2048 DomWorklist.push_back(DT[BB]); 2049 #ifndef NDEBUG 2050 SmallPtrSet<DomTreeNode *, 4> Visited; 2051 Visited.insert(DT[BB]); 2052 #endif 2053 do { 2054 DomTreeNode *N = DomWorklist.pop_back_val(); 2055 2056 // Visit this node. 2057 if (!Callable(N->getBlock())) 2058 continue; 2059 2060 // Accumulate the child nodes. 2061 for (DomTreeNode *ChildN : *N) { 2062 assert(Visited.insert(ChildN).second && 2063 "Cannot visit a node twice when walking a tree!"); 2064 DomWorklist.push_back(ChildN); 2065 } 2066 } while (!DomWorklist.empty()); 2067 } 2068 2069 static void unswitchNontrivialInvariants( 2070 Loop &L, Instruction &TI, ArrayRef<Value *> Invariants, 2071 IVConditionInfo &PartialIVInfo, DominatorTree &DT, LoopInfo &LI, 2072 AssumptionCache &AC, 2073 function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB, 2074 ScalarEvolution *SE, MemorySSAUpdater *MSSAU, 2075 function_ref<void(Loop &, StringRef)> DestroyLoopCB) { 2076 auto *ParentBB = TI.getParent(); 2077 BranchInst *BI = dyn_cast<BranchInst>(&TI); 2078 SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI); 2079 2080 // We can only unswitch switches, conditional branches with an invariant 2081 // condition, or combining invariant conditions with an instruction or 2082 // partially invariant instructions. 2083 assert((SI || (BI && BI->isConditional())) && 2084 "Can only unswitch switches and conditional branch!"); 2085 bool PartiallyInvariant = !PartialIVInfo.InstToDuplicate.empty(); 2086 bool FullUnswitch = 2087 SI || (skipTrivialSelect(BI->getCondition()) == Invariants[0] && 2088 !PartiallyInvariant); 2089 if (FullUnswitch) 2090 assert(Invariants.size() == 1 && 2091 "Cannot have other invariants with full unswitching!"); 2092 else 2093 assert(isa<Instruction>(skipTrivialSelect(BI->getCondition())) && 2094 "Partial unswitching requires an instruction as the condition!"); 2095 2096 if (MSSAU && VerifyMemorySSA) 2097 MSSAU->getMemorySSA()->verifyMemorySSA(); 2098 2099 // Constant and BBs tracking the cloned and continuing successor. When we are 2100 // unswitching the entire condition, this can just be trivially chosen to 2101 // unswitch towards `true`. However, when we are unswitching a set of 2102 // invariants combined with `and` or `or` or partially invariant instructions, 2103 // the combining operation determines the best direction to unswitch: we want 2104 // to unswitch the direction that will collapse the branch. 2105 bool Direction = true; 2106 int ClonedSucc = 0; 2107 if (!FullUnswitch) { 2108 Value *Cond = skipTrivialSelect(BI->getCondition()); 2109 (void)Cond; 2110 assert(((match(Cond, m_LogicalAnd()) ^ match(Cond, m_LogicalOr())) || 2111 PartiallyInvariant) && 2112 "Only `or`, `and`, an `select`, partially invariant instructions " 2113 "can combine invariants being unswitched."); 2114 if (!match(Cond, m_LogicalOr())) { 2115 if (match(Cond, m_LogicalAnd()) || 2116 (PartiallyInvariant && !PartialIVInfo.KnownValue->isOneValue())) { 2117 Direction = false; 2118 ClonedSucc = 1; 2119 } 2120 } 2121 } 2122 2123 BasicBlock *RetainedSuccBB = 2124 BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest(); 2125 SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs; 2126 if (BI) 2127 UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc)); 2128 else 2129 for (auto Case : SI->cases()) 2130 if (Case.getCaseSuccessor() != RetainedSuccBB) 2131 UnswitchedSuccBBs.insert(Case.getCaseSuccessor()); 2132 2133 assert(!UnswitchedSuccBBs.count(RetainedSuccBB) && 2134 "Should not unswitch the same successor we are retaining!"); 2135 2136 // The branch should be in this exact loop. Any inner loop's invariant branch 2137 // should be handled by unswitching that inner loop. The caller of this 2138 // routine should filter out any candidates that remain (but were skipped for 2139 // whatever reason). 2140 assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!"); 2141 2142 // Compute the parent loop now before we start hacking on things. 2143 Loop *ParentL = L.getParentLoop(); 2144 // Get blocks in RPO order for MSSA update, before changing the CFG. 2145 LoopBlocksRPO LBRPO(&L); 2146 if (MSSAU) 2147 LBRPO.perform(&LI); 2148 2149 // Compute the outer-most loop containing one of our exit blocks. This is the 2150 // furthest up our loopnest which can be mutated, which we will use below to 2151 // update things. 2152 Loop *OuterExitL = &L; 2153 SmallVector<BasicBlock *, 4> ExitBlocks; 2154 L.getUniqueExitBlocks(ExitBlocks); 2155 for (auto *ExitBB : ExitBlocks) { 2156 Loop *NewOuterExitL = LI.getLoopFor(ExitBB); 2157 if (!NewOuterExitL) { 2158 // We exited the entire nest with this block, so we're done. 2159 OuterExitL = nullptr; 2160 break; 2161 } 2162 if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL)) 2163 OuterExitL = NewOuterExitL; 2164 } 2165 2166 // At this point, we're definitely going to unswitch something so invalidate 2167 // any cached information in ScalarEvolution for the outer most loop 2168 // containing an exit block and all nested loops. 2169 if (SE) { 2170 if (OuterExitL) 2171 SE->forgetLoop(OuterExitL); 2172 else 2173 SE->forgetTopmostLoop(&L); 2174 } 2175 2176 bool InsertFreeze = false; 2177 if (FreezeLoopUnswitchCond) { 2178 ICFLoopSafetyInfo SafetyInfo; 2179 SafetyInfo.computeLoopSafetyInfo(&L); 2180 InsertFreeze = !SafetyInfo.isGuaranteedToExecute(TI, &DT, &L); 2181 } 2182 2183 // If the edge from this terminator to a successor dominates that successor, 2184 // store a map from each block in its dominator subtree to it. This lets us 2185 // tell when cloning for a particular successor if a block is dominated by 2186 // some *other* successor with a single data structure. We use this to 2187 // significantly reduce cloning. 2188 SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc; 2189 for (auto *SuccBB : llvm::concat<BasicBlock *const>( 2190 makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs)) 2191 if (SuccBB->getUniquePredecessor() || 2192 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) { 2193 return PredBB == ParentBB || DT.dominates(SuccBB, PredBB); 2194 })) 2195 visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) { 2196 DominatingSucc[BB] = SuccBB; 2197 return true; 2198 }); 2199 2200 // Split the preheader, so that we know that there is a safe place to insert 2201 // the conditional branch. We will change the preheader to have a conditional 2202 // branch on LoopCond. The original preheader will become the split point 2203 // between the unswitched versions, and we will have a new preheader for the 2204 // original loop. 2205 BasicBlock *SplitBB = L.getLoopPreheader(); 2206 BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU); 2207 2208 // Keep track of the dominator tree updates needed. 2209 SmallVector<DominatorTree::UpdateType, 4> DTUpdates; 2210 2211 // Clone the loop for each unswitched successor. 2212 SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps; 2213 VMaps.reserve(UnswitchedSuccBBs.size()); 2214 SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs; 2215 for (auto *SuccBB : UnswitchedSuccBBs) { 2216 VMaps.emplace_back(new ValueToValueMapTy()); 2217 ClonedPHs[SuccBB] = buildClonedLoopBlocks( 2218 L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB, 2219 DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU); 2220 } 2221 2222 // Drop metadata if we may break its semantics by moving this instr into the 2223 // split block. 2224 if (TI.getMetadata(LLVMContext::MD_make_implicit)) { 2225 if (DropNonTrivialImplicitNullChecks) 2226 // Do not spend time trying to understand if we can keep it, just drop it 2227 // to save compile time. 2228 TI.setMetadata(LLVMContext::MD_make_implicit, nullptr); 2229 else { 2230 // It is only legal to preserve make.implicit metadata if we are 2231 // guaranteed no reach implicit null check after following this branch. 2232 ICFLoopSafetyInfo SafetyInfo; 2233 SafetyInfo.computeLoopSafetyInfo(&L); 2234 if (!SafetyInfo.isGuaranteedToExecute(TI, &DT, &L)) 2235 TI.setMetadata(LLVMContext::MD_make_implicit, nullptr); 2236 } 2237 } 2238 2239 // The stitching of the branched code back together depends on whether we're 2240 // doing full unswitching or not with the exception that we always want to 2241 // nuke the initial terminator placed in the split block. 2242 SplitBB->getTerminator()->eraseFromParent(); 2243 if (FullUnswitch) { 2244 // Splice the terminator from the original loop and rewrite its 2245 // successors. 2246 SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI); 2247 2248 // Keep a clone of the terminator for MSSA updates. 2249 Instruction *NewTI = TI.clone(); 2250 ParentBB->getInstList().push_back(NewTI); 2251 2252 // First wire up the moved terminator to the preheaders. 2253 if (BI) { 2254 BasicBlock *ClonedPH = ClonedPHs.begin()->second; 2255 BI->setSuccessor(ClonedSucc, ClonedPH); 2256 BI->setSuccessor(1 - ClonedSucc, LoopPH); 2257 Value *Cond = skipTrivialSelect(BI->getCondition()); 2258 if (InsertFreeze) { 2259 if (!isGuaranteedNotToBeUndefOrPoison(Cond, &AC, BI, &DT)) 2260 Cond = new FreezeInst(Cond, Cond->getName() + ".fr", BI); 2261 } 2262 BI->setCondition(Cond); 2263 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH}); 2264 } else { 2265 assert(SI && "Must either be a branch or switch!"); 2266 2267 // Walk the cases and directly update their successors. 2268 assert(SI->getDefaultDest() == RetainedSuccBB && 2269 "Not retaining default successor!"); 2270 SI->setDefaultDest(LoopPH); 2271 for (const auto &Case : SI->cases()) 2272 if (Case.getCaseSuccessor() == RetainedSuccBB) 2273 Case.setSuccessor(LoopPH); 2274 else 2275 Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second); 2276 2277 if (InsertFreeze) { 2278 auto Cond = SI->getCondition(); 2279 if (!isGuaranteedNotToBeUndefOrPoison(Cond, &AC, SI, &DT)) 2280 SI->setCondition(new FreezeInst(Cond, Cond->getName() + ".fr", SI)); 2281 } 2282 // We need to use the set to populate domtree updates as even when there 2283 // are multiple cases pointing at the same successor we only want to 2284 // remove and insert one edge in the domtree. 2285 for (BasicBlock *SuccBB : UnswitchedSuccBBs) 2286 DTUpdates.push_back( 2287 {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second}); 2288 } 2289 2290 if (MSSAU) { 2291 DT.applyUpdates(DTUpdates); 2292 DTUpdates.clear(); 2293 2294 // Remove all but one edge to the retained block and all unswitched 2295 // blocks. This is to avoid having duplicate entries in the cloned Phis, 2296 // when we know we only keep a single edge for each case. 2297 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB); 2298 for (BasicBlock *SuccBB : UnswitchedSuccBBs) 2299 MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB); 2300 2301 for (auto &VMap : VMaps) 2302 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap, 2303 /*IgnoreIncomingWithNoClones=*/true); 2304 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT); 2305 2306 // Remove all edges to unswitched blocks. 2307 for (BasicBlock *SuccBB : UnswitchedSuccBBs) 2308 MSSAU->removeEdge(ParentBB, SuccBB); 2309 } 2310 2311 // Now unhook the successor relationship as we'll be replacing 2312 // the terminator with a direct branch. This is much simpler for branches 2313 // than switches so we handle those first. 2314 if (BI) { 2315 // Remove the parent as a predecessor of the unswitched successor. 2316 assert(UnswitchedSuccBBs.size() == 1 && 2317 "Only one possible unswitched block for a branch!"); 2318 BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin(); 2319 UnswitchedSuccBB->removePredecessor(ParentBB, 2320 /*KeepOneInputPHIs*/ true); 2321 DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB}); 2322 } else { 2323 // Note that we actually want to remove the parent block as a predecessor 2324 // of *every* case successor. The case successor is either unswitched, 2325 // completely eliminating an edge from the parent to that successor, or it 2326 // is a duplicate edge to the retained successor as the retained successor 2327 // is always the default successor and as we'll replace this with a direct 2328 // branch we no longer need the duplicate entries in the PHI nodes. 2329 SwitchInst *NewSI = cast<SwitchInst>(NewTI); 2330 assert(NewSI->getDefaultDest() == RetainedSuccBB && 2331 "Not retaining default successor!"); 2332 for (const auto &Case : NewSI->cases()) 2333 Case.getCaseSuccessor()->removePredecessor( 2334 ParentBB, 2335 /*KeepOneInputPHIs*/ true); 2336 2337 // We need to use the set to populate domtree updates as even when there 2338 // are multiple cases pointing at the same successor we only want to 2339 // remove and insert one edge in the domtree. 2340 for (BasicBlock *SuccBB : UnswitchedSuccBBs) 2341 DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB}); 2342 } 2343 2344 // After MSSAU update, remove the cloned terminator instruction NewTI. 2345 ParentBB->getTerminator()->eraseFromParent(); 2346 2347 // Create a new unconditional branch to the continuing block (as opposed to 2348 // the one cloned). 2349 BranchInst::Create(RetainedSuccBB, ParentBB); 2350 } else { 2351 assert(BI && "Only branches have partial unswitching."); 2352 assert(UnswitchedSuccBBs.size() == 1 && 2353 "Only one possible unswitched block for a branch!"); 2354 BasicBlock *ClonedPH = ClonedPHs.begin()->second; 2355 // When doing a partial unswitch, we have to do a bit more work to build up 2356 // the branch in the split block. 2357 if (PartiallyInvariant) 2358 buildPartialInvariantUnswitchConditionalBranch( 2359 *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, L, MSSAU); 2360 else { 2361 buildPartialUnswitchConditionalBranch( 2362 *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, 2363 FreezeLoopUnswitchCond, BI, &AC, DT); 2364 } 2365 DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH}); 2366 2367 if (MSSAU) { 2368 DT.applyUpdates(DTUpdates); 2369 DTUpdates.clear(); 2370 2371 // Perform MSSA cloning updates. 2372 for (auto &VMap : VMaps) 2373 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap, 2374 /*IgnoreIncomingWithNoClones=*/true); 2375 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT); 2376 } 2377 } 2378 2379 // Apply the updates accumulated above to get an up-to-date dominator tree. 2380 DT.applyUpdates(DTUpdates); 2381 2382 // Now that we have an accurate dominator tree, first delete the dead cloned 2383 // blocks so that we can accurately build any cloned loops. It is important to 2384 // not delete the blocks from the original loop yet because we still want to 2385 // reference the original loop to understand the cloned loop's structure. 2386 deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU); 2387 2388 // Build the cloned loop structure itself. This may be substantially 2389 // different from the original structure due to the simplified CFG. This also 2390 // handles inserting all the cloned blocks into the correct loops. 2391 SmallVector<Loop *, 4> NonChildClonedLoops; 2392 for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps) 2393 buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops); 2394 2395 // Now that our cloned loops have been built, we can update the original loop. 2396 // First we delete the dead blocks from it and then we rebuild the loop 2397 // structure taking these deletions into account. 2398 deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU, SE,DestroyLoopCB); 2399 2400 if (MSSAU && VerifyMemorySSA) 2401 MSSAU->getMemorySSA()->verifyMemorySSA(); 2402 2403 SmallVector<Loop *, 4> HoistedLoops; 2404 bool IsStillLoop = 2405 rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops, SE); 2406 2407 if (MSSAU && VerifyMemorySSA) 2408 MSSAU->getMemorySSA()->verifyMemorySSA(); 2409 2410 // This transformation has a high risk of corrupting the dominator tree, and 2411 // the below steps to rebuild loop structures will result in hard to debug 2412 // errors in that case so verify that the dominator tree is sane first. 2413 // FIXME: Remove this when the bugs stop showing up and rely on existing 2414 // verification steps. 2415 assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 2416 2417 if (BI && !PartiallyInvariant) { 2418 // If we unswitched a branch which collapses the condition to a known 2419 // constant we want to replace all the uses of the invariants within both 2420 // the original and cloned blocks. We do this here so that we can use the 2421 // now updated dominator tree to identify which side the users are on. 2422 assert(UnswitchedSuccBBs.size() == 1 && 2423 "Only one possible unswitched block for a branch!"); 2424 BasicBlock *ClonedPH = ClonedPHs.begin()->second; 2425 2426 // When considering multiple partially-unswitched invariants 2427 // we cant just go replace them with constants in both branches. 2428 // 2429 // For 'AND' we infer that true branch ("continue") means true 2430 // for each invariant operand. 2431 // For 'OR' we can infer that false branch ("continue") means false 2432 // for each invariant operand. 2433 // So it happens that for multiple-partial case we dont replace 2434 // in the unswitched branch. 2435 bool ReplaceUnswitched = 2436 FullUnswitch || (Invariants.size() == 1) || PartiallyInvariant; 2437 2438 ConstantInt *UnswitchedReplacement = 2439 Direction ? ConstantInt::getTrue(BI->getContext()) 2440 : ConstantInt::getFalse(BI->getContext()); 2441 ConstantInt *ContinueReplacement = 2442 Direction ? ConstantInt::getFalse(BI->getContext()) 2443 : ConstantInt::getTrue(BI->getContext()); 2444 for (Value *Invariant : Invariants) { 2445 assert(!isa<Constant>(Invariant) && 2446 "Should not be replacing constant values!"); 2447 // Use make_early_inc_range here as set invalidates the iterator. 2448 for (Use &U : llvm::make_early_inc_range(Invariant->uses())) { 2449 Instruction *UserI = dyn_cast<Instruction>(U.getUser()); 2450 if (!UserI) 2451 continue; 2452 2453 // Replace it with the 'continue' side if in the main loop body, and the 2454 // unswitched if in the cloned blocks. 2455 if (DT.dominates(LoopPH, UserI->getParent())) 2456 U.set(ContinueReplacement); 2457 else if (ReplaceUnswitched && 2458 DT.dominates(ClonedPH, UserI->getParent())) 2459 U.set(UnswitchedReplacement); 2460 } 2461 } 2462 } 2463 2464 // We can change which blocks are exit blocks of all the cloned sibling 2465 // loops, the current loop, and any parent loops which shared exit blocks 2466 // with the current loop. As a consequence, we need to re-form LCSSA for 2467 // them. But we shouldn't need to re-form LCSSA for any child loops. 2468 // FIXME: This could be made more efficient by tracking which exit blocks are 2469 // new, and focusing on them, but that isn't likely to be necessary. 2470 // 2471 // In order to reasonably rebuild LCSSA we need to walk inside-out across the 2472 // loop nest and update every loop that could have had its exits changed. We 2473 // also need to cover any intervening loops. We add all of these loops to 2474 // a list and sort them by loop depth to achieve this without updating 2475 // unnecessary loops. 2476 auto UpdateLoop = [&](Loop &UpdateL) { 2477 #ifndef NDEBUG 2478 UpdateL.verifyLoop(); 2479 for (Loop *ChildL : UpdateL) { 2480 ChildL->verifyLoop(); 2481 assert(ChildL->isRecursivelyLCSSAForm(DT, LI) && 2482 "Perturbed a child loop's LCSSA form!"); 2483 } 2484 #endif 2485 // First build LCSSA for this loop so that we can preserve it when 2486 // forming dedicated exits. We don't want to perturb some other loop's 2487 // LCSSA while doing that CFG edit. 2488 formLCSSA(UpdateL, DT, &LI, SE); 2489 2490 // For loops reached by this loop's original exit blocks we may 2491 // introduced new, non-dedicated exits. At least try to re-form dedicated 2492 // exits for these loops. This may fail if they couldn't have dedicated 2493 // exits to start with. 2494 formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true); 2495 }; 2496 2497 // For non-child cloned loops and hoisted loops, we just need to update LCSSA 2498 // and we can do it in any order as they don't nest relative to each other. 2499 // 2500 // Also check if any of the loops we have updated have become top-level loops 2501 // as that will necessitate widening the outer loop scope. 2502 for (Loop *UpdatedL : 2503 llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) { 2504 UpdateLoop(*UpdatedL); 2505 if (UpdatedL->isOutermost()) 2506 OuterExitL = nullptr; 2507 } 2508 if (IsStillLoop) { 2509 UpdateLoop(L); 2510 if (L.isOutermost()) 2511 OuterExitL = nullptr; 2512 } 2513 2514 // If the original loop had exit blocks, walk up through the outer most loop 2515 // of those exit blocks to update LCSSA and form updated dedicated exits. 2516 if (OuterExitL != &L) 2517 for (Loop *OuterL = ParentL; OuterL != OuterExitL; 2518 OuterL = OuterL->getParentLoop()) 2519 UpdateLoop(*OuterL); 2520 2521 #ifndef NDEBUG 2522 // Verify the entire loop structure to catch any incorrect updates before we 2523 // progress in the pass pipeline. 2524 LI.verify(DT); 2525 #endif 2526 2527 // Now that we've unswitched something, make callbacks to report the changes. 2528 // For that we need to merge together the updated loops and the cloned loops 2529 // and check whether the original loop survived. 2530 SmallVector<Loop *, 4> SibLoops; 2531 for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) 2532 if (UpdatedL->getParentLoop() == ParentL) 2533 SibLoops.push_back(UpdatedL); 2534 UnswitchCB(IsStillLoop, PartiallyInvariant, SibLoops); 2535 2536 if (MSSAU && VerifyMemorySSA) 2537 MSSAU->getMemorySSA()->verifyMemorySSA(); 2538 2539 if (BI) 2540 ++NumBranches; 2541 else 2542 ++NumSwitches; 2543 } 2544 2545 /// Recursively compute the cost of a dominator subtree based on the per-block 2546 /// cost map provided. 2547 /// 2548 /// The recursive computation is memozied into the provided DT-indexed cost map 2549 /// to allow querying it for most nodes in the domtree without it becoming 2550 /// quadratic. 2551 static InstructionCost computeDomSubtreeCost( 2552 DomTreeNode &N, 2553 const SmallDenseMap<BasicBlock *, InstructionCost, 4> &BBCostMap, 2554 SmallDenseMap<DomTreeNode *, InstructionCost, 4> &DTCostMap) { 2555 // Don't accumulate cost (or recurse through) blocks not in our block cost 2556 // map and thus not part of the duplication cost being considered. 2557 auto BBCostIt = BBCostMap.find(N.getBlock()); 2558 if (BBCostIt == BBCostMap.end()) 2559 return 0; 2560 2561 // Lookup this node to see if we already computed its cost. 2562 auto DTCostIt = DTCostMap.find(&N); 2563 if (DTCostIt != DTCostMap.end()) 2564 return DTCostIt->second; 2565 2566 // If not, we have to compute it. We can't use insert above and update 2567 // because computing the cost may insert more things into the map. 2568 InstructionCost Cost = std::accumulate( 2569 N.begin(), N.end(), BBCostIt->second, 2570 [&](InstructionCost Sum, DomTreeNode *ChildN) -> InstructionCost { 2571 return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap); 2572 }); 2573 bool Inserted = DTCostMap.insert({&N, Cost}).second; 2574 (void)Inserted; 2575 assert(Inserted && "Should not insert a node while visiting children!"); 2576 return Cost; 2577 } 2578 2579 /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch, 2580 /// making the following replacement: 2581 /// 2582 /// --code before guard-- 2583 /// call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ] 2584 /// --code after guard-- 2585 /// 2586 /// into 2587 /// 2588 /// --code before guard-- 2589 /// br i1 %cond, label %guarded, label %deopt 2590 /// 2591 /// guarded: 2592 /// --code after guard-- 2593 /// 2594 /// deopt: 2595 /// call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ] 2596 /// unreachable 2597 /// 2598 /// It also makes all relevant DT and LI updates, so that all structures are in 2599 /// valid state after this transform. 2600 static BranchInst *turnGuardIntoBranch(IntrinsicInst *GI, Loop &L, 2601 DominatorTree &DT, LoopInfo &LI, 2602 MemorySSAUpdater *MSSAU) { 2603 SmallVector<DominatorTree::UpdateType, 4> DTUpdates; 2604 LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n"); 2605 BasicBlock *CheckBB = GI->getParent(); 2606 2607 if (MSSAU && VerifyMemorySSA) 2608 MSSAU->getMemorySSA()->verifyMemorySSA(); 2609 2610 // Remove all CheckBB's successors from DomTree. A block can be seen among 2611 // successors more than once, but for DomTree it should be added only once. 2612 SmallPtrSet<BasicBlock *, 4> Successors; 2613 for (auto *Succ : successors(CheckBB)) 2614 if (Successors.insert(Succ).second) 2615 DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ}); 2616 2617 Instruction *DeoptBlockTerm = 2618 SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true); 2619 BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator()); 2620 // SplitBlockAndInsertIfThen inserts control flow that branches to 2621 // DeoptBlockTerm if the condition is true. We want the opposite. 2622 CheckBI->swapSuccessors(); 2623 2624 BasicBlock *GuardedBlock = CheckBI->getSuccessor(0); 2625 GuardedBlock->setName("guarded"); 2626 CheckBI->getSuccessor(1)->setName("deopt"); 2627 BasicBlock *DeoptBlock = CheckBI->getSuccessor(1); 2628 2629 if (MSSAU) 2630 MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI); 2631 2632 GI->moveBefore(DeoptBlockTerm); 2633 GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext())); 2634 2635 // Add new successors of CheckBB into DomTree. 2636 for (auto *Succ : successors(CheckBB)) 2637 DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ}); 2638 2639 // Now the blocks that used to be CheckBB's successors are GuardedBlock's 2640 // successors. 2641 for (auto *Succ : Successors) 2642 DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ}); 2643 2644 // Make proper changes to DT. 2645 DT.applyUpdates(DTUpdates); 2646 // Inform LI of a new loop block. 2647 L.addBasicBlockToLoop(GuardedBlock, LI); 2648 2649 if (MSSAU) { 2650 MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI)); 2651 MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator); 2652 if (VerifyMemorySSA) 2653 MSSAU->getMemorySSA()->verifyMemorySSA(); 2654 } 2655 2656 ++NumGuards; 2657 return CheckBI; 2658 } 2659 2660 /// Cost multiplier is a way to limit potentially exponential behavior 2661 /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch 2662 /// candidates available. Also accounting for the number of "sibling" loops with 2663 /// the idea to account for previous unswitches that already happened on this 2664 /// cluster of loops. There was an attempt to keep this formula simple, 2665 /// just enough to limit the worst case behavior. Even if it is not that simple 2666 /// now it is still not an attempt to provide a detailed heuristic size 2667 /// prediction. 2668 /// 2669 /// TODO: Make a proper accounting of "explosion" effect for all kinds of 2670 /// unswitch candidates, making adequate predictions instead of wild guesses. 2671 /// That requires knowing not just the number of "remaining" candidates but 2672 /// also costs of unswitching for each of these candidates. 2673 static int CalculateUnswitchCostMultiplier( 2674 const Instruction &TI, const Loop &L, const LoopInfo &LI, 2675 const DominatorTree &DT, 2676 ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates) { 2677 2678 // Guards and other exiting conditions do not contribute to exponential 2679 // explosion as soon as they dominate the latch (otherwise there might be 2680 // another path to the latch remaining that does not allow to eliminate the 2681 // loop copy on unswitch). 2682 const BasicBlock *Latch = L.getLoopLatch(); 2683 const BasicBlock *CondBlock = TI.getParent(); 2684 if (DT.dominates(CondBlock, Latch) && 2685 (isGuard(&TI) || 2686 llvm::count_if(successors(&TI), [&L](const BasicBlock *SuccBB) { 2687 return L.contains(SuccBB); 2688 }) <= 1)) { 2689 NumCostMultiplierSkipped++; 2690 return 1; 2691 } 2692 2693 auto *ParentL = L.getParentLoop(); 2694 int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size() 2695 : std::distance(LI.begin(), LI.end())); 2696 // Count amount of clones that all the candidates might cause during 2697 // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases. 2698 int UnswitchedClones = 0; 2699 for (auto Candidate : UnswitchCandidates) { 2700 const Instruction *CI = Candidate.TI; 2701 const BasicBlock *CondBlock = CI->getParent(); 2702 bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch); 2703 if (isGuard(CI)) { 2704 if (!SkipExitingSuccessors) 2705 UnswitchedClones++; 2706 continue; 2707 } 2708 int NonExitingSuccessors = 2709 llvm::count_if(successors(CondBlock), 2710 [SkipExitingSuccessors, &L](const BasicBlock *SuccBB) { 2711 return !SkipExitingSuccessors || L.contains(SuccBB); 2712 }); 2713 UnswitchedClones += Log2_32(NonExitingSuccessors); 2714 } 2715 2716 // Ignore up to the "unscaled candidates" number of unswitch candidates 2717 // when calculating the power-of-two scaling of the cost. The main idea 2718 // with this control is to allow a small number of unswitches to happen 2719 // and rely more on siblings multiplier (see below) when the number 2720 // of candidates is small. 2721 unsigned ClonesPower = 2722 std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0); 2723 2724 // Allowing top-level loops to spread a bit more than nested ones. 2725 int SiblingsMultiplier = 2726 std::max((ParentL ? SiblingsCount 2727 : SiblingsCount / (int)UnswitchSiblingsToplevelDiv), 2728 1); 2729 // Compute the cost multiplier in a way that won't overflow by saturating 2730 // at an upper bound. 2731 int CostMultiplier; 2732 if (ClonesPower > Log2_32(UnswitchThreshold) || 2733 SiblingsMultiplier > UnswitchThreshold) 2734 CostMultiplier = UnswitchThreshold; 2735 else 2736 CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower), 2737 (int)UnswitchThreshold); 2738 2739 LLVM_DEBUG(dbgs() << " Computed multiplier " << CostMultiplier 2740 << " (siblings " << SiblingsMultiplier << " * clones " 2741 << (1 << ClonesPower) << ")" 2742 << " for unswitch candidate: " << TI << "\n"); 2743 return CostMultiplier; 2744 } 2745 2746 static bool collectUnswitchCandidates( 2747 SmallVectorImpl<NonTrivialUnswitchCandidate> &UnswitchCandidates, 2748 IVConditionInfo &PartialIVInfo, Instruction *&PartialIVCondBranch, 2749 const Loop &L, const LoopInfo &LI, AAResults &AA, 2750 const MemorySSAUpdater *MSSAU) { 2751 assert(UnswitchCandidates.empty() && "Should be!"); 2752 // Whether or not we should also collect guards in the loop. 2753 bool CollectGuards = false; 2754 if (UnswitchGuards) { 2755 auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction( 2756 Intrinsic::getName(Intrinsic::experimental_guard)); 2757 if (GuardDecl && !GuardDecl->use_empty()) 2758 CollectGuards = true; 2759 } 2760 2761 for (auto *BB : L.blocks()) { 2762 if (LI.getLoopFor(BB) != &L) 2763 continue; 2764 2765 if (CollectGuards) 2766 for (auto &I : *BB) 2767 if (isGuard(&I)) { 2768 auto *Cond = cast<IntrinsicInst>(&I)->getArgOperand(0); 2769 // TODO: Support AND, OR conditions and partial unswitching. 2770 if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond)) 2771 UnswitchCandidates.push_back({&I, {Cond}}); 2772 } 2773 2774 if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) { 2775 // We can only consider fully loop-invariant switch conditions as we need 2776 // to completely eliminate the switch after unswitching. 2777 if (!isa<Constant>(SI->getCondition()) && 2778 L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor()) 2779 UnswitchCandidates.push_back({SI, {SI->getCondition()}}); 2780 continue; 2781 } 2782 2783 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 2784 if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) || 2785 BI->getSuccessor(0) == BI->getSuccessor(1)) 2786 continue; 2787 2788 Value *Cond = skipTrivialSelect(BI->getCondition()); 2789 if (isa<Constant>(Cond)) 2790 continue; 2791 2792 if (L.isLoopInvariant(Cond)) { 2793 UnswitchCandidates.push_back({BI, {Cond}}); 2794 continue; 2795 } 2796 2797 Instruction &CondI = *cast<Instruction>(Cond); 2798 if (match(&CondI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()))) { 2799 TinyPtrVector<Value *> Invariants = 2800 collectHomogenousInstGraphLoopInvariants(L, CondI, LI); 2801 if (Invariants.empty()) 2802 continue; 2803 2804 UnswitchCandidates.push_back({BI, std::move(Invariants)}); 2805 continue; 2806 } 2807 } 2808 2809 if (MSSAU && !findOptionMDForLoop(&L, "llvm.loop.unswitch.partial.disable") && 2810 !any_of(UnswitchCandidates, [&L](auto &TerminatorAndInvariants) { 2811 return TerminatorAndInvariants.TI == L.getHeader()->getTerminator(); 2812 })) { 2813 MemorySSA *MSSA = MSSAU->getMemorySSA(); 2814 if (auto Info = hasPartialIVCondition(L, MSSAThreshold, *MSSA, AA)) { 2815 LLVM_DEBUG( 2816 dbgs() << "simple-loop-unswitch: Found partially invariant condition " 2817 << *Info->InstToDuplicate[0] << "\n"); 2818 PartialIVInfo = *Info; 2819 PartialIVCondBranch = L.getHeader()->getTerminator(); 2820 TinyPtrVector<Value *> ValsToDuplicate; 2821 llvm::append_range(ValsToDuplicate, Info->InstToDuplicate); 2822 UnswitchCandidates.push_back( 2823 {L.getHeader()->getTerminator(), std::move(ValsToDuplicate)}); 2824 } 2825 } 2826 return !UnswitchCandidates.empty(); 2827 } 2828 2829 static bool isSafeForNoNTrivialUnswitching(Loop &L, LoopInfo &LI) { 2830 if (!L.isSafeToClone()) 2831 return false; 2832 for (auto *BB : L.blocks()) 2833 for (auto &I : *BB) { 2834 if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB)) 2835 return false; 2836 if (auto *CB = dyn_cast<CallBase>(&I)) { 2837 assert(!CB->cannotDuplicate() && "Checked by L.isSafeToClone()."); 2838 if (CB->isConvergent()) 2839 return false; 2840 } 2841 } 2842 2843 // Check if there are irreducible CFG cycles in this loop. If so, we cannot 2844 // easily unswitch non-trivial edges out of the loop. Doing so might turn the 2845 // irreducible control flow into reducible control flow and introduce new 2846 // loops "out of thin air". If we ever discover important use cases for doing 2847 // this, we can add support to loop unswitch, but it is a lot of complexity 2848 // for what seems little or no real world benefit. 2849 LoopBlocksRPO RPOT(&L); 2850 RPOT.perform(&LI); 2851 if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI)) 2852 return false; 2853 2854 SmallVector<BasicBlock *, 4> ExitBlocks; 2855 L.getUniqueExitBlocks(ExitBlocks); 2856 // We cannot unswitch if exit blocks contain a cleanuppad/catchswitch 2857 // instruction as we don't know how to split those exit blocks. 2858 // FIXME: We should teach SplitBlock to handle this and remove this 2859 // restriction. 2860 for (auto *ExitBB : ExitBlocks) { 2861 auto *I = ExitBB->getFirstNonPHI(); 2862 if (isa<CleanupPadInst>(I) || isa<CatchSwitchInst>(I)) { 2863 LLVM_DEBUG(dbgs() << "Cannot unswitch because of cleanuppad/catchswitch " 2864 "in exit block\n"); 2865 return false; 2866 } 2867 } 2868 2869 return true; 2870 } 2871 2872 static NonTrivialUnswitchCandidate findBestNonTrivialUnswitchCandidate( 2873 ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates, const Loop &L, 2874 const DominatorTree &DT, const LoopInfo &LI, AssumptionCache &AC, 2875 const TargetTransformInfo &TTI, const IVConditionInfo &PartialIVInfo) { 2876 // Given that unswitching these terminators will require duplicating parts of 2877 // the loop, so we need to be able to model that cost. Compute the ephemeral 2878 // values and set up a data structure to hold per-BB costs. We cache each 2879 // block's cost so that we don't recompute this when considering different 2880 // subsets of the loop for duplication during unswitching. 2881 SmallPtrSet<const Value *, 4> EphValues; 2882 CodeMetrics::collectEphemeralValues(&L, &AC, EphValues); 2883 SmallDenseMap<BasicBlock *, InstructionCost, 4> BBCostMap; 2884 2885 // Compute the cost of each block, as well as the total loop cost. Also, bail 2886 // out if we see instructions which are incompatible with loop unswitching 2887 // (convergent, noduplicate, or cross-basic-block tokens). 2888 // FIXME: We might be able to safely handle some of these in non-duplicated 2889 // regions. 2890 TargetTransformInfo::TargetCostKind CostKind = 2891 L.getHeader()->getParent()->hasMinSize() 2892 ? TargetTransformInfo::TCK_CodeSize 2893 : TargetTransformInfo::TCK_SizeAndLatency; 2894 InstructionCost LoopCost = 0; 2895 for (auto *BB : L.blocks()) { 2896 InstructionCost Cost = 0; 2897 for (auto &I : *BB) { 2898 if (EphValues.count(&I)) 2899 continue; 2900 Cost += TTI.getInstructionCost(&I, CostKind); 2901 } 2902 assert(Cost >= 0 && "Must not have negative costs!"); 2903 LoopCost += Cost; 2904 assert(LoopCost >= 0 && "Must not have negative loop costs!"); 2905 BBCostMap[BB] = Cost; 2906 } 2907 LLVM_DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n"); 2908 2909 // Now we find the best candidate by searching for the one with the following 2910 // properties in order: 2911 // 2912 // 1) An unswitching cost below the threshold 2913 // 2) The smallest number of duplicated unswitch candidates (to avoid 2914 // creating redundant subsequent unswitching) 2915 // 3) The smallest cost after unswitching. 2916 // 2917 // We prioritize reducing fanout of unswitch candidates provided the cost 2918 // remains below the threshold because this has a multiplicative effect. 2919 // 2920 // This requires memoizing each dominator subtree to avoid redundant work. 2921 // 2922 // FIXME: Need to actually do the number of candidates part above. 2923 SmallDenseMap<DomTreeNode *, InstructionCost, 4> DTCostMap; 2924 // Given a terminator which might be unswitched, computes the non-duplicated 2925 // cost for that terminator. 2926 auto ComputeUnswitchedCost = [&](Instruction &TI, 2927 bool FullUnswitch) -> InstructionCost { 2928 BasicBlock &BB = *TI.getParent(); 2929 SmallPtrSet<BasicBlock *, 4> Visited; 2930 2931 InstructionCost Cost = 0; 2932 for (BasicBlock *SuccBB : successors(&BB)) { 2933 // Don't count successors more than once. 2934 if (!Visited.insert(SuccBB).second) 2935 continue; 2936 2937 // If this is a partial unswitch candidate, then it must be a conditional 2938 // branch with a condition of either `or`, `and`, their corresponding 2939 // select forms or partially invariant instructions. In that case, one of 2940 // the successors is necessarily duplicated, so don't even try to remove 2941 // its cost. 2942 if (!FullUnswitch) { 2943 auto &BI = cast<BranchInst>(TI); 2944 Value *Cond = skipTrivialSelect(BI.getCondition()); 2945 if (match(Cond, m_LogicalAnd())) { 2946 if (SuccBB == BI.getSuccessor(1)) 2947 continue; 2948 } else if (match(Cond, m_LogicalOr())) { 2949 if (SuccBB == BI.getSuccessor(0)) 2950 continue; 2951 } else if ((PartialIVInfo.KnownValue->isOneValue() && 2952 SuccBB == BI.getSuccessor(0)) || 2953 (!PartialIVInfo.KnownValue->isOneValue() && 2954 SuccBB == BI.getSuccessor(1))) 2955 continue; 2956 } 2957 2958 // This successor's domtree will not need to be duplicated after 2959 // unswitching if the edge to the successor dominates it (and thus the 2960 // entire tree). This essentially means there is no other path into this 2961 // subtree and so it will end up live in only one clone of the loop. 2962 if (SuccBB->getUniquePredecessor() || 2963 llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) { 2964 return PredBB == &BB || DT.dominates(SuccBB, PredBB); 2965 })) { 2966 Cost += computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap); 2967 assert(Cost <= LoopCost && 2968 "Non-duplicated cost should never exceed total loop cost!"); 2969 } 2970 } 2971 2972 // Now scale the cost by the number of unique successors minus one. We 2973 // subtract one because there is already at least one copy of the entire 2974 // loop. This is computing the new cost of unswitching a condition. 2975 // Note that guards always have 2 unique successors that are implicit and 2976 // will be materialized if we decide to unswitch it. 2977 int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size(); 2978 assert(SuccessorsCount > 1 && 2979 "Cannot unswitch a condition without multiple distinct successors!"); 2980 return (LoopCost - Cost) * (SuccessorsCount - 1); 2981 }; 2982 2983 Optional<NonTrivialUnswitchCandidate> Best; 2984 for (auto &Candidate : UnswitchCandidates) { 2985 Instruction &TI = *Candidate.TI; 2986 ArrayRef<Value *> Invariants = Candidate.Invariants; 2987 BranchInst *BI = dyn_cast<BranchInst>(&TI); 2988 InstructionCost CandidateCost = ComputeUnswitchedCost( 2989 TI, /*FullUnswitch*/ !BI || 2990 (Invariants.size() == 1 && 2991 Invariants[0] == skipTrivialSelect(BI->getCondition()))); 2992 // Calculate cost multiplier which is a tool to limit potentially 2993 // exponential behavior of loop-unswitch. 2994 if (EnableUnswitchCostMultiplier) { 2995 int CostMultiplier = 2996 CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates); 2997 assert( 2998 (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) && 2999 "cost multiplier needs to be in the range of 1..UnswitchThreshold"); 3000 CandidateCost *= CostMultiplier; 3001 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost 3002 << " (multiplier: " << CostMultiplier << ")" 3003 << " for unswitch candidate: " << TI << "\n"); 3004 } else { 3005 LLVM_DEBUG(dbgs() << " Computed cost of " << CandidateCost 3006 << " for unswitch candidate: " << TI << "\n"); 3007 } 3008 3009 if (!Best || CandidateCost < Best->Cost) { 3010 Best = Candidate; 3011 Best->Cost = CandidateCost; 3012 } 3013 } 3014 assert(Best && "Must be!"); 3015 return *Best; 3016 } 3017 3018 static bool unswitchBestCondition( 3019 Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, 3020 AAResults &AA, TargetTransformInfo &TTI, 3021 function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB, 3022 ScalarEvolution *SE, MemorySSAUpdater *MSSAU, 3023 function_ref<void(Loop &, StringRef)> DestroyLoopCB) { 3024 // Collect all invariant conditions within this loop (as opposed to an inner 3025 // loop which would be handled when visiting that inner loop). 3026 SmallVector<NonTrivialUnswitchCandidate, 4> UnswitchCandidates; 3027 IVConditionInfo PartialIVInfo; 3028 Instruction *PartialIVCondBranch = nullptr; 3029 // If we didn't find any candidates, we're done. 3030 if (!collectUnswitchCandidates(UnswitchCandidates, PartialIVInfo, 3031 PartialIVCondBranch, L, LI, AA, MSSAU)) 3032 return false; 3033 3034 LLVM_DEBUG( 3035 dbgs() << "Considering " << UnswitchCandidates.size() 3036 << " non-trivial loop invariant conditions for unswitching.\n"); 3037 3038 NonTrivialUnswitchCandidate Best = findBestNonTrivialUnswitchCandidate( 3039 UnswitchCandidates, L, DT, LI, AC, TTI, PartialIVInfo); 3040 3041 assert(Best.TI && "Failed to find loop unswitch candidate"); 3042 assert(Best.Cost && "Failed to compute cost"); 3043 3044 if (*Best.Cost >= UnswitchThreshold) { 3045 LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: " << *Best.Cost 3046 << "\n"); 3047 return false; 3048 } 3049 3050 if (Best.TI != PartialIVCondBranch) 3051 PartialIVInfo.InstToDuplicate.clear(); 3052 3053 // If the best candidate is a guard, turn it into a branch. 3054 if (isGuard(Best.TI)) 3055 Best.TI = 3056 turnGuardIntoBranch(cast<IntrinsicInst>(Best.TI), L, DT, LI, MSSAU); 3057 3058 LLVM_DEBUG(dbgs() << " Unswitching non-trivial (cost = " << Best.Cost 3059 << ") terminator: " << *Best.TI << "\n"); 3060 unswitchNontrivialInvariants(L, *Best.TI, Best.Invariants, PartialIVInfo, DT, 3061 LI, AC, UnswitchCB, SE, MSSAU, DestroyLoopCB); 3062 return true; 3063 } 3064 3065 /// Unswitch control flow predicated on loop invariant conditions. 3066 /// 3067 /// This first hoists all branches or switches which are trivial (IE, do not 3068 /// require duplicating any part of the loop) out of the loop body. It then 3069 /// looks at other loop invariant control flows and tries to unswitch those as 3070 /// well by cloning the loop if the result is small enough. 3071 /// 3072 /// The `DT`, `LI`, `AC`, `AA`, `TTI` parameters are required analyses that are 3073 /// also updated based on the unswitch. The `MSSA` analysis is also updated if 3074 /// valid (i.e. its use is enabled). 3075 /// 3076 /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is 3077 /// true, we will attempt to do non-trivial unswitching as well as trivial 3078 /// unswitching. 3079 /// 3080 /// The `UnswitchCB` callback provided will be run after unswitching is 3081 /// complete, with the first parameter set to `true` if the provided loop 3082 /// remains a loop, and a list of new sibling loops created. 3083 /// 3084 /// If `SE` is non-null, we will update that analysis based on the unswitching 3085 /// done. 3086 static bool 3087 unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, 3088 AAResults &AA, TargetTransformInfo &TTI, bool Trivial, 3089 bool NonTrivial, 3090 function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB, 3091 ScalarEvolution *SE, MemorySSAUpdater *MSSAU, 3092 ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, 3093 function_ref<void(Loop &, StringRef)> DestroyLoopCB) { 3094 assert(L.isRecursivelyLCSSAForm(DT, LI) && 3095 "Loops must be in LCSSA form before unswitching."); 3096 3097 // Must be in loop simplified form: we need a preheader and dedicated exits. 3098 if (!L.isLoopSimplifyForm()) 3099 return false; 3100 3101 // Try trivial unswitch first before loop over other basic blocks in the loop. 3102 if (Trivial && unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) { 3103 // If we unswitched successfully we will want to clean up the loop before 3104 // processing it further so just mark it as unswitched and return. 3105 UnswitchCB(/*CurrentLoopValid*/ true, false, {}); 3106 return true; 3107 } 3108 3109 // Check whether we should continue with non-trivial conditions. 3110 // EnableNonTrivialUnswitch: Global variable that forces non-trivial 3111 // unswitching for testing and debugging. 3112 // NonTrivial: Parameter that enables non-trivial unswitching for this 3113 // invocation of the transform. But this should be allowed only 3114 // for targets without branch divergence. 3115 // 3116 // FIXME: If divergence analysis becomes available to a loop 3117 // transform, we should allow unswitching for non-trivial uniform 3118 // branches even on targets that have divergence. 3119 // https://bugs.llvm.org/show_bug.cgi?id=48819 3120 bool ContinueWithNonTrivial = 3121 EnableNonTrivialUnswitch || (NonTrivial && !TTI.hasBranchDivergence()); 3122 if (!ContinueWithNonTrivial) 3123 return false; 3124 3125 // Skip non-trivial unswitching for optsize functions. 3126 if (L.getHeader()->getParent()->hasOptSize()) 3127 return false; 3128 3129 // Skip cold loops, as unswitching them brings little benefit 3130 // but increases the code size 3131 if (PSI && PSI->hasProfileSummary() && BFI && 3132 PSI->isFunctionColdInCallGraph(L.getHeader()->getParent(), *BFI)) { 3133 LLVM_DEBUG(dbgs() << " Skip cold loop: " << L << "\n"); 3134 return false; 3135 } 3136 3137 // Perform legality checks. 3138 if (!isSafeForNoNTrivialUnswitching(L, LI)) 3139 return false; 3140 3141 // For non-trivial unswitching, because it often creates new loops, we rely on 3142 // the pass manager to iterate on the loops rather than trying to immediately 3143 // reach a fixed point. There is no substantial advantage to iterating 3144 // internally, and if any of the new loops are simplified enough to contain 3145 // trivial unswitching we want to prefer those. 3146 3147 // Try to unswitch the best invariant condition. We prefer this full unswitch to 3148 // a partial unswitch when possible below the threshold. 3149 if (unswitchBestCondition(L, DT, LI, AC, AA, TTI, UnswitchCB, SE, MSSAU, 3150 DestroyLoopCB)) 3151 return true; 3152 3153 // No other opportunities to unswitch. 3154 return false; 3155 } 3156 3157 PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM, 3158 LoopStandardAnalysisResults &AR, 3159 LPMUpdater &U) { 3160 Function &F = *L.getHeader()->getParent(); 3161 (void)F; 3162 ProfileSummaryInfo *PSI = nullptr; 3163 if (auto OuterProxy = 3164 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR) 3165 .getCachedResult<ModuleAnalysisManagerFunctionProxy>(F)) 3166 PSI = OuterProxy->getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 3167 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L 3168 << "\n"); 3169 3170 // Save the current loop name in a variable so that we can report it even 3171 // after it has been deleted. 3172 std::string LoopName = std::string(L.getName()); 3173 3174 auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid, 3175 bool PartiallyInvariant, 3176 ArrayRef<Loop *> NewLoops) { 3177 // If we did a non-trivial unswitch, we have added new (cloned) loops. 3178 if (!NewLoops.empty()) 3179 U.addSiblingLoops(NewLoops); 3180 3181 // If the current loop remains valid, we should revisit it to catch any 3182 // other unswitch opportunities. Otherwise, we need to mark it as deleted. 3183 if (CurrentLoopValid) { 3184 if (PartiallyInvariant) { 3185 // Mark the new loop as partially unswitched, to avoid unswitching on 3186 // the same condition again. 3187 auto &Context = L.getHeader()->getContext(); 3188 MDNode *DisableUnswitchMD = MDNode::get( 3189 Context, 3190 MDString::get(Context, "llvm.loop.unswitch.partial.disable")); 3191 MDNode *NewLoopID = makePostTransformationMetadata( 3192 Context, L.getLoopID(), {"llvm.loop.unswitch.partial"}, 3193 {DisableUnswitchMD}); 3194 L.setLoopID(NewLoopID); 3195 } else 3196 U.revisitCurrentLoop(); 3197 } else 3198 U.markLoopAsDeleted(L, LoopName); 3199 }; 3200 3201 auto DestroyLoopCB = [&U](Loop &L, StringRef Name) { 3202 U.markLoopAsDeleted(L, Name); 3203 }; 3204 3205 Optional<MemorySSAUpdater> MSSAU; 3206 if (AR.MSSA) { 3207 MSSAU = MemorySSAUpdater(AR.MSSA); 3208 if (VerifyMemorySSA) 3209 AR.MSSA->verifyMemorySSA(); 3210 } 3211 if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.AA, AR.TTI, Trivial, NonTrivial, 3212 UnswitchCB, &AR.SE, MSSAU ? MSSAU.getPointer() : nullptr, 3213 PSI, AR.BFI, DestroyLoopCB)) 3214 return PreservedAnalyses::all(); 3215 3216 if (AR.MSSA && VerifyMemorySSA) 3217 AR.MSSA->verifyMemorySSA(); 3218 3219 // Historically this pass has had issues with the dominator tree so verify it 3220 // in asserts builds. 3221 assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast)); 3222 3223 auto PA = getLoopPassPreservedAnalyses(); 3224 if (AR.MSSA) 3225 PA.preserve<MemorySSAAnalysis>(); 3226 return PA; 3227 } 3228 3229 void SimpleLoopUnswitchPass::printPipeline( 3230 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) { 3231 static_cast<PassInfoMixin<SimpleLoopUnswitchPass> *>(this)->printPipeline( 3232 OS, MapClassName2PassName); 3233 3234 OS << "<"; 3235 OS << (NonTrivial ? "" : "no-") << "nontrivial;"; 3236 OS << (Trivial ? "" : "no-") << "trivial"; 3237 OS << ">"; 3238 } 3239 3240 namespace { 3241 3242 class SimpleLoopUnswitchLegacyPass : public LoopPass { 3243 bool NonTrivial; 3244 3245 public: 3246 static char ID; // Pass ID, replacement for typeid 3247 3248 explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false) 3249 : LoopPass(ID), NonTrivial(NonTrivial) { 3250 initializeSimpleLoopUnswitchLegacyPassPass( 3251 *PassRegistry::getPassRegistry()); 3252 } 3253 3254 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 3255 3256 void getAnalysisUsage(AnalysisUsage &AU) const override { 3257 AU.addRequired<AssumptionCacheTracker>(); 3258 AU.addRequired<TargetTransformInfoWrapperPass>(); 3259 AU.addRequired<MemorySSAWrapperPass>(); 3260 AU.addPreserved<MemorySSAWrapperPass>(); 3261 getLoopAnalysisUsage(AU); 3262 } 3263 }; 3264 3265 } // end anonymous namespace 3266 3267 bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) { 3268 if (skipLoop(L)) 3269 return false; 3270 3271 Function &F = *L->getHeader()->getParent(); 3272 3273 LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L 3274 << "\n"); 3275 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3276 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 3277 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 3278 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 3279 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 3280 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA(); 3281 MemorySSAUpdater MSSAU(MSSA); 3282 3283 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 3284 auto *SE = SEWP ? &SEWP->getSE() : nullptr; 3285 3286 auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid, bool PartiallyInvariant, 3287 ArrayRef<Loop *> NewLoops) { 3288 // If we did a non-trivial unswitch, we have added new (cloned) loops. 3289 for (auto *NewL : NewLoops) 3290 LPM.addLoop(*NewL); 3291 3292 // If the current loop remains valid, re-add it to the queue. This is 3293 // a little wasteful as we'll finish processing the current loop as well, 3294 // but it is the best we can do in the old PM. 3295 if (CurrentLoopValid) { 3296 // If the current loop has been unswitched using a partially invariant 3297 // condition, we should not re-add the current loop to avoid unswitching 3298 // on the same condition again. 3299 if (!PartiallyInvariant) 3300 LPM.addLoop(*L); 3301 } else 3302 LPM.markLoopAsDeleted(*L); 3303 }; 3304 3305 auto DestroyLoopCB = [&LPM](Loop &L, StringRef /* Name */) { 3306 LPM.markLoopAsDeleted(L); 3307 }; 3308 3309 if (VerifyMemorySSA) 3310 MSSA->verifyMemorySSA(); 3311 bool Changed = 3312 unswitchLoop(*L, DT, LI, AC, AA, TTI, true, NonTrivial, UnswitchCB, SE, 3313 &MSSAU, nullptr, nullptr, DestroyLoopCB); 3314 3315 if (VerifyMemorySSA) 3316 MSSA->verifyMemorySSA(); 3317 3318 // Historically this pass has had issues with the dominator tree so verify it 3319 // in asserts builds. 3320 assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 3321 3322 return Changed; 3323 } 3324 3325 char SimpleLoopUnswitchLegacyPass::ID = 0; 3326 INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", 3327 "Simple unswitch loops", false, false) 3328 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 3329 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 3330 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 3331 INITIALIZE_PASS_DEPENDENCY(LoopPass) 3332 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 3333 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 3334 INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", 3335 "Simple unswitch loops", false, false) 3336 3337 Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) { 3338 return new SimpleLoopUnswitchLegacyPass(NonTrivial); 3339 } 3340