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