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