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