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