Bug Summary

File:llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
Warning:line 2912, column 21
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SimpleLoopUnswitch.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Transforms/Scalar -I include -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-10-17-004846-21170-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp

/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp

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

/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Transforms/Utils/LoopUtils.h

1//===- llvm/Transforms/Utils/LoopUtils.h - Loop utilities -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines some loop transformation utilities.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
14#define LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
15
16#include "llvm/ADT/StringRef.h"
17#include "llvm/Analysis/IVDescriptors.h"
18#include "llvm/Analysis/TargetTransformInfo.h"
19#include "llvm/Transforms/Utils/ValueMapper.h"
20
21namespace llvm {
22
23template <typename T> class DomTreeNodeBase;
24using DomTreeNode = DomTreeNodeBase<BasicBlock>;
25class AAResults;
26class AliasSet;
27class AliasSetTracker;
28class BasicBlock;
29class BlockFrequencyInfo;
30class ICFLoopSafetyInfo;
31class IRBuilderBase;
32class Loop;
33class LoopInfo;
34class MemoryAccess;
35class MemorySSA;
36class MemorySSAUpdater;
37class OptimizationRemarkEmitter;
38class PredIteratorCache;
39class ScalarEvolution;
40class ScalarEvolutionExpander;
41class SCEV;
42class SCEVExpander;
43class TargetLibraryInfo;
44class LPPassManager;
45class Instruction;
46struct RuntimeCheckingPtrGroup;
47typedef std::pair<const RuntimeCheckingPtrGroup *,
48 const RuntimeCheckingPtrGroup *>
49 RuntimePointerCheck;
50
51template <typename T> class Optional;
52template <typename T, unsigned N> class SmallSetVector;
53template <typename T, unsigned N> class SmallVector;
54template <typename T> class SmallVectorImpl;
55template <typename T, unsigned N> class SmallPriorityWorklist;
56
57BasicBlock *InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI,
58 MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
59
60/// Ensure that all exit blocks of the loop are dedicated exits.
61///
62/// For any loop exit block with non-loop predecessors, we split the loop
63/// predecessors to use a dedicated loop exit block. We update the dominator
64/// tree and loop info if provided, and will preserve LCSSA if requested.
65bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
66 MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
67
68/// Ensures LCSSA form for every instruction from the Worklist in the scope of
69/// innermost containing loop.
70///
71/// For the given instruction which have uses outside of the loop, an LCSSA PHI
72/// node is inserted and the uses outside the loop are rewritten to use this
73/// node.
74///
75/// LoopInfo and DominatorTree are required and, since the routine makes no
76/// changes to CFG, preserved.
77///
78/// Returns true if any modifications are made.
79///
80/// This function may introduce unused PHI nodes. If \p PHIsToRemove is not
81/// nullptr, those are added to it (before removing, the caller has to check if
82/// they still do not have any uses). Otherwise the PHIs are directly removed.
83bool formLCSSAForInstructions(
84 SmallVectorImpl<Instruction *> &Worklist, const DominatorTree &DT,
85 const LoopInfo &LI, ScalarEvolution *SE, IRBuilderBase &Builder,
86 SmallVectorImpl<PHINode *> *PHIsToRemove = nullptr);
87
88/// Put loop into LCSSA form.
89///
90/// Looks at all instructions in the loop which have uses outside of the
91/// current loop. For each, an LCSSA PHI node is inserted and the uses outside
92/// the loop are rewritten to use this node. Sub-loops must be in LCSSA form
93/// already.
94///
95/// LoopInfo and DominatorTree are required and preserved.
96///
97/// If ScalarEvolution is passed in, it will be preserved.
98///
99/// Returns true if any modifications are made to the loop.
100bool formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI,
101 ScalarEvolution *SE);
102
103/// Put a loop nest into LCSSA form.
104///
105/// This recursively forms LCSSA for a loop nest.
106///
107/// LoopInfo and DominatorTree are required and preserved.
108///
109/// If ScalarEvolution is passed in, it will be preserved.
110///
111/// Returns true if any modifications are made to the loop.
112bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI,
113 ScalarEvolution *SE);
114
115/// Flags controlling how much is checked when sinking or hoisting
116/// instructions. The number of memory access in the loop (and whether there
117/// are too many) is determined in the constructors when using MemorySSA.
118class SinkAndHoistLICMFlags {
119public:
120 // Explicitly set limits.
121 SinkAndHoistLICMFlags(unsigned LicmMssaOptCap,
122 unsigned LicmMssaNoAccForPromotionCap, bool IsSink,
123 Loop *L = nullptr, MemorySSA *MSSA = nullptr);
124 // Use default limits.
125 SinkAndHoistLICMFlags(bool IsSink, Loop *L = nullptr,
126 MemorySSA *MSSA = nullptr);
127
128 void setIsSink(bool B) { IsSink = B; }
129 bool getIsSink() { return IsSink; }
130 bool tooManyMemoryAccesses() { return NoOfMemAccTooLarge; }
131 bool tooManyClobberingCalls() { return LicmMssaOptCounter >= LicmMssaOptCap; }
132 void incrementClobberingCalls() { ++LicmMssaOptCounter; }
133
134protected:
135 bool NoOfMemAccTooLarge = false;
136 unsigned LicmMssaOptCounter = 0;
137 unsigned LicmMssaOptCap;
138 unsigned LicmMssaNoAccForPromotionCap;
139 bool IsSink;
140};
141
142/// Walk the specified region of the CFG (defined by all blocks
143/// dominated by the specified block, and that are in the current loop) in
144/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
145/// uses before definitions, allowing us to sink a loop body in one pass without
146/// iteration. Takes DomTreeNode, AAResults, LoopInfo, DominatorTree,
147/// BlockFrequencyInfo, TargetLibraryInfo, Loop, AliasSet information for all
148/// instructions of the loop and loop safety information as
149/// arguments. Diagnostics is emitted via \p ORE. It returns changed status.
150/// \p CurLoop is a loop to do sinking on. \p OutermostLoop is used only when
151/// this function is called by \p sinkRegionForLoopNest.
152bool sinkRegion(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *,
153 BlockFrequencyInfo *, TargetLibraryInfo *,
154 TargetTransformInfo *, Loop *CurLoop, MemorySSAUpdater *,
155 ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &,
156 OptimizationRemarkEmitter *, Loop *OutermostLoop = nullptr);
157
158/// Call sinkRegion on loops contained within the specified loop
159/// in order from innermost to outermost.
160bool sinkRegionForLoopNest(DomTreeNode *, AAResults *, LoopInfo *,
161 DominatorTree *, BlockFrequencyInfo *,
162 TargetLibraryInfo *, TargetTransformInfo *, Loop *,
163 MemorySSAUpdater *, ICFLoopSafetyInfo *,
164 SinkAndHoistLICMFlags &,
165 OptimizationRemarkEmitter *);
166
167/// Walk the specified region of the CFG (defined by all blocks
168/// dominated by the specified block, and that are in the current loop) in depth
169/// first order w.r.t the DominatorTree. This allows us to visit definitions
170/// before uses, allowing us to hoist a loop body in one pass without iteration.
171/// Takes DomTreeNode, AAResults, LoopInfo, DominatorTree,
172/// BlockFrequencyInfo, TargetLibraryInfo, Loop, AliasSet information for all
173/// instructions of the loop and loop safety information as arguments.
174/// Diagnostics is emitted via \p ORE. It returns changed status.
175bool hoistRegion(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *,
176 BlockFrequencyInfo *, TargetLibraryInfo *, Loop *,
177 MemorySSAUpdater *, ScalarEvolution *, ICFLoopSafetyInfo *,
178 SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *, bool);
179
180/// This function deletes dead loops. The caller of this function needs to
181/// guarantee that the loop is infact dead.
182/// The function requires a bunch or prerequisites to be present:
183/// - The loop needs to be in LCSSA form
184/// - The loop needs to have a Preheader
185/// - A unique dedicated exit block must exist
186///
187/// This also updates the relevant analysis information in \p DT, \p SE, \p LI
188/// and \p MSSA if pointers to those are provided.
189/// It also updates the loop PM if an updater struct is provided.
190
191void deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
192 LoopInfo *LI, MemorySSA *MSSA = nullptr);
193
194/// Remove the backedge of the specified loop. Handles loop nests and general
195/// loop structures subject to the precondition that the loop has no parent
196/// loop and has a single latch block. Preserves all listed analyses.
197void breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
198 LoopInfo &LI, MemorySSA *MSSA);
199
200/// Try to promote memory values to scalars by sinking stores out of
201/// the loop and moving loads to before the loop. We do this by looping over
202/// the stores in the loop, looking for stores to Must pointers which are
203/// loop invariant. It takes a set of must-alias values, Loop exit blocks
204/// vector, loop exit blocks insertion point vector, PredIteratorCache,
205/// LoopInfo, DominatorTree, Loop, AliasSet information for all instructions
206/// of the loop and loop safety information as arguments.
207/// Diagnostics is emitted via \p ORE. It returns changed status.
208bool promoteLoopAccessesToScalars(
209 const SmallSetVector<Value *, 8> &, SmallVectorImpl<BasicBlock *> &,
210 SmallVectorImpl<Instruction *> &, SmallVectorImpl<MemoryAccess *> &,
211 PredIteratorCache &, LoopInfo *, DominatorTree *, const TargetLibraryInfo *,
212 Loop *, MemorySSAUpdater *, ICFLoopSafetyInfo *,
213 OptimizationRemarkEmitter *);
214
215/// Does a BFS from a given node to all of its children inside a given loop.
216/// The returned vector of nodes includes the starting point.
217SmallVector<DomTreeNode *, 16> collectChildrenInLoop(DomTreeNode *N,
218 const Loop *CurLoop);
219
220/// Returns the instructions that use values defined in the loop.
221SmallVector<Instruction *, 8> findDefsUsedOutsideOfLoop(Loop *L);
222
223/// Find a combination of metadata ("llvm.loop.vectorize.width" and
224/// "llvm.loop.vectorize.scalable.enable") for a loop and use it to construct a
225/// ElementCount. If the metadata "llvm.loop.vectorize.width" cannot be found
226/// then None is returned.
227Optional<ElementCount>
228getOptionalElementCountLoopAttribute(const Loop *TheLoop);
229
230/// Create a new loop identifier for a loop created from a loop transformation.
231///
232/// @param OrigLoopID The loop ID of the loop before the transformation.
233/// @param FollowupAttrs List of attribute names that contain attributes to be
234/// added to the new loop ID.
235/// @param InheritOptionsAttrsPrefix Selects which attributes should be inherited
236/// from the original loop. The following values
237/// are considered:
238/// nullptr : Inherit all attributes from @p OrigLoopID.
239/// "" : Do not inherit any attribute from @p OrigLoopID; only use
240/// those specified by a followup attribute.
241/// "<prefix>": Inherit all attributes except those which start with
242/// <prefix>; commonly used to remove metadata for the
243/// applied transformation.
244/// @param AlwaysNew If true, do not try to reuse OrigLoopID and never return
245/// None.
246///
247/// @return The loop ID for the after-transformation loop. The following values
248/// can be returned:
249/// None : No followup attribute was found; it is up to the
250/// transformation to choose attributes that make sense.
251/// @p OrigLoopID: The original identifier can be reused.
252/// nullptr : The new loop has no attributes.
253/// MDNode* : A new unique loop identifier.
254Optional<MDNode *>
255makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef<StringRef> FollowupAttrs,
256 const char *InheritOptionsAttrsPrefix = "",
257 bool AlwaysNew = false);
258
259/// Look for the loop attribute that disables all transformation heuristic.
260bool hasDisableAllTransformsHint(const Loop *L);
261
262/// Look for the loop attribute that disables the LICM transformation heuristics.
263bool hasDisableLICMTransformsHint(const Loop *L);
264
265/// The mode sets how eager a transformation should be applied.
266enum TransformationMode {
267 /// The pass can use heuristics to determine whether a transformation should
268 /// be applied.
269 TM_Unspecified,
270
271 /// The transformation should be applied without considering a cost model.
272 TM_Enable,
273
274 /// The transformation should not be applied.
275 TM_Disable,
276
277 /// Force is a flag and should not be used alone.
278 TM_Force = 0x04,
279
280 /// The transformation was directed by the user, e.g. by a #pragma in
281 /// the source code. If the transformation could not be applied, a
282 /// warning should be emitted.
283 TM_ForcedByUser = TM_Enable | TM_Force,
284
285 /// The transformation must not be applied. For instance, `#pragma clang loop
286 /// unroll(disable)` explicitly forbids any unrolling to take place. Unlike
287 /// general loop metadata, it must not be dropped. Most passes should not
288 /// behave differently under TM_Disable and TM_SuppressedByUser.
289 TM_SuppressedByUser = TM_Disable | TM_Force
290};
291
292/// @{
293/// Get the mode for LLVM's supported loop transformations.
294TransformationMode hasUnrollTransformation(const Loop *L);
295TransformationMode hasUnrollAndJamTransformation(const Loop *L);
296TransformationMode hasVectorizeTransformation(const Loop *L);
297TransformationMode hasDistributeTransformation(const Loop *L);
298TransformationMode hasLICMVersioningTransformation(const Loop *L);
299/// @}
300
301/// Set input string into loop metadata by keeping other values intact.
302/// If the string is already in loop metadata update value if it is
303/// different.
304void addStringMetadataToLoop(Loop *TheLoop, const char *MDString,
305 unsigned V = 0);
306
307/// Returns a loop's estimated trip count based on branch weight metadata.
308/// In addition if \p EstimatedLoopInvocationWeight is not null it is
309/// initialized with weight of loop's latch leading to the exit.
310/// Returns 0 when the count is estimated to be 0, or None when a meaningful
311/// estimate can not be made.
312Optional<unsigned>
313getLoopEstimatedTripCount(Loop *L,
314 unsigned *EstimatedLoopInvocationWeight = nullptr);
315
316/// Set a loop's branch weight metadata to reflect that loop has \p
317/// EstimatedTripCount iterations and \p EstimatedLoopInvocationWeight exits
318/// through latch. Returns true if metadata is successfully updated, false
319/// otherwise. Note that loop must have a latch block which controls loop exit
320/// in order to succeed.
321bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
322 unsigned EstimatedLoopInvocationWeight);
323
324/// Check inner loop (L) backedge count is known to be invariant on all
325/// iterations of its outer loop. If the loop has no parent, this is trivially
326/// true.
327bool hasIterationCountInvariantInParent(Loop *L, ScalarEvolution &SE);
328
329/// Helper to consistently add the set of standard passes to a loop pass's \c
330/// AnalysisUsage.
331///
332/// All loop passes should call this as part of implementing their \c
333/// getAnalysisUsage.
334void getLoopAnalysisUsage(AnalysisUsage &AU);
335
336/// Returns true if is legal to hoist or sink this instruction disregarding the
337/// possible introduction of faults. Reasoning about potential faulting
338/// instructions is the responsibility of the caller since it is challenging to
339/// do efficiently from within this routine.
340/// \p TargetExecutesOncePerLoop is true only when it is guaranteed that the
341/// target executes at most once per execution of the loop body. This is used
342/// to assess the legality of duplicating atomic loads. Generally, this is
343/// true when moving out of loop and not true when moving into loops.
344/// If \p ORE is set use it to emit optimization remarks.
345bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
346 Loop *CurLoop, AliasSetTracker *CurAST,
347 MemorySSAUpdater *MSSAU, bool TargetExecutesOncePerLoop,
348 SinkAndHoistLICMFlags *LICMFlags = nullptr,
349 OptimizationRemarkEmitter *ORE = nullptr);
350
351/// Returns the comparison predicate used when expanding a min/max reduction.
352CmpInst::Predicate getMinMaxReductionPredicate(RecurKind RK);
353
354/// See RecurrenceDescriptor::isSelectCmpPattern for a description of the
355/// pattern we are trying to match. In this pattern we are only ever selecting
356/// between two values: 1) an initial PHI start value, and 2) a loop invariant
357/// value. This function uses \p LoopExitInst to determine 2), which we then use
358/// to select between \p Left and \p Right. Any lane value in \p Left that
359/// matches 2) will be merged into \p Right.
360Value *createSelectCmpOp(IRBuilderBase &Builder, Value *StartVal, RecurKind RK,
361 Value *Left, Value *Right);
362
363/// Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
364/// The Builder's fast-math-flags must be set to propagate the expected values.
365Value *createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
366 Value *Right);
367
368/// Generates an ordered vector reduction using extracts to reduce the value.
369Value *getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
370 unsigned Op, RecurKind MinMaxKind = RecurKind::None,
371 ArrayRef<Value *> RedOps = None);
372
373/// Generates a vector reduction using shufflevectors to reduce the value.
374/// Fast-math-flags are propagated using the IRBuilder's setting.
375Value *getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op,
376 RecurKind MinMaxKind = RecurKind::None,
377 ArrayRef<Value *> RedOps = None);
378
379/// Create a target reduction of the given vector. The reduction operation
380/// is described by the \p Opcode parameter. min/max reductions require
381/// additional information supplied in \p RdxKind.
382/// The target is queried to determine if intrinsics or shuffle sequences are
383/// required to implement the reduction.
384/// Fast-math-flags are propagated using the IRBuilder's setting.
385Value *createSimpleTargetReduction(IRBuilderBase &B,
386 const TargetTransformInfo *TTI, Value *Src,
387 RecurKind RdxKind,
388 ArrayRef<Value *> RedOps = None);
389
390/// Create a target reduction of the given vector \p Src for a reduction of the
391/// kind RecurKind::SelectICmp or RecurKind::SelectFCmp. The reduction operation
392/// is described by \p Desc.
393Value *createSelectCmpTargetReduction(IRBuilderBase &B,
394 const TargetTransformInfo *TTI,
395 Value *Src,
396 const RecurrenceDescriptor &Desc,
397 PHINode *OrigPhi);
398
399/// Create a generic target reduction using a recurrence descriptor \p Desc
400/// The target is queried to determine if intrinsics or shuffle sequences are
401/// required to implement the reduction.
402/// Fast-math-flags are propagated using the RecurrenceDescriptor.
403Value *createTargetReduction(IRBuilderBase &B, const TargetTransformInfo *TTI,
404 const RecurrenceDescriptor &Desc, Value *Src,
405 PHINode *OrigPhi = nullptr);
406
407/// Create an ordered reduction intrinsic using the given recurrence
408/// descriptor \p Desc.
409Value *createOrderedReduction(IRBuilderBase &B,
410 const RecurrenceDescriptor &Desc, Value *Src,
411 Value *Start);
412
413/// Get the intersection (logical and) of all of the potential IR flags
414/// of each scalar operation (VL) that will be converted into a vector (I).
415/// If OpValue is non-null, we only consider operations similar to OpValue
416/// when intersecting.
417/// Flag set: NSW, NUW, exact, and all of fast-math.
418void propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue = nullptr);
419
420/// Returns true if we can prove that \p S is defined and always negative in
421/// loop \p L.
422bool isKnownNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE);
423
424/// Returns true if we can prove that \p S is defined and always non-negative in
425/// loop \p L.
426bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
427 ScalarEvolution &SE);
428
429/// Returns true if \p S is defined and never is equal to signed/unsigned max.
430bool cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
431 bool Signed);
432
433/// Returns true if \p S is defined and never is equal to signed/unsigned min.
434bool cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
435 bool Signed);
436
437enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, NoHardUse, AlwaysRepl };
438
439/// If the final value of any expressions that are recurrent in the loop can
440/// be computed, substitute the exit values from the loop into any instructions
441/// outside of the loop that use the final values of the current expressions.
442/// Return the number of loop exit values that have been replaced, and the
443/// corresponding phi node will be added to DeadInsts.
444int rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
445 ScalarEvolution *SE, const TargetTransformInfo *TTI,
446 SCEVExpander &Rewriter, DominatorTree *DT,
447 ReplaceExitVal ReplaceExitValue,
448 SmallVector<WeakTrackingVH, 16> &DeadInsts);
449
450/// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
451/// \p OrigLoop and the following distribution of \p OrigLoop iteration among \p
452/// UnrolledLoop and \p RemainderLoop. \p UnrolledLoop receives weights that
453/// reflect TC/UF iterations, and \p RemainderLoop receives weights that reflect
454/// the remaining TC%UF iterations.
455///
456/// Note that \p OrigLoop may be equal to either \p UnrolledLoop or \p
457/// RemainderLoop in which case weights for \p OrigLoop are updated accordingly.
458/// Note also behavior is undefined if \p UnrolledLoop and \p RemainderLoop are
459/// equal. \p UF must be greater than zero.
460/// If \p OrigLoop has no profile info associated nothing happens.
461///
462/// This utility may be useful for such optimizations as unroller and
463/// vectorizer as it's typical transformation for them.
464void setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
465 Loop *RemainderLoop, uint64_t UF);
466
467/// Utility that implements appending of loops onto a worklist given a range.
468/// We want to process loops in postorder, but the worklist is a LIFO data
469/// structure, so we append to it in *reverse* postorder.
470/// For trees, a preorder traversal is a viable reverse postorder, so we
471/// actually append using a preorder walk algorithm.
472template <typename RangeT>
473void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist<Loop *, 4> &);
474/// Utility that implements appending of loops onto a worklist given a range.
475/// It has the same behavior as appendLoopsToWorklist, but assumes the range of
476/// loops has already been reversed, so it processes loops in the given order.
477template <typename RangeT>
478void appendReversedLoopsToWorklist(RangeT &&,
479 SmallPriorityWorklist<Loop *, 4> &);
480
481/// Utility that implements appending of loops onto a worklist given LoopInfo.
482/// Calls the templated utility taking a Range of loops, handing it the Loops
483/// in LoopInfo, iterated in reverse. This is because the loops are stored in
484/// RPO w.r.t. the control flow graph in LoopInfo. For the purpose of unrolling,
485/// loop deletion, and LICM, we largely want to work forward across the CFG so
486/// that we visit defs before uses and can propagate simplifications from one
487/// loop nest into the next. Calls appendReversedLoopsToWorklist with the
488/// already reversed loops in LI.
489/// FIXME: Consider changing the order in LoopInfo.
490void appendLoopsToWorklist(LoopInfo &, SmallPriorityWorklist<Loop *, 4> &);
491
492/// Recursively clone the specified loop and all of its children,
493/// mapping the blocks with the specified map.
494Loop *cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
495 LoopInfo *LI, LPPassManager *LPM);
496
497/// Add code that checks at runtime if the accessed arrays in \p PointerChecks
498/// overlap.
499///
500/// Returns a pair of instructions where the first element is the first
501/// instruction generated in possibly a sequence of instructions and the
502/// second value is the final comparator value or NULL if no check is needed.
503std::pair<Instruction *, Instruction *>
504addRuntimeChecks(Instruction *Loc, Loop *TheLoop,
505 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
506 SCEVExpander &Expander);
507
508/// Struct to hold information about a partially invariant condition.
509struct IVConditionInfo {
510 /// Instructions that need to be duplicated and checked for the unswitching
511 /// condition.
512 SmallVector<Instruction *> InstToDuplicate;
513
514 /// Constant to indicate for which value the condition is invariant.
515 Constant *KnownValue = nullptr;
4
Null pointer value stored to 'PartialIVInfo.KnownValue'
516
517 /// True if the partially invariant path is no-op (=does not have any
518 /// side-effects and no loop value is used outside the loop).
519 bool PathIsNoop = true;
520
521 /// If the partially invariant path reaches a single exit block, ExitForPath
522 /// is set to that block. Otherwise it is nullptr.
523 BasicBlock *ExitForPath = nullptr;
524};
525
526/// Check if the loop header has a conditional branch that is not
527/// loop-invariant, because it involves load instructions. If all paths from
528/// either the true or false successor to the header or loop exists do not
529/// modify the memory feeding the condition, perform 'partial unswitching'. That
530/// is, duplicate the instructions feeding the condition in the pre-header. Then
531/// unswitch on the duplicated condition. The condition is now known in the
532/// unswitched version for the 'invariant' path through the original loop.
533///
534/// If the branch condition of the header is partially invariant, return a pair
535/// containing the instructions to duplicate and a boolean Constant to update
536/// the condition in the loops created for the true or false successors.
537Optional<IVConditionInfo> hasPartialIVCondition(Loop &L, unsigned MSSAThreshold,
538 MemorySSA &MSSA, AAResults &AA);
539
540} // end namespace llvm
541
542#endif // LLVM_TRANSFORMS_UTILS_LOOPUTILS_H

/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h

1//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the SmallVector class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_SMALLVECTOR_H
14#define LLVM_ADT_SMALLVECTOR_H
15
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/ErrorHandling.h"
19#include "llvm/Support/MemAlloc.h"
20#include "llvm/Support/type_traits.h"
21#include <algorithm>
22#include <cassert>
23#include <cstddef>
24#include <cstdlib>
25#include <cstring>
26#include <functional>
27#include <initializer_list>
28#include <iterator>
29#include <limits>
30#include <memory>
31#include <new>
32#include <type_traits>
33#include <utility>
34
35namespace llvm {
36
37/// This is all the stuff common to all SmallVectors.
38///
39/// The template parameter specifies the type which should be used to hold the
40/// Size and Capacity of the SmallVector, so it can be adjusted.
41/// Using 32 bit size is desirable to shrink the size of the SmallVector.
42/// Using 64 bit size is desirable for cases like SmallVector<char>, where a
43/// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
44/// buffering bitcode output - which can exceed 4GB.
45template <class Size_T> class SmallVectorBase {
46protected:
47 void *BeginX;
48 Size_T Size = 0, Capacity;
49
50 /// The maximum value of the Size_T used.
51 static constexpr size_t SizeTypeMax() {
52 return std::numeric_limits<Size_T>::max();
53 }
54
55 SmallVectorBase() = delete;
56 SmallVectorBase(void *FirstEl, size_t TotalCapacity)
57 : BeginX(FirstEl), Capacity(TotalCapacity) {}
58
59 /// This is a helper for \a grow() that's out of line to reduce code
60 /// duplication. This function will report a fatal error if it can't grow at
61 /// least to \p MinSize.
62 void *mallocForGrow(size_t MinSize, size_t TSize, size_t &NewCapacity);
63
64 /// This is an implementation of the grow() method which only works
65 /// on POD-like data types and is out of line to reduce code duplication.
66 /// This function will report a fatal error if it cannot increase capacity.
67 void grow_pod(void *FirstEl, size_t MinSize, size_t TSize);
68
69public:
70 size_t size() const { return Size; }
71 size_t capacity() const { return Capacity; }
72
73 LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { return !Size; }
10
Assuming field 'Size' is not equal to 0
11
Returning zero, which participates in a condition later
74
75 /// Set the array size to \p N, which the current array must have enough
76 /// capacity for.
77 ///
78 /// This does not construct or destroy any elements in the vector.
79 ///
80 /// Clients can use this in conjunction with capacity() to write past the end
81 /// of the buffer when they know that more elements are available, and only
82 /// update the size later. This avoids the cost of value initializing elements
83 /// which will only be overwritten.
84 void set_size(size_t N) {
85 assert(N <= capacity())(static_cast <bool> (N <= capacity()) ? void (0) : __assert_fail
("N <= capacity()", "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 Size = N;
87 }
88};
89
90template <class T>
91using SmallVectorSizeType =
92 typename std::conditional<sizeof(T) < 4 && sizeof(void *) >= 8, uint64_t,
93 uint32_t>::type;
94
95/// Figure out the offset of the first element.
96template <class T, typename = void> struct SmallVectorAlignmentAndSize {
97 alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof(
98 SmallVectorBase<SmallVectorSizeType<T>>)];
99 alignas(T) char FirstEl[sizeof(T)];
100};
101
102/// This is the part of SmallVectorTemplateBase which does not depend on whether
103/// the type T is a POD. The extra dummy template argument is used by ArrayRef
104/// to avoid unnecessarily requiring T to be complete.
105template <typename T, typename = void>
106class SmallVectorTemplateCommon
107 : public SmallVectorBase<SmallVectorSizeType<T>> {
108 using Base = SmallVectorBase<SmallVectorSizeType<T>>;
109
110 /// Find the address of the first element. For this pointer math to be valid
111 /// with small-size of 0 for T with lots of alignment, it's important that
112 /// SmallVectorStorage is properly-aligned even for small-size of 0.
113 void *getFirstEl() const {
114 return const_cast<void *>(reinterpret_cast<const void *>(
115 reinterpret_cast<const char *>(this) +
116 offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)__builtin_offsetof(SmallVectorAlignmentAndSize<T>, FirstEl
)
));
117 }
118 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
119
120protected:
121 SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {}
122
123 void grow_pod(size_t MinSize, size_t TSize) {
124 Base::grow_pod(getFirstEl(), MinSize, TSize);
125 }
126
127 /// Return true if this is a smallvector which has not had dynamic
128 /// memory allocated for it.
129 bool isSmall() const { return this->BeginX == getFirstEl(); }
130
131 /// Put this vector in a state of being small.
132 void resetToSmall() {
133 this->BeginX = getFirstEl();
134 this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
135 }
136
137 /// Return true if V is an internal reference to the given range.
138 bool isReferenceToRange(const void *V, const void *First, const void *Last) const {
139 // Use std::less to avoid UB.
140 std::less<> LessThan;
141 return !LessThan(V, First) && LessThan(V, Last);
142 }
143
144 /// Return true if V is an internal reference to this vector.
145 bool isReferenceToStorage(const void *V) const {
146 return isReferenceToRange(V, this->begin(), this->end());
147 }
148
149 /// Return true if First and Last form a valid (possibly empty) range in this
150 /// vector's storage.
151 bool isRangeInStorage(const void *First, const void *Last) const {
152 // Use std::less to avoid UB.
153 std::less<> LessThan;
154 return !LessThan(First, this->begin()) && !LessThan(Last, First) &&
155 !LessThan(this->end(), Last);
156 }
157
158 /// Return true unless Elt will be invalidated by resizing the vector to
159 /// NewSize.
160 bool isSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
161 // Past the end.
162 if (LLVM_LIKELY(!isReferenceToStorage(Elt))__builtin_expect((bool)(!isReferenceToStorage(Elt)), true))
163 return true;
164
165 // Return false if Elt will be destroyed by shrinking.
166 if (NewSize <= this->size())
167 return Elt < this->begin() + NewSize;
168
169 // Return false if we need to grow.
170 return NewSize <= this->capacity();
171 }
172
173 /// Check whether Elt will be invalidated by resizing the vector to NewSize.
174 void assertSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
175 assert(isSafeToReferenceAfterResize(Elt, NewSize) &&(static_cast <bool> (isSafeToReferenceAfterResize(Elt, NewSize
) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? void (0) : __assert_fail ("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 177, __extension__ __PRETTY_FUNCTION__))
176 "Attempting to reference an element of the vector in an operation "(static_cast <bool> (isSafeToReferenceAfterResize(Elt, NewSize
) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? void (0) : __assert_fail ("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 177, __extension__ __PRETTY_FUNCTION__))
177 "that invalidates it")(static_cast <bool> (isSafeToReferenceAfterResize(Elt, NewSize
) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? void (0) : __assert_fail ("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 177, __extension__ __PRETTY_FUNCTION__))
;
178 }
179
180 /// Check whether Elt will be invalidated by increasing the size of the
181 /// vector by N.
182 void assertSafeToAdd(const void *Elt, size_t N = 1) {
183 this->assertSafeToReferenceAfterResize(Elt, this->size() + N);
184 }
185
186 /// Check whether any part of the range will be invalidated by clearing.
187 void assertSafeToReferenceAfterClear(const T *From, const T *To) {
188 if (From == To)
189 return;
190 this->assertSafeToReferenceAfterResize(From, 0);
191 this->assertSafeToReferenceAfterResize(To - 1, 0);
192 }
193 template <
194 class ItTy,
195 std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
196 bool> = false>
197 void assertSafeToReferenceAfterClear(ItTy, ItTy) {}
198
199 /// Check whether any part of the range will be invalidated by growing.
200 void assertSafeToAddRange(const T *From, const T *To) {
201 if (From == To)
202 return;
203 this->assertSafeToAdd(From, To - From);
204 this->assertSafeToAdd(To - 1, To - From);
205 }
206 template <
207 class ItTy,
208 std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
209 bool> = false>
210 void assertSafeToAddRange(ItTy, ItTy) {}
211
212 /// Reserve enough space to add one element, and return the updated element
213 /// pointer in case it was a reference to the storage.
214 template <class U>
215 static const T *reserveForParamAndGetAddressImpl(U *This, const T &Elt,
216 size_t N) {
217 size_t NewSize = This->size() + N;
218 if (LLVM_LIKELY(NewSize <= This->capacity())__builtin_expect((bool)(NewSize <= This->capacity()), true
)
)
219 return &Elt;
220
221 bool ReferencesStorage = false;
222 int64_t Index = -1;
223 if (!U::TakesParamByValue) {
224 if (LLVM_UNLIKELY(This->isReferenceToStorage(&Elt))__builtin_expect((bool)(This->isReferenceToStorage(&Elt
)), false)
) {
225 ReferencesStorage = true;
226 Index = &Elt - This->begin();
227 }
228 }
229 This->grow(NewSize);
230 return ReferencesStorage ? This->begin() + Index : &Elt;
231 }
232
233public:
234 using size_type = size_t;
235 using difference_type = ptrdiff_t;
236 using value_type = T;
237 using iterator = T *;
238 using const_iterator = const T *;
239
240 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
241 using reverse_iterator = std::reverse_iterator<iterator>;
242
243 using reference = T &;
244 using const_reference = const T &;
245 using pointer = T *;
246 using const_pointer = const T *;
247
248 using Base::capacity;
249 using Base::empty;
250 using Base::size;
251
252 // forward iterator creation methods.
253 iterator begin() { return (iterator)this->BeginX; }
254 const_iterator begin() const { return (const_iterator)this->BeginX; }
255 iterator end() { return begin() + size(); }
256 const_iterator end() const { return begin() + size(); }
257
258 // reverse iterator creation methods.
259 reverse_iterator rbegin() { return reverse_iterator(end()); }
260 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
261 reverse_iterator rend() { return reverse_iterator(begin()); }
262 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
263
264 size_type size_in_bytes() const { return size() * sizeof(T); }
265 size_type max_size() const {
266 return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T));
267 }
268
269 size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
270
271 /// Return a pointer to the vector's buffer, even if empty().
272 pointer data() { return pointer(begin()); }
273 /// Return a pointer to the vector's buffer, even if empty().
274 const_pointer data() const { return const_pointer(begin()); }
275
276 reference operator[](size_type idx) {
277 assert(idx < size())(static_cast <bool> (idx < size()) ? void (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 277, __extension__ __PRETTY_FUNCTION__))
;
278 return begin()[idx];
279 }
280 const_reference operator[](size_type idx) const {
281 assert(idx < size())(static_cast <bool> (idx < size()) ? void (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 281, __extension__ __PRETTY_FUNCTION__))
;
282 return begin()[idx];
283 }
284
285 reference front() {
286 assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail
("!empty()", "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 286, __extension__ __PRETTY_FUNCTION__))
;
287 return begin()[0];
288 }
289 const_reference front() const {
290 assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail
("!empty()", "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 290, __extension__ __PRETTY_FUNCTION__))
;
291 return begin()[0];
292 }
293
294 reference back() {
295 assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail
("!empty()", "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 295, __extension__ __PRETTY_FUNCTION__))
;
296 return end()[-1];
297 }
298 const_reference back() const {
299 assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail
("!empty()", "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return end()[-1];
301 }
302};
303
304/// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put
305/// method implementations that are designed to work with non-trivial T's.
306///
307/// We approximate is_trivially_copyable with trivial move/copy construction and
308/// trivial destruction. While the standard doesn't specify that you're allowed
309/// copy these types with memcpy, there is no way for the type to observe this.
310/// This catches the important case of std::pair<POD, POD>, which is not
311/// trivially assignable.
312template <typename T, bool = (is_trivially_copy_constructible<T>::value) &&
313 (is_trivially_move_constructible<T>::value) &&
314 std::is_trivially_destructible<T>::value>
315class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
316 friend class SmallVectorTemplateCommon<T>;
317
318protected:
319 static constexpr bool TakesParamByValue = false;
320 using ValueParamT = const T &;
321
322 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
323
324 static void destroy_range(T *S, T *E) {
325 while (S != E) {
326 --E;
327 E->~T();
328 }
329 }
330
331 /// Move the range [I, E) into the uninitialized memory starting with "Dest",
332 /// constructing elements as needed.
333 template<typename It1, typename It2>
334 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
335 std::uninitialized_copy(std::make_move_iterator(I),
336 std::make_move_iterator(E), Dest);
337 }
338
339 /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
340 /// constructing elements as needed.
341 template<typename It1, typename It2>
342 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
343 std::uninitialized_copy(I, E, Dest);
344 }
345
346 /// Grow the allocated memory (without initializing new elements), doubling
347 /// the size of the allocated memory. Guarantees space for at least one more
348 /// element, or MinSize more elements if specified.
349 void grow(size_t MinSize = 0);
350
351 /// Create a new allocation big enough for \p MinSize and pass back its size
352 /// in \p NewCapacity. This is the first section of \a grow().
353 T *mallocForGrow(size_t MinSize, size_t &NewCapacity) {
354 return static_cast<T *>(
355 SmallVectorBase<SmallVectorSizeType<T>>::mallocForGrow(
356 MinSize, sizeof(T), NewCapacity));
357 }
358
359 /// Move existing elements over to the new allocation \p NewElts, the middle
360 /// section of \a grow().
361 void moveElementsForGrow(T *NewElts);
362
363 /// Transfer ownership of the allocation, finishing up \a grow().
364 void takeAllocationForGrow(T *NewElts, size_t NewCapacity);
365
366 /// Reserve enough space to add one element, and return the updated element
367 /// pointer in case it was a reference to the storage.
368 const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
369 return this->reserveForParamAndGetAddressImpl(this, Elt, N);
370 }
371
372 /// Reserve enough space to add one element, and return the updated element
373 /// pointer in case it was a reference to the storage.
374 T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
375 return const_cast<T *>(
376 this->reserveForParamAndGetAddressImpl(this, Elt, N));
377 }
378
379 static T &&forward_value_param(T &&V) { return std::move(V); }
380 static const T &forward_value_param(const T &V) { return V; }
381
382 void growAndAssign(size_t NumElts, const T &Elt) {
383 // Grow manually in case Elt is an internal reference.
384 size_t NewCapacity;
385 T *NewElts = mallocForGrow(NumElts, NewCapacity);
386 std::uninitialized_fill_n(NewElts, NumElts, Elt);
387 this->destroy_range(this->begin(), this->end());
388 takeAllocationForGrow(NewElts, NewCapacity);
389 this->set_size(NumElts);
390 }
391
392 template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
393 // Grow manually in case one of Args is an internal reference.
394 size_t NewCapacity;
395 T *NewElts = mallocForGrow(0, NewCapacity);
396 ::new ((void *)(NewElts + this->size())) T(std::forward<ArgTypes>(Args)...);
397 moveElementsForGrow(NewElts);
398 takeAllocationForGrow(NewElts, NewCapacity);
399 this->set_size(this->size() + 1);
400 return this->back();
401 }
402
403public:
404 void push_back(const T &Elt) {
405 const T *EltPtr = reserveForParamAndGetAddress(Elt);
406 ::new ((void *)this->end()) T(*EltPtr);
407 this->set_size(this->size() + 1);
408 }
409
410 void push_back(T &&Elt) {
411 T *EltPtr = reserveForParamAndGetAddress(Elt);
412 ::new ((void *)this->end()) T(::std::move(*EltPtr));
413 this->set_size(this->size() + 1);
414 }
415
416 void pop_back() {
417 this->set_size(this->size() - 1);
418 this->end()->~T();
419 }
420};
421
422// Define this out-of-line to dissuade the C++ compiler from inlining it.
423template <typename T, bool TriviallyCopyable>
424void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
425 size_t NewCapacity;
426 T *NewElts = mallocForGrow(MinSize, NewCapacity);
427 moveElementsForGrow(NewElts);
428 takeAllocationForGrow(NewElts, NewCapacity);
429}
430
431// Define this out-of-line to dissuade the C++ compiler from inlining it.
432template <typename T, bool TriviallyCopyable>
433void SmallVectorTemplateBase<T, TriviallyCopyable>::moveElementsForGrow(
434 T *NewElts) {
435 // Move the elements over.
436 this->uninitialized_move(this->begin(), this->end(), NewElts);
437
438 // Destroy the original elements.
439 destroy_range(this->begin(), this->end());
440}
441
442// Define this out-of-line to dissuade the C++ compiler from inlining it.
443template <typename T, bool TriviallyCopyable>
444void SmallVectorTemplateBase<T, TriviallyCopyable>::takeAllocationForGrow(
445 T *NewElts, size_t NewCapacity) {
446 // If this wasn't grown from the inline copy, deallocate the old space.
447 if (!this->isSmall())
448 free(this->begin());
449
450 this->BeginX = NewElts;
451 this->Capacity = NewCapacity;
452}
453
454/// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
455/// method implementations that are designed to work with trivially copyable
456/// T's. This allows using memcpy in place of copy/move construction and
457/// skipping destruction.
458template <typename T>
459class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
460 friend class SmallVectorTemplateCommon<T>;
461
462protected:
463 /// True if it's cheap enough to take parameters by value. Doing so avoids
464 /// overhead related to mitigations for reference invalidation.
465 static constexpr bool TakesParamByValue = sizeof(T) <= 2 * sizeof(void *);
466
467 /// Either const T& or T, depending on whether it's cheap enough to take
468 /// parameters by value.
469 using ValueParamT =
470 typename std::conditional<TakesParamByValue, T, const T &>::type;
471
472 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
473
474 // No need to do a destroy loop for POD's.
475 static void destroy_range(T *, T *) {}
476
477 /// Move the range [I, E) onto the uninitialized memory
478 /// starting with "Dest", constructing elements into it as needed.
479 template<typename It1, typename It2>
480 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
481 // Just do a copy.
482 uninitialized_copy(I, E, Dest);
483 }
484
485 /// Copy the range [I, E) onto the uninitialized memory
486 /// starting with "Dest", constructing elements into it as needed.
487 template<typename It1, typename It2>
488 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
489 // Arbitrary iterator types; just use the basic implementation.
490 std::uninitialized_copy(I, E, Dest);
491 }
492
493 /// Copy the range [I, E) onto the uninitialized memory
494 /// starting with "Dest", constructing elements into it as needed.
495 template <typename T1, typename T2>
496 static void uninitialized_copy(
497 T1 *I, T1 *E, T2 *Dest,
498 std::enable_if_t<std::is_same<typename std::remove_const<T1>::type,
499 T2>::value> * = nullptr) {
500 // Use memcpy for PODs iterated by pointers (which includes SmallVector
501 // iterators): std::uninitialized_copy optimizes to memmove, but we can
502 // use memcpy here. Note that I and E are iterators and thus might be
503 // invalid for memcpy if they are equal.
504 if (I != E)
505 memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T));
506 }
507
508 /// Double the size of the allocated memory, guaranteeing space for at
509 /// least one more element or MinSize if specified.
510 void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
511
512 /// Reserve enough space to add one element, and return the updated element
513 /// pointer in case it was a reference to the storage.
514 const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
515 return this->reserveForParamAndGetAddressImpl(this, Elt, N);
516 }
517
518 /// Reserve enough space to add one element, and return the updated element
519 /// pointer in case it was a reference to the storage.
520 T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
521 return const_cast<T *>(
522 this->reserveForParamAndGetAddressImpl(this, Elt, N));
523 }
524
525 /// Copy \p V or return a reference, depending on \a ValueParamT.
526 static ValueParamT forward_value_param(ValueParamT V) { return V; }
527
528 void growAndAssign(size_t NumElts, T Elt) {
529 // Elt has been copied in case it's an internal reference, side-stepping
530 // reference invalidation problems without losing the realloc optimization.
531 this->set_size(0);
532 this->grow(NumElts);
533 std::uninitialized_fill_n(this->begin(), NumElts, Elt);
534 this->set_size(NumElts);
535 }
536
537 template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
538 // Use push_back with a copy in case Args has an internal reference,
539 // side-stepping reference invalidation problems without losing the realloc
540 // optimization.
541 push_back(T(std::forward<ArgTypes>(Args)...));
542 return this->back();
543 }
544
545public:
546 void push_back(ValueParamT Elt) {
547 const T *EltPtr = reserveForParamAndGetAddress(Elt);
548 memcpy(reinterpret_cast<void *>(this->end()), EltPtr, sizeof(T));
549 this->set_size(this->size() + 1);
550 }
551
552 void pop_back() { this->set_size(this->size() - 1); }
553};
554
555/// This class consists of common code factored out of the SmallVector class to
556/// reduce code duplication based on the SmallVector 'N' template parameter.
557template <typename T>
558class SmallVectorImpl : public SmallVectorTemplateBase<T> {
559 using SuperClass = SmallVectorTemplateBase<T>;
560
561public:
562 using iterator = typename SuperClass::iterator;
563 using const_iterator = typename SuperClass::const_iterator;
564 using reference = typename SuperClass::reference;
565 using size_type = typename SuperClass::size_type;
566
567protected:
568 using SmallVectorTemplateBase<T>::TakesParamByValue;
569 using ValueParamT = typename SuperClass::ValueParamT;
570
571 // Default ctor - Initialize to empty.
572 explicit SmallVectorImpl(unsigned N)
573 : SmallVectorTemplateBase<T>(N) {}
574
575public:
576 SmallVectorImpl(const SmallVectorImpl &) = delete;
577
578 ~SmallVectorImpl() {
579 // Subclass has already destructed this vector's elements.
580 // If this wasn't grown from the inline copy, deallocate the old space.
581 if (!this->isSmall())
582 free(this->begin());
583 }
584
585 void clear() {
586 this->destroy_range(this->begin(), this->end());
587 this->Size = 0;
588 }
589
590private:
591 template <bool ForOverwrite> void resizeImpl(size_type N) {
592 if (N < this->size()) {
593 this->pop_back_n(this->size() - N);
594 } else if (N > this->size()) {
595 this->reserve(N);
596 for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
597 if (ForOverwrite)
598 new (&*I) T;
599 else
600 new (&*I) T();
601 this->set_size(N);
602 }
603 }
604
605public:
606 void resize(size_type N) { resizeImpl<false>(N); }
607
608 /// Like resize, but \ref T is POD, the new values won't be initialized.
609 void resize_for_overwrite(size_type N) { resizeImpl<true>(N); }
610
611 void resize(size_type N, ValueParamT NV) {
612 if (N == this->size())
613 return;
614
615 if (N < this->size()) {
616 this->pop_back_n(this->size() - N);
617 return;
618 }
619
620 // N > this->size(). Defer to append.
621 this->append(N - this->size(), NV);
622 }
623
624 void reserve(size_type N) {
625 if (this->capacity() < N)
626 this->grow(N);
627 }
628
629 void pop_back_n(size_type NumItems) {
630 assert(this->size() >= NumItems)(static_cast <bool> (this->size() >= NumItems) ? void
(0) : __assert_fail ("this->size() >= NumItems", "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 630, __extension__ __PRETTY_FUNCTION__))
;
631 this->destroy_range(this->end() - NumItems, this->end());
632 this->set_size(this->size() - NumItems);
633 }
634
635 LLVM_NODISCARD[[clang::warn_unused_result]] T pop_back_val() {
636 T Result = ::std::move(this->back());
637 this->pop_back();
638 return Result;
639 }
640
641 void swap(SmallVectorImpl &RHS);
642
643 /// Add the specified range to the end of the SmallVector.
644 template <typename in_iter,
645 typename = std::enable_if_t<std::is_convertible<
646 typename std::iterator_traits<in_iter>::iterator_category,
647 std::input_iterator_tag>::value>>
648 void append(in_iter in_start, in_iter in_end) {
649 this->assertSafeToAddRange(in_start, in_end);
650 size_type NumInputs = std::distance(in_start, in_end);
651 this->reserve(this->size() + NumInputs);
652 this->uninitialized_copy(in_start, in_end, this->end());
653 this->set_size(this->size() + NumInputs);
654 }
655
656 /// Append \p NumInputs copies of \p Elt to the end.
657 void append(size_type NumInputs, ValueParamT Elt) {
658 const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs);
659 std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr);
660 this->set_size(this->size() + NumInputs);
661 }
662
663 void append(std::initializer_list<T> IL) {
664 append(IL.begin(), IL.end());
665 }
666
667 void append(const SmallVectorImpl &RHS) { append(RHS.begin(), RHS.end()); }
668
669 void assign(size_type NumElts, ValueParamT Elt) {
670 // Note that Elt could be an internal reference.
671 if (NumElts > this->capacity()) {
672 this->growAndAssign(NumElts, Elt);
673 return;
674 }
675
676 // Assign over existing elements.
677 std::fill_n(this->begin(), std::min(NumElts, this->size()), Elt);
678 if (NumElts > this->size())
679 std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt);
680 else if (NumElts < this->size())
681 this->destroy_range(this->begin() + NumElts, this->end());
682 this->set_size(NumElts);
683 }
684
685 // FIXME: Consider assigning over existing elements, rather than clearing &
686 // re-initializing them - for all assign(...) variants.
687
688 template <typename in_iter,
689 typename = std::enable_if_t<std::is_convertible<
690 typename std::iterator_traits<in_iter>::iterator_category,
691 std::input_iterator_tag>::value>>
692 void assign(in_iter in_start, in_iter in_end) {
693 this->assertSafeToReferenceAfterClear(in_start, in_end);
694 clear();
695 append(in_start, in_end);
696 }
697
698 void assign(std::initializer_list<T> IL) {
699 clear();
700 append(IL);
701 }
702
703 void assign(const SmallVectorImpl &RHS) { assign(RHS.begin(), RHS.end()); }
704
705 iterator erase(const_iterator CI) {
706 // Just cast away constness because this is a non-const member function.
707 iterator I = const_cast<iterator>(CI);
708
709 assert(this->isReferenceToStorage(CI) && "Iterator to erase is out of bounds.")(static_cast <bool> (this->isReferenceToStorage(CI) &&
"Iterator to erase is out of bounds.") ? void (0) : __assert_fail
("this->isReferenceToStorage(CI) && \"Iterator to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 709, __extension__ __PRETTY_FUNCTION__))
;
710
711 iterator N = I;
712 // Shift all elts down one.
713 std::move(I+1, this->end(), I);
714 // Drop the last elt.
715 this->pop_back();
716 return(N);
717 }
718
719 iterator erase(const_iterator CS, const_iterator CE) {
720 // Just cast away constness because this is a non-const member function.
721 iterator S = const_cast<iterator>(CS);
722 iterator E = const_cast<iterator>(CE);
723
724 assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds.")(static_cast <bool> (this->isRangeInStorage(S, E) &&
"Range to erase is out of bounds.") ? void (0) : __assert_fail
("this->isRangeInStorage(S, E) && \"Range to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 724, __extension__ __PRETTY_FUNCTION__))
;
725
726 iterator N = S;
727 // Shift all elts down.
728 iterator I = std::move(E, this->end(), S);
729 // Drop the last elts.
730 this->destroy_range(I, this->end());
731 this->set_size(I - this->begin());
732 return(N);
733 }
734
735private:
736 template <class ArgType> iterator insert_one_impl(iterator I, ArgType &&Elt) {
737 // Callers ensure that ArgType is derived from T.
738 static_assert(
739 std::is_same<std::remove_const_t<std::remove_reference_t<ArgType>>,
740 T>::value,
741 "ArgType must be derived from T!");
742
743 if (I == this->end()) { // Important special case for empty vector.
744 this->push_back(::std::forward<ArgType>(Elt));
745 return this->end()-1;
746 }
747
748 assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.")(static_cast <bool> (this->isReferenceToStorage(I) &&
"Insertion iterator is out of bounds.") ? void (0) : __assert_fail
("this->isReferenceToStorage(I) && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 748, __extension__ __PRETTY_FUNCTION__))
;
749
750 // Grow if necessary.
751 size_t Index = I - this->begin();
752 std::remove_reference_t<ArgType> *EltPtr =
753 this->reserveForParamAndGetAddress(Elt);
754 I = this->begin() + Index;
755
756 ::new ((void*) this->end()) T(::std::move(this->back()));
757 // Push everything else over.
758 std::move_backward(I, this->end()-1, this->end());
759 this->set_size(this->size() + 1);
760
761 // If we just moved the element we're inserting, be sure to update
762 // the reference (never happens if TakesParamByValue).
763 static_assert(!TakesParamByValue || std::is_same<ArgType, T>::value,
764 "ArgType must be 'T' when taking by value!");
765 if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end()))
766 ++EltPtr;
767
768 *I = ::std::forward<ArgType>(*EltPtr);
769 return I;
770 }
771
772public:
773 iterator insert(iterator I, T &&Elt) {
774 return insert_one_impl(I, this->forward_value_param(std::move(Elt)));
775 }
776
777 iterator insert(iterator I, const T &Elt) {
778 return insert_one_impl(I, this->forward_value_param(Elt));
779 }
780
781 iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) {
782 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
783 size_t InsertElt = I - this->begin();
784
785 if (I == this->end()) { // Important special case for empty vector.
786 append(NumToInsert, Elt);
787 return this->begin()+InsertElt;
788 }
789
790 assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.")(static_cast <bool> (this->isReferenceToStorage(I) &&
"Insertion iterator is out of bounds.") ? void (0) : __assert_fail
("this->isReferenceToStorage(I) && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 790, __extension__ __PRETTY_FUNCTION__))
;
791
792 // Ensure there is enough space, and get the (maybe updated) address of
793 // Elt.
794 const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert);
795
796 // Uninvalidate the iterator.
797 I = this->begin()+InsertElt;
798
799 // If there are more elements between the insertion point and the end of the
800 // range than there are being inserted, we can use a simple approach to
801 // insertion. Since we already reserved space, we know that this won't
802 // reallocate the vector.
803 if (size_t(this->end()-I) >= NumToInsert) {
804 T *OldEnd = this->end();
805 append(std::move_iterator<iterator>(this->end() - NumToInsert),
806 std::move_iterator<iterator>(this->end()));
807
808 // Copy the existing elements that get replaced.
809 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
810
811 // If we just moved the element we're inserting, be sure to update
812 // the reference (never happens if TakesParamByValue).
813 if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
814 EltPtr += NumToInsert;
815
816 std::fill_n(I, NumToInsert, *EltPtr);
817 return I;
818 }
819
820 // Otherwise, we're inserting more elements than exist already, and we're
821 // not inserting at the end.
822
823 // Move over the elements that we're about to overwrite.
824 T *OldEnd = this->end();
825 this->set_size(this->size() + NumToInsert);
826 size_t NumOverwritten = OldEnd-I;
827 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
828
829 // If we just moved the element we're inserting, be sure to update
830 // the reference (never happens if TakesParamByValue).
831 if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
832 EltPtr += NumToInsert;
833
834 // Replace the overwritten part.
835 std::fill_n(I, NumOverwritten, *EltPtr);
836
837 // Insert the non-overwritten middle part.
838 std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr);
839 return I;
840 }
841
842 template <typename ItTy,
843 typename = std::enable_if_t<std::is_convertible<
844 typename std::iterator_traits<ItTy>::iterator_category,
845 std::input_iterator_tag>::value>>
846 iterator insert(iterator I, ItTy From, ItTy To) {
847 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
848 size_t InsertElt = I - this->begin();
849
850 if (I == this->end()) { // Important special case for empty vector.
851 append(From, To);
852 return this->begin()+InsertElt;
853 }
854
855 assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.")(static_cast <bool> (this->isReferenceToStorage(I) &&
"Insertion iterator is out of bounds.") ? void (0) : __assert_fail
("this->isReferenceToStorage(I) && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/ADT/SmallVector.h"
, 855, __extension__ __PRETTY_FUNCTION__))
;
856
857 // Check that the reserve that follows doesn't invalidate the iterators.
858 this->assertSafeToAddRange(From, To);
859
860 size_t NumToInsert = std::distance(From, To);
861
862 // Ensure there is enough space.
863 reserve(this->size() + NumToInsert);
864
865 // Uninvalidate the iterator.
866 I = this->begin()+InsertElt;
867
868 // If there are more elements between the insertion point and the end of the
869 // range than there are being inserted, we can use a simple approach to
870 // insertion. Since we already reserved space, we know that this won't
871 // reallocate the vector.
872 if (size_t(this->end()-I) >= NumToInsert) {
873 T *OldEnd = this->end();
874 append(std::move_iterator<iterator>(this->end() - NumToInsert),
875 std::move_iterator<iterator>(this->end()));
876
877 // Copy the existing elements that get replaced.
878 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
879
880 std::copy(From, To, I);
881 return I;
882 }
883
884 // Otherwise, we're inserting more elements than exist already, and we're
885 // not inserting at the end.
886
887 // Move over the elements that we're about to overwrite.
888 T *OldEnd = this->end();
889 this->set_size(this->size() + NumToInsert);
890 size_t NumOverwritten = OldEnd-I;
891 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
892
893 // Replace the overwritten part.
894 for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
895 *J = *From;
896 ++J; ++From;
897 }
898
899 // Insert the non-overwritten middle part.
900 this->uninitialized_copy(From, To, OldEnd);
901 return I;
902 }
903
904 void insert(iterator I, std::initializer_list<T> IL) {
905 insert(I, IL.begin(), IL.end());
906 }
907
908 template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
909 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
910 return this->growAndEmplaceBack(std::forward<ArgTypes>(Args)...);
911
912 ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
913 this->set_size(this->size() + 1);
914 return this->back();
915 }
916
917 SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
918
919 SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
920
921 bool operator==(const SmallVectorImpl &RHS) const {
922 if (this->size() != RHS.size()) return false;
923 return std::equal(this->begin(), this->end(), RHS.begin());
924 }
925 bool operator!=(const SmallVectorImpl &RHS) const {
926 return !(*this == RHS);
927 }
928
929 bool operator<(const SmallVectorImpl &RHS) const {
930 return std::lexicographical_compare(this->begin(), this->end(),
931 RHS.begin(), RHS.end());
932 }
933};
934
935template <typename T>
936void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
937 if (this == &RHS) return;
938
939 // We can only avoid copying elements if neither vector is small.
940 if (!this->isSmall() && !RHS.isSmall()) {
941 std::swap(this->BeginX, RHS.BeginX);
942 std::swap(this->Size, RHS.Size);
943 std::swap(this->Capacity, RHS.Capacity);
944 return;
945 }
946 this->reserve(RHS.size());
947 RHS.reserve(this->size());
948
949 // Swap the shared elements.
950 size_t NumShared = this->size();
951 if (NumShared > RHS.size()) NumShared = RHS.size();
952 for (size_type i = 0; i != NumShared; ++i)
953 std::swap((*this)[i], RHS[i]);
954
955 // Copy over the extra elts.
956 if (this->size() > RHS.size()) {
957 size_t EltDiff = this->size() - RHS.size();
958 this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
959 RHS.set_size(RHS.size() + EltDiff);
960 this->destroy_range(this->begin()+NumShared, this->end());
961 this->set_size(NumShared);
962 } else if (RHS.size() > this->size()) {
963 size_t EltDiff = RHS.size() - this->size();
964 this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
965 this->set_size(this->size() + EltDiff);
966 this->destroy_range(RHS.begin()+NumShared, RHS.end());
967 RHS.set_size(NumShared);
968 }
969}
970
971template <typename T>
972SmallVectorImpl<T> &SmallVectorImpl<T>::
973 operator=(const SmallVectorImpl<T> &RHS) {
974 // Avoid self-assignment.
975 if (this == &RHS) return *this;
976
977 // If we already have sufficient space, assign the common elements, then
978 // destroy any excess.
979 size_t RHSSize = RHS.size();
980 size_t CurSize = this->size();
981 if (CurSize >= RHSSize) {
982 // Assign common elements.
983 iterator NewEnd;
984 if (RHSSize)
985 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
986 else
987 NewEnd = this->begin();
988
989 // Destroy excess elements.
990 this->destroy_range(NewEnd, this->end());
991
992 // Trim.
993 this->set_size(RHSSize);
994 return *this;
995 }
996
997 // If we have to grow to have enough elements, destroy the current elements.
998 // This allows us to avoid copying them during the grow.
999 // FIXME: don't do this if they're efficiently moveable.
1000 if (this->capacity() < RHSSize) {
1001 // Destroy current elements.
1002 this->clear();
1003 CurSize = 0;
1004 this->grow(RHSSize);
1005 } else if (CurSize) {
1006 // Otherwise, use assignment for the already-constructed elements.
1007 std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
1008 }
1009
1010 // Copy construct the new elements in place.
1011 this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
1012 this->begin()+CurSize);
1013
1014 // Set end.
1015 this->set_size(RHSSize);
1016 return *this;
1017}
1018
1019template <typename T>
1020SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
1021 // Avoid self-assignment.
1022 if (this == &RHS) return *this;
1023
1024 // If the RHS isn't small, clear this vector and then steal its buffer.
1025 if (!RHS.isSmall()) {
1026 this->destroy_range(this->begin(), this->end());
1027 if (!this->isSmall()) free(this->begin());
1028 this->BeginX = RHS.BeginX;
1029 this->Size = RHS.Size;
1030 this->Capacity = RHS.Capacity;
1031 RHS.resetToSmall();
1032 return *this;
1033 }
1034
1035 // If we already have sufficient space, assign the common elements, then
1036 // destroy any excess.
1037 size_t RHSSize = RHS.size();
1038 size_t CurSize = this->size();
1039 if (CurSize >= RHSSize) {
1040 // Assign common elements.
1041 iterator NewEnd = this->begin();
1042 if (RHSSize)
1043 NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
1044
1045 // Destroy excess elements and trim the bounds.
1046 this->destroy_range(NewEnd, this->end());
1047 this->set_size(RHSSize);
1048
1049 // Clear the RHS.
1050 RHS.clear();
1051
1052 return *this;
1053 }
1054
1055 // If we have to grow to have enough elements, destroy the current elements.
1056 // This allows us to avoid copying them during the grow.
1057 // FIXME: this may not actually make any sense if we can efficiently move
1058 // elements.
1059 if (this->capacity() < RHSSize) {
1060 // Destroy current elements.
1061 this->clear();
1062 CurSize = 0;
1063 this->grow(RHSSize);
1064 } else if (CurSize) {
1065 // Otherwise, use assignment for the already-constructed elements.
1066 std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
1067 }
1068
1069 // Move-construct the new elements in place.
1070 this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
1071 this->begin()+CurSize);
1072
1073 // Set end.
1074 this->set_size(RHSSize);
1075
1076 RHS.clear();
1077 return *this;
1078}
1079
1080/// Storage for the SmallVector elements. This is specialized for the N=0 case
1081/// to avoid allocating unnecessary storage.
1082template <typename T, unsigned N>
1083struct SmallVectorStorage {
1084 alignas(T) char InlineElts[N * sizeof(T)];
1085};
1086
1087/// We need the storage to be properly aligned even for small-size of 0 so that
1088/// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
1089/// well-defined.
1090template <typename T> struct alignas(T) SmallVectorStorage<T, 0> {};
1091
1092/// Forward declaration of SmallVector so that
1093/// calculateSmallVectorDefaultInlinedElements can reference
1094/// `sizeof(SmallVector<T, 0>)`.
1095template <typename T, unsigned N> class LLVM_GSL_OWNER[[gsl::Owner]] SmallVector;
1096
1097/// Helper class for calculating the default number of inline elements for
1098/// `SmallVector<T>`.
1099///
1100/// This should be migrated to a constexpr function when our minimum
1101/// compiler support is enough for multi-statement constexpr functions.
1102template <typename T> struct CalculateSmallVectorDefaultInlinedElements {
1103 // Parameter controlling the default number of inlined elements
1104 // for `SmallVector<T>`.
1105 //
1106 // The default number of inlined elements ensures that
1107 // 1. There is at least one inlined element.
1108 // 2. `sizeof(SmallVector<T>) <= kPreferredSmallVectorSizeof` unless
1109 // it contradicts 1.
1110 static constexpr size_t kPreferredSmallVectorSizeof = 64;
1111
1112 // static_assert that sizeof(T) is not "too big".
1113 //
1114 // Because our policy guarantees at least one inlined element, it is possible
1115 // for an arbitrarily large inlined element to allocate an arbitrarily large
1116 // amount of inline storage. We generally consider it an antipattern for a
1117 // SmallVector to allocate an excessive amount of inline storage, so we want
1118 // to call attention to these cases and make sure that users are making an
1119 // intentional decision if they request a lot of inline storage.
1120 //
1121 // We want this assertion to trigger in pathological cases, but otherwise
1122 // not be too easy to hit. To accomplish that, the cutoff is actually somewhat
1123 // larger than kPreferredSmallVectorSizeof (otherwise,
1124 // `SmallVector<SmallVector<T>>` would be one easy way to trip it, and that
1125 // pattern seems useful in practice).
1126 //
1127 // One wrinkle is that this assertion is in theory non-portable, since
1128 // sizeof(T) is in general platform-dependent. However, we don't expect this
1129 // to be much of an issue, because most LLVM development happens on 64-bit
1130 // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for
1131 // 32-bit hosts, dodging the issue. The reverse situation, where development
1132 // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a
1133 // 64-bit host, is expected to be very rare.
1134 static_assert(
1135 sizeof(T) <= 256,
1136 "You are trying to use a default number of inlined elements for "
1137 "`SmallVector<T>` but `sizeof(T)` is really big! Please use an "
1138 "explicit number of inlined elements with `SmallVector<T, N>` to make "
1139 "sure you really want that much inline storage.");
1140
1141 // Discount the size of the header itself when calculating the maximum inline
1142 // bytes.
1143 static constexpr size_t PreferredInlineBytes =
1144 kPreferredSmallVectorSizeof - sizeof(SmallVector<T, 0>);
1145 static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T);
1146 static constexpr size_t value =
1147 NumElementsThatFit == 0 ? 1 : NumElementsThatFit;
1148};
1149
1150/// This is a 'vector' (really, a variable-sized array), optimized
1151/// for the case when the array is small. It contains some number of elements
1152/// in-place, which allows it to avoid heap allocation when the actual number of
1153/// elements is below that threshold. This allows normal "small" cases to be
1154/// fast without losing generality for large inputs.
1155///
1156/// \note
1157/// In the absence of a well-motivated choice for the number of inlined
1158/// elements \p N, it is recommended to use \c SmallVector<T> (that is,
1159/// omitting the \p N). This will choose a default number of inlined elements
1160/// reasonable for allocation on the stack (for example, trying to keep \c
1161/// sizeof(SmallVector<T>) around 64 bytes).
1162///
1163/// \warning This does not attempt to be exception safe.
1164///
1165/// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h
1166template <typename T,
1167 unsigned N = CalculateSmallVectorDefaultInlinedElements<T>::value>
1168class LLVM_GSL_OWNER[[gsl::Owner]] SmallVector : public SmallVectorImpl<T>,
1169 SmallVectorStorage<T, N> {
1170public:
1171 SmallVector() : SmallVectorImpl<T>(N) {}
1172
1173 ~SmallVector() {
1174 // Destroy the constructed elements in the vector.
1175 this->destroy_range(this->begin(), this->end());
1176 }
1177
1178 explicit SmallVector(size_t Size, const T &Value = T())
1179 : SmallVectorImpl<T>(N) {
1180 this->assign(Size, Value);
1181 }
1182
1183 template <typename ItTy,
1184 typename = std::enable_if_t<std::is_convertible<
1185 typename std::iterator_traits<ItTy>::iterator_category,
1186 std::input_iterator_tag>::value>>
1187 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
1188 this->append(S, E);
1189 }
1190
1191 template <typename RangeTy>
1192 explicit SmallVector(const iterator_range<RangeTy> &R)
1193 : SmallVectorImpl<T>(N) {
1194 this->append(R.begin(), R.end());
1195 }
1196
1197 SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
1198 this->assign(IL);
1199 }
1200
1201 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
1202 if (!RHS.empty())
1203 SmallVectorImpl<T>::operator=(RHS);
1204 }
1205
1206 SmallVector &operator=(const SmallVector &RHS) {
1207 SmallVectorImpl<T>::operator=(RHS);
1208 return *this;
1209 }
1210
1211 SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
1212 if (!RHS.empty())
1213 SmallVectorImpl<T>::operator=(::std::move(RHS));
1214 }
1215
1216 SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
1217 if (!RHS.empty())
1218 SmallVectorImpl<T>::operator=(::std::move(RHS));
1219 }
1220
1221 SmallVector &operator=(SmallVector &&RHS) {
1222 SmallVectorImpl<T>::operator=(::std::move(RHS));
1223 return *this;
1224 }
1225
1226 SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
1227 SmallVectorImpl<T>::operator=(::std::move(RHS));
1228 return *this;
1229 }
1230
1231 SmallVector &operator=(std::initializer_list<T> IL) {
1232 this->assign(IL);
1233 return *this;
1234 }
1235};
1236
1237template <typename T, unsigned N>
1238inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
1239 return X.capacity_in_bytes();
1240}
1241
1242/// Given a range of type R, iterate the entire range and return a
1243/// SmallVector with elements of the vector. This is useful, for example,
1244/// when you want to iterate a range and then sort the results.
1245template <unsigned Size, typename R>
1246SmallVector<typename std::remove_const<typename std::remove_reference<
1247 decltype(*std::begin(std::declval<R &>()))>::type>::type,
1248 Size>
1249to_vector(R &&Range) {
1250 return {std::begin(Range), std::end(Range)};
1251}
1252
1253} // end namespace llvm
1254
1255namespace std {
1256
1257 /// Implement std::swap in terms of SmallVector swap.
1258 template<typename T>
1259 inline void
1260 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
1261 LHS.swap(RHS);
1262 }
1263
1264 /// Implement std::swap in terms of SmallVector swap.
1265 template<typename T, unsigned N>
1266 inline void
1267 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
1268 LHS.swap(RHS);
1269 }
1270
1271} // end namespace std
1272
1273#endif // LLVM_ADT_SMALLVECTOR_H

/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/CFG.h

1//===-- Analysis/CFG.h - BasicBlock Analyses --------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This family of functions performs analyses on basic blocks, and instructions
10// contained within basic blocks.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_CFG_H
15#define LLVM_ANALYSIS_CFG_H
16
17#include "llvm/ADT/GraphTraits.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include <utility>
20
21namespace llvm {
22
23class BasicBlock;
24class DominatorTree;
25class Function;
26class Instruction;
27class LoopInfo;
28template <typename T> class SmallVectorImpl;
29
30/// Analyze the specified function to find all of the loop backedges in the
31/// function and return them. This is a relatively cheap (compared to
32/// computing dominators and loop info) analysis.
33///
34/// The output is added to Result, as pairs of <from,to> edge info.
35void FindFunctionBackedges(
36 const Function &F,
37 SmallVectorImpl<std::pair<const BasicBlock *, const BasicBlock *> > &
38 Result);
39
40/// Search for the specified successor of basic block BB and return its position
41/// in the terminator instruction's list of successors. It is an error to call
42/// this with a block that is not a successor.
43unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ);
44
45/// Return true if the specified edge is a critical edge. Critical edges are
46/// edges from a block with multiple successors to a block with multiple
47/// predecessors.
48///
49bool isCriticalEdge(const Instruction *TI, unsigned SuccNum,
50 bool AllowIdenticalEdges = false);
51bool isCriticalEdge(const Instruction *TI, const BasicBlock *Succ,
52 bool AllowIdenticalEdges = false);
53
54/// Determine whether instruction 'To' is reachable from 'From', without passing
55/// through any blocks in ExclusionSet, returning true if uncertain.
56///
57/// Determine whether there is a path from From to To within a single function.
58/// Returns false only if we can prove that once 'From' has been executed then
59/// 'To' can not be executed. Conservatively returns true.
60///
61/// This function is linear with respect to the number of blocks in the CFG,
62/// walking down successors from From to reach To, with a fixed threshold.
63/// Using DT or LI allows us to answer more quickly. LI reduces the cost of
64/// an entire loop of any number of blocks to be the same as the cost of a
65/// single block. DT reduces the cost by allowing the search to terminate when
66/// we find a block that dominates the block containing 'To'. DT is most useful
67/// on branchy code but not loops, and LI is most useful on code with loops but
68/// does not help on branchy code outside loops.
69bool isPotentiallyReachable(
70 const Instruction *From, const Instruction *To,
71 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet = nullptr,
72 const DominatorTree *DT = nullptr, const LoopInfo *LI = nullptr);
73
74/// Determine whether block 'To' is reachable from 'From', returning
75/// true if uncertain.
76///
77/// Determine whether there is a path from From to To within a single function.
78/// Returns false only if we can prove that once 'From' has been reached then
79/// 'To' can not be executed. Conservatively returns true.
80bool isPotentiallyReachable(
81 const BasicBlock *From, const BasicBlock *To,
82 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet = nullptr,
83 const DominatorTree *DT = nullptr, const LoopInfo *LI = nullptr);
84
85/// Determine whether there is at least one path from a block in
86