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