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