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