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