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