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