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