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