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