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