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