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