Bug Summary

File:llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
Warning:line 2911, 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 -ffp-contract=on -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~++20220128100846+e1a12767ee62/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~++20220128100846+e1a12767ee62/llvm/lib/Transforms/Scalar -I include -I /build/llvm-toolchain-snapshot-14~++20220128100846+e1a12767ee62/llvm/include -D _FORTIFY_SOURCE=2 -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 -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220128100846+e1a12767ee62/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220128100846+e1a12767ee62/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220128100846+e1a12767ee62/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220128100846+e1a12767ee62/= -O3 -Wno-unused-command-line-argument -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~++20220128100846+e1a12767ee62/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220128100846+e1a12767ee62/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220128100846+e1a12767ee62/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -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-2022-01-28-233020-220964-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220128100846+e1a12767ee62/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp

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

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

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

/build/llvm-toolchain-snapshot-14~++20220128100846+e1a12767ee62/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/// 'Worklist' to 'StopBB' without passing through any blocks in
87/// 'ExclusionSet', returning true if uncertain.
88///
89/// Determine whether there is a path from at least one block in Worklist to
90/// StopBB within a single function without passing through any of the blocks
91/// in 'ExclusionSet'. Returns false only if we can prove that once any block
92/// in 'Worklist' has been reached then 'StopBB' can not be executed.
93/// Conservatively returns true.
94bool isPotentiallyReachableFromMany(
95 SmallVectorImpl<BasicBlock *> &Worklist, BasicBlock *StopBB,
96 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet,
97 const DominatorTree *DT = nullptr, const LoopInfo *LI = nullptr);
98
99/// Return true if the control flow in \p RPOTraversal is irreducible.
100///
101/// This is a generic implementation to detect CFG irreducibility based on loop
102/// info analysis. It can be used for any kind of CFG (Loop, MachineLoop,
103/// Function, MachineFunction, etc.) by providing an RPO traversal (\p
104/// RPOTraversal) and the loop info analysis (\p LI) of the CFG. This utility
105/// function is only recommended when loop info analysis is available. If loop
106/// info analysis isn't available, please, don't compute it explicitly for this
107/// purpose. There are more efficient ways to detect CFG irreducibility that
108/// don't require recomputing loop info analysis (e.g., T1/T2 or Tarjan's
109/// algorithm).
110///
111/// Requirements:
112/// 1) GraphTraits must be implemented for NodeT type. It is used to access
113/// NodeT successors.
114// 2) \p RPOTraversal must be a valid reverse post-order traversal of the
115/// target CFG with begin()/end() iterator interfaces.
116/// 3) \p LI must be a valid LoopInfoBase that contains up-to-date loop
117/// analysis information of the CFG.
118///
119/// This algorithm uses the information about reducible loop back-edges already
120/// computed in \p LI. When a back-edge is found during the RPO traversal, the
121/// algorithm checks whether the back-edge is one of the reducible back-edges in
122/// loop info. If it isn't, the CFG is irreducible. For example, for the CFG
123/// below (canonical irreducible graph) loop info won't contain any loop, so the
124/// algorithm will return that the CFG is irreducible when checking the B <-
125/// -> C back-edge.
126///
127/// (A->B, A->C, B->C, C->B, C->D)