Bug Summary

File:llvm/lib/Transforms/Scalar/JumpThreading.cpp
Warning:line 1424, column 7
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 -disable-llvm-verifier -discard-value-names -main-file-name JumpThreading.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/lib/Transforms/Scalar -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-21-121427-42170-1 -x c++ /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp

1//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
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 implements the Jump Threading pass.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Transforms/Scalar/JumpThreading.h"
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/Optional.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
25#include "llvm/Analysis/CFG.h"
26#include "llvm/Analysis/ConstantFolding.h"
27#include "llvm/Analysis/DomTreeUpdater.h"
28#include "llvm/Analysis/GlobalsModRef.h"
29#include "llvm/Analysis/GuardUtils.h"
30#include "llvm/Analysis/InstructionSimplify.h"
31#include "llvm/Analysis/LazyValueInfo.h"
32#include "llvm/Analysis/Loads.h"
33#include "llvm/Analysis/LoopInfo.h"
34#include "llvm/Analysis/TargetLibraryInfo.h"
35#include "llvm/Analysis/ValueTracking.h"
36#include "llvm/IR/BasicBlock.h"
37#include "llvm/IR/CFG.h"
38#include "llvm/IR/Constant.h"
39#include "llvm/IR/ConstantRange.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
42#include "llvm/IR/Dominators.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/InstrTypes.h"
45#include "llvm/IR/Instruction.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/IntrinsicInst.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/MDBuilder.h"
51#include "llvm/IR/Metadata.h"
52#include "llvm/IR/Module.h"
53#include "llvm/IR/PassManager.h"
54#include "llvm/IR/PatternMatch.h"
55#include "llvm/IR/Type.h"
56#include "llvm/IR/Use.h"
57#include "llvm/IR/User.h"
58#include "llvm/IR/Value.h"
59#include "llvm/InitializePasses.h"
60#include "llvm/Pass.h"
61#include "llvm/Support/BlockFrequency.h"
62#include "llvm/Support/BranchProbability.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Debug.h"
66#include "llvm/Support/raw_ostream.h"
67#include "llvm/Transforms/Scalar.h"
68#include "llvm/Transforms/Utils/BasicBlockUtils.h"
69#include "llvm/Transforms/Utils/Cloning.h"
70#include "llvm/Transforms/Utils/Local.h"
71#include "llvm/Transforms/Utils/SSAUpdater.h"
72#include "llvm/Transforms/Utils/ValueMapper.h"
73#include <algorithm>
74#include <cassert>
75#include <cstddef>
76#include <cstdint>
77#include <iterator>
78#include <memory>
79#include <utility>
80
81using namespace llvm;
82using namespace jumpthreading;
83
84#define DEBUG_TYPE"jump-threading" "jump-threading"
85
86STATISTIC(NumThreads, "Number of jumps threaded")static llvm::Statistic NumThreads = {"jump-threading", "NumThreads"
, "Number of jumps threaded"}
;
87STATISTIC(NumFolds, "Number of terminators folded")static llvm::Statistic NumFolds = {"jump-threading", "NumFolds"
, "Number of terminators folded"}
;
88STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi")static llvm::Statistic NumDupes = {"jump-threading", "NumDupes"
, "Number of branch blocks duplicated to eliminate phi"}
;
89
90static cl::opt<unsigned>
91BBDuplicateThreshold("jump-threading-threshold",
92 cl::desc("Max block size to duplicate for jump threading"),
93 cl::init(6), cl::Hidden);
94
95static cl::opt<unsigned>
96ImplicationSearchThreshold(
97 "jump-threading-implication-search-threshold",
98 cl::desc("The number of predecessors to search for a stronger "
99 "condition to use to thread over a weaker condition"),
100 cl::init(3), cl::Hidden);
101
102static cl::opt<bool> PrintLVIAfterJumpThreading(
103 "print-lvi-after-jump-threading",
104 cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false),
105 cl::Hidden);
106
107static cl::opt<bool> JumpThreadingFreezeSelectCond(
108 "jump-threading-freeze-select-cond",
109 cl::desc("Freeze the condition when unfolding select"), cl::init(false),
110 cl::Hidden);
111
112static cl::opt<bool> ThreadAcrossLoopHeaders(
113 "jump-threading-across-loop-headers",
114 cl::desc("Allow JumpThreading to thread across loop headers, for testing"),
115 cl::init(false), cl::Hidden);
116
117
118namespace {
119
120 /// This pass performs 'jump threading', which looks at blocks that have
121 /// multiple predecessors and multiple successors. If one or more of the
122 /// predecessors of the block can be proven to always jump to one of the
123 /// successors, we forward the edge from the predecessor to the successor by
124 /// duplicating the contents of this block.
125 ///
126 /// An example of when this can occur is code like this:
127 ///
128 /// if () { ...
129 /// X = 4;
130 /// }
131 /// if (X < 3) {
132 ///
133 /// In this case, the unconditional branch at the end of the first if can be
134 /// revectored to the false side of the second if.
135 class JumpThreading : public FunctionPass {
136 JumpThreadingPass Impl;
137
138 public:
139 static char ID; // Pass identification
140
141 JumpThreading(bool InsertFreezeWhenUnfoldingSelect = false, int T = -1)
142 : FunctionPass(ID), Impl(InsertFreezeWhenUnfoldingSelect, T) {
143 initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
144 }
145
146 bool runOnFunction(Function &F) override;
147
148 void getAnalysisUsage(AnalysisUsage &AU) const override {
149 AU.addRequired<DominatorTreeWrapperPass>();
150 AU.addPreserved<DominatorTreeWrapperPass>();
151 AU.addRequired<AAResultsWrapperPass>();
152 AU.addRequired<LazyValueInfoWrapperPass>();
153 AU.addPreserved<LazyValueInfoWrapperPass>();
154 AU.addPreserved<GlobalsAAWrapperPass>();
155 AU.addRequired<TargetLibraryInfoWrapperPass>();
156 }
157
158 void releaseMemory() override { Impl.releaseMemory(); }
159 };
160
161} // end anonymous namespace
162
163char JumpThreading::ID = 0;
164
165INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",static void *initializeJumpThreadingPassOnce(PassRegistry &
Registry) {
166 "Jump Threading", false, false)static void *initializeJumpThreadingPassOnce(PassRegistry &
Registry) {
167INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
168INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)initializeLazyValueInfoWrapperPassPass(Registry);
169INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
170INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
171INITIALIZE_PASS_END(JumpThreading, "jump-threading",PassInfo *PI = new PassInfo( "Jump Threading", "jump-threading"
, &JumpThreading::ID, PassInfo::NormalCtor_t(callDefaultCtor
<JumpThreading>), false, false); Registry.registerPass(
*PI, true); return PI; } static llvm::once_flag InitializeJumpThreadingPassFlag
; void llvm::initializeJumpThreadingPass(PassRegistry &Registry
) { llvm::call_once(InitializeJumpThreadingPassFlag, initializeJumpThreadingPassOnce
, std::ref(Registry)); }
172 "Jump Threading", false, false)PassInfo *PI = new PassInfo( "Jump Threading", "jump-threading"
, &JumpThreading::ID, PassInfo::NormalCtor_t(callDefaultCtor
<JumpThreading>), false, false); Registry.registerPass(
*PI, true); return PI; } static llvm::once_flag InitializeJumpThreadingPassFlag
; void llvm::initializeJumpThreadingPass(PassRegistry &Registry
) { llvm::call_once(InitializeJumpThreadingPassFlag, initializeJumpThreadingPassOnce
, std::ref(Registry)); }
173
174// Public interface to the Jump Threading pass
175FunctionPass *llvm::createJumpThreadingPass(bool InsertFr, int Threshold) {
176 return new JumpThreading(InsertFr, Threshold);
177}
178
179JumpThreadingPass::JumpThreadingPass(bool InsertFr, int T) {
180 InsertFreezeWhenUnfoldingSelect = JumpThreadingFreezeSelectCond | InsertFr;
181 DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
182}
183
184// Update branch probability information according to conditional
185// branch probability. This is usually made possible for cloned branches
186// in inline instances by the context specific profile in the caller.
187// For instance,
188//
189// [Block PredBB]
190// [Branch PredBr]
191// if (t) {
192// Block A;
193// } else {
194// Block B;
195// }
196//
197// [Block BB]
198// cond = PN([true, %A], [..., %B]); // PHI node
199// [Branch CondBr]
200// if (cond) {
201// ... // P(cond == true) = 1%
202// }
203//
204// Here we know that when block A is taken, cond must be true, which means
205// P(cond == true | A) = 1
206//
207// Given that P(cond == true) = P(cond == true | A) * P(A) +
208// P(cond == true | B) * P(B)
209// we get:
210// P(cond == true ) = P(A) + P(cond == true | B) * P(B)
211//
212// which gives us:
213// P(A) is less than P(cond == true), i.e.
214// P(t == true) <= P(cond == true)
215//
216// In other words, if we know P(cond == true) is unlikely, we know
217// that P(t == true) is also unlikely.
218//
219static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) {
220 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
221 if (!CondBr)
222 return;
223
224 uint64_t TrueWeight, FalseWeight;
225 if (!CondBr->extractProfMetadata(TrueWeight, FalseWeight))
226 return;
227
228 if (TrueWeight + FalseWeight == 0)
229 // Zero branch_weights do not give a hint for getting branch probabilities.
230 // Technically it would result in division by zero denominator, which is
231 // TrueWeight + FalseWeight.
232 return;
233
234 // Returns the outgoing edge of the dominating predecessor block
235 // that leads to the PhiNode's incoming block:
236 auto GetPredOutEdge =
237 [](BasicBlock *IncomingBB,
238 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
239 auto *PredBB = IncomingBB;
240 auto *SuccBB = PhiBB;
241 SmallPtrSet<BasicBlock *, 16> Visited;
242 while (true) {
243 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
244 if (PredBr && PredBr->isConditional())
245 return {PredBB, SuccBB};
246 Visited.insert(PredBB);
247 auto *SinglePredBB = PredBB->getSinglePredecessor();
248 if (!SinglePredBB)
249 return {nullptr, nullptr};
250
251 // Stop searching when SinglePredBB has been visited. It means we see
252 // an unreachable loop.
253 if (Visited.count(SinglePredBB))
254 return {nullptr, nullptr};
255
256 SuccBB = PredBB;
257 PredBB = SinglePredBB;
258 }
259 };
260
261 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
262 Value *PhiOpnd = PN->getIncomingValue(i);
263 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
264
265 if (!CI || !CI->getType()->isIntegerTy(1))
266 continue;
267
268 BranchProbability BP =
269 (CI->isOne() ? BranchProbability::getBranchProbability(
270 TrueWeight, TrueWeight + FalseWeight)
271 : BranchProbability::getBranchProbability(
272 FalseWeight, TrueWeight + FalseWeight));
273
274 auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB);
275 if (!PredOutEdge.first)
276 return;
277
278 BasicBlock *PredBB = PredOutEdge.first;
279 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
280 if (!PredBr)
281 return;
282
283 uint64_t PredTrueWeight, PredFalseWeight;
284 // FIXME: We currently only set the profile data when it is missing.
285 // With PGO, this can be used to refine even existing profile data with
286 // context information. This needs to be done after more performance
287 // testing.
288 if (PredBr->extractProfMetadata(PredTrueWeight, PredFalseWeight))
289 continue;
290
291 // We can not infer anything useful when BP >= 50%, because BP is the
292 // upper bound probability value.
293 if (BP >= BranchProbability(50, 100))
294 continue;
295
296 SmallVector<uint32_t, 2> Weights;
297 if (PredBr->getSuccessor(0) == PredOutEdge.second) {
298 Weights.push_back(BP.getNumerator());
299 Weights.push_back(BP.getCompl().getNumerator());
300 } else {
301 Weights.push_back(BP.getCompl().getNumerator());
302 Weights.push_back(BP.getNumerator());
303 }
304 PredBr->setMetadata(LLVMContext::MD_prof,
305 MDBuilder(PredBr->getParent()->getContext())
306 .createBranchWeights(Weights));
307 }
308}
309
310/// runOnFunction - Toplevel algorithm.
311bool JumpThreading::runOnFunction(Function &F) {
312 if (skipFunction(F))
313 return false;
314 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
315 auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
316 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
317 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
318 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
319 std::unique_ptr<BlockFrequencyInfo> BFI;
320 std::unique_ptr<BranchProbabilityInfo> BPI;
321 if (F.hasProfileData()) {
322 LoopInfo LI{DominatorTree(F)};
323 BPI.reset(new BranchProbabilityInfo(F, LI, TLI));
324 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
325 }
326
327 bool Changed = Impl.runImpl(F, TLI, LVI, AA, &DTU, F.hasProfileData(),
328 std::move(BFI), std::move(BPI));
329 if (PrintLVIAfterJumpThreading) {
330 dbgs() << "LVI for function '" << F.getName() << "':\n";
331 LVI->printLVI(F, DTU.getDomTree(), dbgs());
332 }
333 return Changed;
334}
335
336PreservedAnalyses JumpThreadingPass::run(Function &F,
337 FunctionAnalysisManager &AM) {
338 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
339 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
340 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
341 auto &AA = AM.getResult<AAManager>(F);
342 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
343
344 std::unique_ptr<BlockFrequencyInfo> BFI;
345 std::unique_ptr<BranchProbabilityInfo> BPI;
346 if (F.hasProfileData()) {
347 LoopInfo LI{DominatorTree(F)};
348 BPI.reset(new BranchProbabilityInfo(F, LI, &TLI));
349 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
350 }
351
352 bool Changed = runImpl(F, &TLI, &LVI, &AA, &DTU, F.hasProfileData(),
353 std::move(BFI), std::move(BPI));
354
355 if (!Changed)
356 return PreservedAnalyses::all();
357 PreservedAnalyses PA;
358 PA.preserve<GlobalsAA>();
359 PA.preserve<DominatorTreeAnalysis>();
360 PA.preserve<LazyValueAnalysis>();
361 return PA;
362}
363
364bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
365 LazyValueInfo *LVI_, AliasAnalysis *AA_,
366 DomTreeUpdater *DTU_, bool HasProfileData_,
367 std::unique_ptr<BlockFrequencyInfo> BFI_,
368 std::unique_ptr<BranchProbabilityInfo> BPI_) {
369 LLVM_DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "Jump threading on function '"
<< F.getName() << "'\n"; } } while (false)
;
370 TLI = TLI_;
371 LVI = LVI_;
372 AA = AA_;
373 DTU = DTU_;
374 BFI.reset();
375 BPI.reset();
376 // When profile data is available, we need to update edge weights after
377 // successful jump threading, which requires both BPI and BFI being available.
378 HasProfileData = HasProfileData_;
379 auto *GuardDecl = F.getParent()->getFunction(
380 Intrinsic::getName(Intrinsic::experimental_guard));
381 HasGuards = GuardDecl && !GuardDecl->use_empty();
382 if (HasProfileData) {
383 BPI = std::move(BPI_);
384 BFI = std::move(BFI_);
385 }
386
387 // Reduce the number of instructions duplicated when optimizing strictly for
388 // size.
389 if (BBDuplicateThreshold.getNumOccurrences())
390 BBDupThreshold = BBDuplicateThreshold;
391 else if (F.hasFnAttribute(Attribute::MinSize))
392 BBDupThreshold = 3;
393 else
394 BBDupThreshold = DefaultBBDupThreshold;
395
396 // JumpThreading must not processes blocks unreachable from entry. It's a
397 // waste of compute time and can potentially lead to hangs.
398 SmallPtrSet<BasicBlock *, 16> Unreachable;
399 assert(DTU && "DTU isn't passed into JumpThreading before using it.")((DTU && "DTU isn't passed into JumpThreading before using it."
) ? static_cast<void> (0) : __assert_fail ("DTU && \"DTU isn't passed into JumpThreading before using it.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 399, __PRETTY_FUNCTION__))
;
400 assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed.")((DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed."
) ? static_cast<void> (0) : __assert_fail ("DTU->hasDomTree() && \"JumpThreading relies on DomTree to proceed.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 400, __PRETTY_FUNCTION__))
;
401 DominatorTree &DT = DTU->getDomTree();
402 for (auto &BB : F)
403 if (!DT.isReachableFromEntry(&BB))
404 Unreachable.insert(&BB);
405
406 if (!ThreadAcrossLoopHeaders)
407 FindLoopHeaders(F);
408
409 bool EverChanged = false;
410 bool Changed;
411 do {
412 Changed = false;
413 for (auto &BB : F) {
414 if (Unreachable.count(&BB))
415 continue;
416 while (ProcessBlock(&BB)) // Thread all of the branches we can over BB.
417 Changed = true;
418
419 // Jump threading may have introduced redundant debug values into BB
420 // which should be removed.
421 if (Changed)
422 RemoveRedundantDbgInstrs(&BB);
423
424 // Stop processing BB if it's the entry or is now deleted. The following
425 // routines attempt to eliminate BB and locating a suitable replacement
426 // for the entry is non-trivial.
427 if (&BB == &F.getEntryBlock() || DTU->isBBPendingDeletion(&BB))
428 continue;
429
430 if (pred_empty(&BB)) {
431 // When ProcessBlock makes BB unreachable it doesn't bother to fix up
432 // the instructions in it. We must remove BB to prevent invalid IR.
433 LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " JT: Deleting dead block '"
<< BB.getName() << "' with terminator: " <<
*BB.getTerminator() << '\n'; } } while (false)
434 << "' with terminator: " << *BB.getTerminator()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " JT: Deleting dead block '"
<< BB.getName() << "' with terminator: " <<
*BB.getTerminator() << '\n'; } } while (false)
435 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " JT: Deleting dead block '"
<< BB.getName() << "' with terminator: " <<
*BB.getTerminator() << '\n'; } } while (false)
;
436 LoopHeaders.erase(&BB);
437 LVI->eraseBlock(&BB);
438 DeleteDeadBlock(&BB, DTU);
439 Changed = true;
440 continue;
441 }
442
443 // ProcessBlock doesn't thread BBs with unconditional TIs. However, if BB
444 // is "almost empty", we attempt to merge BB with its sole successor.
445 auto *BI = dyn_cast<BranchInst>(BB.getTerminator());
446 if (BI && BI->isUnconditional()) {
447 BasicBlock *Succ = BI->getSuccessor(0);
448 if (
449 // The terminator must be the only non-phi instruction in BB.
450 BB.getFirstNonPHIOrDbg()->isTerminator() &&
451 // Don't alter Loop headers and latches to ensure another pass can
452 // detect and transform nested loops later.
453 !LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) &&
454 TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU)) {
455 RemoveRedundantDbgInstrs(Succ);
456 // BB is valid for cleanup here because we passed in DTU. F remains
457 // BB's parent until a DTU->getDomTree() event.
458 LVI->eraseBlock(&BB);
459 Changed = true;
460 }
461 }
462 }
463 EverChanged |= Changed;
464 } while (Changed);
465
466 LoopHeaders.clear();
467 return EverChanged;
468}
469
470// Replace uses of Cond with ToVal when safe to do so. If all uses are
471// replaced, we can remove Cond. We cannot blindly replace all uses of Cond
472// because we may incorrectly replace uses when guards/assumes are uses of
473// of `Cond` and we used the guards/assume to reason about the `Cond` value
474// at the end of block. RAUW unconditionally replaces all uses
475// including the guards/assumes themselves and the uses before the
476// guard/assume.
477static void ReplaceFoldableUses(Instruction *Cond, Value *ToVal) {
478 assert(Cond->getType() == ToVal->getType())((Cond->getType() == ToVal->getType()) ? static_cast<
void> (0) : __assert_fail ("Cond->getType() == ToVal->getType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 478, __PRETTY_FUNCTION__))
;
479 auto *BB = Cond->getParent();
480 // We can unconditionally replace all uses in non-local blocks (i.e. uses
481 // strictly dominated by BB), since LVI information is true from the
482 // terminator of BB.
483 replaceNonLocalUsesWith(Cond, ToVal);
484 for (Instruction &I : reverse(*BB)) {
485 // Reached the Cond whose uses we are trying to replace, so there are no
486 // more uses.
487 if (&I == Cond)
488 break;
489 // We only replace uses in instructions that are guaranteed to reach the end
490 // of BB, where we know Cond is ToVal.
491 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
492 break;
493 I.replaceUsesOfWith(Cond, ToVal);
494 }
495 if (Cond->use_empty() && !Cond->mayHaveSideEffects())
496 Cond->eraseFromParent();
497}
498
499/// Return the cost of duplicating a piece of this block from first non-phi
500/// and before StopAt instruction to thread across it. Stop scanning the block
501/// when exceeding the threshold. If duplication is impossible, returns ~0U.
502static unsigned getJumpThreadDuplicationCost(BasicBlock *BB,
503 Instruction *StopAt,
504 unsigned Threshold) {
505 assert(StopAt->getParent() == BB && "Not an instruction from proper BB?")((StopAt->getParent() == BB && "Not an instruction from proper BB?"
) ? static_cast<void> (0) : __assert_fail ("StopAt->getParent() == BB && \"Not an instruction from proper BB?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 505, __PRETTY_FUNCTION__))
;
506 /// Ignore PHI nodes, these will be flattened when duplication happens.
507 BasicBlock::const_iterator I(BB->getFirstNonPHI());
508
509 // FIXME: THREADING will delete values that are just used to compute the
510 // branch, so they shouldn't count against the duplication cost.
511
512 unsigned Bonus = 0;
513 if (BB->getTerminator() == StopAt) {
514 // Threading through a switch statement is particularly profitable. If this
515 // block ends in a switch, decrease its cost to make it more likely to
516 // happen.
517 if (isa<SwitchInst>(StopAt))
518 Bonus = 6;
519
520 // The same holds for indirect branches, but slightly more so.
521 if (isa<IndirectBrInst>(StopAt))
522 Bonus = 8;
523 }
524
525 // Bump the threshold up so the early exit from the loop doesn't skip the
526 // terminator-based Size adjustment at the end.
527 Threshold += Bonus;
528
529 // Sum up the cost of each instruction until we get to the terminator. Don't
530 // include the terminator because the copy won't include it.
531 unsigned Size = 0;
532 for (; &*I != StopAt; ++I) {
533
534 // Stop scanning the block if we've reached the threshold.
535 if (Size > Threshold)
536 return Size;
537
538 // Debugger intrinsics don't incur code size.
539 if (isa<DbgInfoIntrinsic>(I)) continue;
540
541 // If this is a pointer->pointer bitcast, it is free.
542 if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
543 continue;
544
545 // Freeze instruction is free, too.
546 if (isa<FreezeInst>(I))
547 continue;
548
549 // Bail out if this instruction gives back a token type, it is not possible
550 // to duplicate it if it is used outside this BB.
551 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
552 return ~0U;
553
554 // All other instructions count for at least one unit.
555 ++Size;
556
557 // Calls are more expensive. If they are non-intrinsic calls, we model them
558 // as having cost of 4. If they are a non-vector intrinsic, we model them
559 // as having cost of 2 total, and if they are a vector intrinsic, we model
560 // them as having cost 1.
561 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
562 if (CI->cannotDuplicate() || CI->isConvergent())
563 // Blocks with NoDuplicate are modelled as having infinite cost, so they
564 // are never duplicated.
565 return ~0U;
566 else if (!isa<IntrinsicInst>(CI))
567 Size += 3;
568 else if (!CI->getType()->isVectorTy())
569 Size += 1;
570 }
571 }
572
573 return Size > Bonus ? Size - Bonus : 0;
574}
575
576/// FindLoopHeaders - We do not want jump threading to turn proper loop
577/// structures into irreducible loops. Doing this breaks up the loop nesting
578/// hierarchy and pessimizes later transformations. To prevent this from
579/// happening, we first have to find the loop headers. Here we approximate this
580/// by finding targets of backedges in the CFG.
581///
582/// Note that there definitely are cases when we want to allow threading of
583/// edges across a loop header. For example, threading a jump from outside the
584/// loop (the preheader) to an exit block of the loop is definitely profitable.
585/// It is also almost always profitable to thread backedges from within the loop
586/// to exit blocks, and is often profitable to thread backedges to other blocks
587/// within the loop (forming a nested loop). This simple analysis is not rich
588/// enough to track all of these properties and keep it up-to-date as the CFG
589/// mutates, so we don't allow any of these transformations.
590void JumpThreadingPass::FindLoopHeaders(Function &F) {
591 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
592 FindFunctionBackedges(F, Edges);
593
594 for (const auto &Edge : Edges)
595 LoopHeaders.insert(Edge.second);
596}
597
598/// getKnownConstant - Helper method to determine if we can thread over a
599/// terminator with the given value as its condition, and if so what value to
600/// use for that. What kind of value this is depends on whether we want an
601/// integer or a block address, but an undef is always accepted.
602/// Returns null if Val is null or not an appropriate constant.
603static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
604 if (!Val)
605 return nullptr;
606
607 // Undef is "known" enough.
608 if (UndefValue *U = dyn_cast<UndefValue>(Val))
609 return U;
610
611 if (Preference == WantBlockAddress)
612 return dyn_cast<BlockAddress>(Val->stripPointerCasts());
613
614 return dyn_cast<ConstantInt>(Val);
615}
616
617/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
618/// if we can infer that the value is a known ConstantInt/BlockAddress or undef
619/// in any of our predecessors. If so, return the known list of value and pred
620/// BB in the result vector.
621///
622/// This returns true if there were any known values.
623bool JumpThreadingPass::ComputeValueKnownInPredecessorsImpl(
624 Value *V, BasicBlock *BB, PredValueInfo &Result,
625 ConstantPreference Preference, DenseSet<Value *> &RecursionSet,
626 Instruction *CxtI) {
627 // This method walks up use-def chains recursively. Because of this, we could
628 // get into an infinite loop going around loops in the use-def chain. To
629 // prevent this, keep track of what (value, block) pairs we've already visited
630 // and terminate the search if we loop back to them
631 if (!RecursionSet.insert(V).second)
632 return false;
633
634 // If V is a constant, then it is known in all predecessors.
635 if (Constant *KC = getKnownConstant(V, Preference)) {
636 for (BasicBlock *Pred : predecessors(BB))
637 Result.emplace_back(KC, Pred);
638
639 return !Result.empty();
640 }
641
642 // If V is a non-instruction value, or an instruction in a different block,
643 // then it can't be derived from a PHI.
644 Instruction *I = dyn_cast<Instruction>(V);
645 if (!I || I->getParent() != BB) {
646
647 // Okay, if this is a live-in value, see if it has a known value at the end
648 // of any of our predecessors.
649 //
650 // FIXME: This should be an edge property, not a block end property.
651 /// TODO: Per PR2563, we could infer value range information about a
652 /// predecessor based on its terminator.
653 //
654 // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
655 // "I" is a non-local compare-with-a-constant instruction. This would be
656 // able to handle value inequalities better, for example if the compare is
657 // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
658 // Perhaps getConstantOnEdge should be smart enough to do this?
659 for (BasicBlock *P : predecessors(BB)) {
660 // If the value is known by LazyValueInfo to be a constant in a
661 // predecessor, use that information to try to thread this block.
662 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
663 if (Constant *KC = getKnownConstant(PredCst, Preference))
664 Result.emplace_back(KC, P);
665 }
666
667 return !Result.empty();
668 }
669
670 /// If I is a PHI node, then we know the incoming values for any constants.
671 if (PHINode *PN = dyn_cast<PHINode>(I)) {
672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
673 Value *InVal = PN->getIncomingValue(i);
674 if (Constant *KC = getKnownConstant(InVal, Preference)) {
675 Result.emplace_back(KC, PN->getIncomingBlock(i));
676 } else {
677 Constant *CI = LVI->getConstantOnEdge(InVal,
678 PN->getIncomingBlock(i),
679 BB, CxtI);
680 if (Constant *KC = getKnownConstant(CI, Preference))
681 Result.emplace_back(KC, PN->getIncomingBlock(i));
682 }
683 }
684
685 return !Result.empty();
686 }
687
688 // Handle Cast instructions.
689 if (CastInst *CI = dyn_cast<CastInst>(I)) {
690 Value *Source = CI->getOperand(0);
691 ComputeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
692 RecursionSet, CxtI);
693 if (Result.empty())
694 return false;
695
696 // Convert the known values.
697 for (auto &R : Result)
698 R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType());
699
700 return true;
701 }
702
703 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
704 Value *Source = FI->getOperand(0);
705 ComputeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
706 RecursionSet, CxtI);
707
708 erase_if(Result, [](auto &Pair) {
709 return !isGuaranteedNotToBeUndefOrPoison(Pair.first);
710 });
711
712 return !Result.empty();
713 }
714
715 // Handle some boolean conditions.
716 if (I->getType()->getPrimitiveSizeInBits() == 1) {
717 assert(Preference == WantInteger && "One-bit non-integer type?")((Preference == WantInteger && "One-bit non-integer type?"
) ? static_cast<void> (0) : __assert_fail ("Preference == WantInteger && \"One-bit non-integer type?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 717, __PRETTY_FUNCTION__))
;
718 // X | true -> true
719 // X & false -> false
720 if (I->getOpcode() == Instruction::Or ||
721 I->getOpcode() == Instruction::And) {
722 PredValueInfoTy LHSVals, RHSVals;
723
724 ComputeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
725 WantInteger, RecursionSet, CxtI);
726 ComputeValueKnownInPredecessorsImpl(I->getOperand(1), BB, RHSVals,
727 WantInteger, RecursionSet, CxtI);
728
729 if (LHSVals.empty() && RHSVals.empty())
730 return false;
731
732 ConstantInt *InterestingVal;
733 if (I->getOpcode() == Instruction::Or)
734 InterestingVal = ConstantInt::getTrue(I->getContext());
735 else
736 InterestingVal = ConstantInt::getFalse(I->getContext());
737
738 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
739
740 // Scan for the sentinel. If we find an undef, force it to the
741 // interesting value: x|undef -> true and x&undef -> false.
742 for (const auto &LHSVal : LHSVals)
743 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
744 Result.emplace_back(InterestingVal, LHSVal.second);
745 LHSKnownBBs.insert(LHSVal.second);
746 }
747 for (const auto &RHSVal : RHSVals)
748 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
749 // If we already inferred a value for this block on the LHS, don't
750 // re-add it.
751 if (!LHSKnownBBs.count(RHSVal.second))
752 Result.emplace_back(InterestingVal, RHSVal.second);
753 }
754
755 return !Result.empty();
756 }
757
758 // Handle the NOT form of XOR.
759 if (I->getOpcode() == Instruction::Xor &&
760 isa<ConstantInt>(I->getOperand(1)) &&
761 cast<ConstantInt>(I->getOperand(1))->isOne()) {
762 ComputeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result,
763 WantInteger, RecursionSet, CxtI);
764 if (Result.empty())
765 return false;
766
767 // Invert the known values.
768 for (auto &R : Result)
769 R.first = ConstantExpr::getNot(R.first);
770
771 return true;
772 }
773
774 // Try to simplify some other binary operator values.
775 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
776 assert(Preference != WantBlockAddress((Preference != WantBlockAddress && "A binary operator creating a block address?"
) ? static_cast<void> (0) : __assert_fail ("Preference != WantBlockAddress && \"A binary operator creating a block address?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 777, __PRETTY_FUNCTION__))
777 && "A binary operator creating a block address?")((Preference != WantBlockAddress && "A binary operator creating a block address?"
) ? static_cast<void> (0) : __assert_fail ("Preference != WantBlockAddress && \"A binary operator creating a block address?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 777, __PRETTY_FUNCTION__))
;
778 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
779 PredValueInfoTy LHSVals;
780 ComputeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
781 WantInteger, RecursionSet, CxtI);
782
783 // Try to use constant folding to simplify the binary operator.
784 for (const auto &LHSVal : LHSVals) {
785 Constant *V = LHSVal.first;
786 Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
787
788 if (Constant *KC = getKnownConstant(Folded, WantInteger))
789 Result.emplace_back(KC, LHSVal.second);
790 }
791 }
792
793 return !Result.empty();
794 }
795
796 // Handle compare with phi operand, where the PHI is defined in this block.
797 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
798 assert(Preference == WantInteger && "Compares only produce integers")((Preference == WantInteger && "Compares only produce integers"
) ? static_cast<void> (0) : __assert_fail ("Preference == WantInteger && \"Compares only produce integers\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 798, __PRETTY_FUNCTION__))
;
799 Type *CmpType = Cmp->getType();
800 Value *CmpLHS = Cmp->getOperand(0);
801 Value *CmpRHS = Cmp->getOperand(1);
802 CmpInst::Predicate Pred = Cmp->getPredicate();
803
804 PHINode *PN = dyn_cast<PHINode>(CmpLHS);
805 if (!PN)
806 PN = dyn_cast<PHINode>(CmpRHS);
807 if (PN && PN->getParent() == BB) {
808 const DataLayout &DL = PN->getModule()->getDataLayout();
809 // We can do this simplification if any comparisons fold to true or false.
810 // See if any do.
811 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
812 BasicBlock *PredBB = PN->getIncomingBlock(i);
813 Value *LHS, *RHS;
814 if (PN == CmpLHS) {
815 LHS = PN->getIncomingValue(i);
816 RHS = CmpRHS->DoPHITranslation(BB, PredBB);
817 } else {
818 LHS = CmpLHS->DoPHITranslation(BB, PredBB);
819 RHS = PN->getIncomingValue(i);
820 }
821 Value *Res = SimplifyCmpInst(Pred, LHS, RHS, {DL});
822 if (!Res) {
823 if (!isa<Constant>(RHS))
824 continue;
825
826 // getPredicateOnEdge call will make no sense if LHS is defined in BB.
827 auto LHSInst = dyn_cast<Instruction>(LHS);
828 if (LHSInst && LHSInst->getParent() == BB)
829 continue;
830
831 LazyValueInfo::Tristate
832 ResT = LVI->getPredicateOnEdge(Pred, LHS,
833 cast<Constant>(RHS), PredBB, BB,
834 CxtI ? CxtI : Cmp);
835 if (ResT == LazyValueInfo::Unknown)
836 continue;
837 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
838 }
839
840 if (Constant *KC = getKnownConstant(Res, WantInteger))
841 Result.emplace_back(KC, PredBB);
842 }
843
844 return !Result.empty();
845 }
846
847 // If comparing a live-in value against a constant, see if we know the
848 // live-in value on any predecessors.
849 if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) {
850 Constant *CmpConst = cast<Constant>(CmpRHS);
851
852 if (!isa<Instruction>(CmpLHS) ||
853 cast<Instruction>(CmpLHS)->getParent() != BB) {
854 for (BasicBlock *P : predecessors(BB)) {
855 // If the value is known by LazyValueInfo to be a constant in a
856 // predecessor, use that information to try to thread this block.
857 LazyValueInfo::Tristate Res =
858 LVI->getPredicateOnEdge(Pred, CmpLHS,
859 CmpConst, P, BB, CxtI ? CxtI : Cmp);
860 if (Res == LazyValueInfo::Unknown)
861 continue;
862
863 Constant *ResC = ConstantInt::get(CmpType, Res);
864 Result.emplace_back(ResC, P);
865 }
866
867 return !Result.empty();
868 }
869
870 // InstCombine can fold some forms of constant range checks into
871 // (icmp (add (x, C1)), C2). See if we have we have such a thing with
872 // x as a live-in.
873 {
874 using namespace PatternMatch;
875
876 Value *AddLHS;
877 ConstantInt *AddConst;
878 if (isa<ConstantInt>(CmpConst) &&
879 match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
880 if (!isa<Instruction>(AddLHS) ||
881 cast<Instruction>(AddLHS)->getParent() != BB) {
882 for (BasicBlock *P : predecessors(BB)) {
883 // If the value is known by LazyValueInfo to be a ConstantRange in
884 // a predecessor, use that information to try to thread this
885 // block.
886 ConstantRange CR = LVI->getConstantRangeOnEdge(
887 AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
888 // Propagate the range through the addition.
889 CR = CR.add(AddConst->getValue());
890
891 // Get the range where the compare returns true.
892 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
893 Pred, cast<ConstantInt>(CmpConst)->getValue());
894
895 Constant *ResC;
896 if (CmpRange.contains(CR))
897 ResC = ConstantInt::getTrue(CmpType);
898 else if (CmpRange.inverse().contains(CR))
899 ResC = ConstantInt::getFalse(CmpType);
900 else
901 continue;
902
903 Result.emplace_back(ResC, P);
904 }
905
906 return !Result.empty();
907 }
908 }
909 }
910
911 // Try to find a constant value for the LHS of a comparison,
912 // and evaluate it statically if we can.
913 PredValueInfoTy LHSVals;
914 ComputeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
915 WantInteger, RecursionSet, CxtI);
916
917 for (const auto &LHSVal : LHSVals) {
918 Constant *V = LHSVal.first;
919 Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst);
920 if (Constant *KC = getKnownConstant(Folded, WantInteger))
921 Result.emplace_back(KC, LHSVal.second);
922 }
923
924 return !Result.empty();
925 }
926 }
927
928 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
929 // Handle select instructions where at least one operand is a known constant
930 // and we can figure out the condition value for any predecessor block.
931 Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
932 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
933 PredValueInfoTy Conds;
934 if ((TrueVal || FalseVal) &&
935 ComputeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds,
936 WantInteger, RecursionSet, CxtI)) {
937 for (auto &C : Conds) {
938 Constant *Cond = C.first;
939
940 // Figure out what value to use for the condition.
941 bool KnownCond;
942 if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
943 // A known boolean.
944 KnownCond = CI->isOne();
945 } else {
946 assert(isa<UndefValue>(Cond) && "Unexpected condition value")((isa<UndefValue>(Cond) && "Unexpected condition value"
) ? static_cast<void> (0) : __assert_fail ("isa<UndefValue>(Cond) && \"Unexpected condition value\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 946, __PRETTY_FUNCTION__))
;
947 // Either operand will do, so be sure to pick the one that's a known
948 // constant.
949 // FIXME: Do this more cleverly if both values are known constants?
950 KnownCond = (TrueVal != nullptr);
951 }
952
953 // See if the select has a known constant value for this predecessor.
954 if (Constant *Val = KnownCond ? TrueVal : FalseVal)
955 Result.emplace_back(Val, C.second);
956 }
957
958 return !Result.empty();
959 }
960 }
961
962 // If all else fails, see if LVI can figure out a constant value for us.
963 assert(CxtI->getParent() == BB && "CxtI should be in BB")((CxtI->getParent() == BB && "CxtI should be in BB"
) ? static_cast<void> (0) : __assert_fail ("CxtI->getParent() == BB && \"CxtI should be in BB\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 963, __PRETTY_FUNCTION__))
;
964 Constant *CI = LVI->getConstant(V, CxtI);
965 if (Constant *KC = getKnownConstant(CI, Preference)) {
966 for (BasicBlock *Pred : predecessors(BB))
967 Result.emplace_back(KC, Pred);
968 }
969
970 return !Result.empty();
971}
972
973/// GetBestDestForBranchOnUndef - If we determine that the specified block ends
974/// in an undefined jump, decide which block is best to revector to.
975///
976/// Since we can pick an arbitrary destination, we pick the successor with the
977/// fewest predecessors. This should reduce the in-degree of the others.
978static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
979 Instruction *BBTerm = BB->getTerminator();
980 unsigned MinSucc = 0;
981 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
982 // Compute the successor with the minimum number of predecessors.
983 unsigned MinNumPreds = pred_size(TestBB);
984 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
985 TestBB = BBTerm->getSuccessor(i);
986 unsigned NumPreds = pred_size(TestBB);
987 if (NumPreds < MinNumPreds) {
988 MinSucc = i;
989 MinNumPreds = NumPreds;
990 }
991 }
992
993 return MinSucc;
994}
995
996static bool hasAddressTakenAndUsed(BasicBlock *BB) {
997 if (!BB->hasAddressTaken()) return false;
998
999 // If the block has its address taken, it may be a tree of dead constants
1000 // hanging off of it. These shouldn't keep the block alive.
1001 BlockAddress *BA = BlockAddress::get(BB);
1002 BA->removeDeadConstantUsers();
1003 return !BA->use_empty();
1004}
1005
1006/// ProcessBlock - If there are any predecessors whose control can be threaded
1007/// through to a successor, transform them now.
1008bool JumpThreadingPass::ProcessBlock(BasicBlock *BB) {
1009 // If the block is trivially dead, just return and let the caller nuke it.
1010 // This simplifies other transformations.
1011 if (DTU->isBBPendingDeletion(BB) ||
1012 (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()))
1013 return false;
1014
1015 // If this block has a single predecessor, and if that pred has a single
1016 // successor, merge the blocks. This encourages recursive jump threading
1017 // because now the condition in this block can be threaded through
1018 // predecessors of our predecessor block.
1019 if (MaybeMergeBasicBlockIntoOnlyPred(BB))
1020 return true;
1021
1022 if (TryToUnfoldSelectInCurrBB(BB))
1023 return true;
1024
1025 // Look if we can propagate guards to predecessors.
1026 if (HasGuards && ProcessGuards(BB))
1027 return true;
1028
1029 // What kind of constant we're looking for.
1030 ConstantPreference Preference = WantInteger;
1031
1032 // Look to see if the terminator is a conditional branch, switch or indirect
1033 // branch, if not we can't thread it.
1034 Value *Condition;
1035 Instruction *Terminator = BB->getTerminator();
1036 if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
1037 // Can't thread an unconditional jump.
1038 if (BI->isUnconditional()) return false;
1039 Condition = BI->getCondition();
1040 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
1041 Condition = SI->getCondition();
1042 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
1043 // Can't thread indirect branch with no successors.
1044 if (IB->getNumSuccessors() == 0) return false;
1045 Condition = IB->getAddress()->stripPointerCasts();
1046 Preference = WantBlockAddress;
1047 } else {
1048 return false; // Must be an invoke or callbr.
1049 }
1050
1051 // Keep track if we constant folded the condition in this invocation.
1052 bool ConstantFolded = false;
1053
1054 // Run constant folding to see if we can reduce the condition to a simple
1055 // constant.
1056 if (Instruction *I = dyn_cast<Instruction>(Condition)) {
1057 Value *SimpleVal =
1058 ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
1059 if (SimpleVal) {
1060 I->replaceAllUsesWith(SimpleVal);
1061 if (isInstructionTriviallyDead(I, TLI))
1062 I->eraseFromParent();
1063 Condition = SimpleVal;
1064 ConstantFolded = true;
1065 }
1066 }
1067
1068 // If the terminator is branching on an undef or freeze undef, we can pick any
1069 // of the successors to branch to. Let GetBestDestForJumpOnUndef decide.
1070 auto *FI = dyn_cast<FreezeInst>(Condition);
1071 if (isa<UndefValue>(Condition) ||
1072 (FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) {
1073 unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
1074 std::vector<DominatorTree::UpdateType> Updates;
1075
1076 // Fold the branch/switch.
1077 Instruction *BBTerm = BB->getTerminator();
1078 Updates.reserve(BBTerm->getNumSuccessors());
1079 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
1080 if (i == BestSucc) continue;
1081 BasicBlock *Succ = BBTerm->getSuccessor(i);
1082 Succ->removePredecessor(BB, true);
1083 Updates.push_back({DominatorTree::Delete, BB, Succ});
1084 }
1085
1086 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding undef terminator: " <<
*BBTerm << '\n'; } } while (false)
1087 << "' folding undef terminator: " << *BBTerm << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding undef terminator: " <<
*BBTerm << '\n'; } } while (false)
;
1088 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
1089 BBTerm->eraseFromParent();
1090 DTU->applyUpdatesPermissive(Updates);
1091 if (FI)
1092 FI->eraseFromParent();
1093 return true;
1094 }
1095
1096 // If the terminator of this block is branching on a constant, simplify the
1097 // terminator to an unconditional branch. This can occur due to threading in
1098 // other blocks.
1099 if (getKnownConstant(Condition, Preference)) {
1100 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding terminator: " << *
BB->getTerminator() << '\n'; } } while (false)
1101 << "' folding terminator: " << *BB->getTerminator()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding terminator: " << *
BB->getTerminator() << '\n'; } } while (false)
1102 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " In block '" <<
BB->getName() << "' folding terminator: " << *
BB->getTerminator() << '\n'; } } while (false)
;
1103 ++NumFolds;
1104 ConstantFoldTerminator(BB, true, nullptr, DTU);
1105 return true;
1106 }
1107
1108 Instruction *CondInst = dyn_cast<Instruction>(Condition);
1109
1110 // All the rest of our checks depend on the condition being an instruction.
1111 if (!CondInst) {
1112 // FIXME: Unify this with code below.
1113 if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
1114 return true;
1115 return ConstantFolded;
1116 }
1117
1118 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
1119 // If we're branching on a conditional, LVI might be able to determine
1120 // it's value at the branch instruction. We only handle comparisons
1121 // against a constant at this time.
1122 // TODO: This should be extended to handle switches as well.
1123 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
1124 Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
1125 if (CondBr && CondConst) {
1126 // We should have returned as soon as we turn a conditional branch to
1127 // unconditional. Because its no longer interesting as far as jump
1128 // threading is concerned.
1129 assert(CondBr->isConditional() && "Threading on unconditional terminator")((CondBr->isConditional() && "Threading on unconditional terminator"
) ? static_cast<void> (0) : __assert_fail ("CondBr->isConditional() && \"Threading on unconditional terminator\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1129, __PRETTY_FUNCTION__))
;
1130
1131 LazyValueInfo::Tristate Ret =
1132 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1133 CondConst, CondBr);
1134 if (Ret != LazyValueInfo::Unknown) {
1135 unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0;
1136 unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1;
1137 BasicBlock *ToRemoveSucc = CondBr->getSuccessor(ToRemove);
1138 ToRemoveSucc->removePredecessor(BB, true);
1139 BranchInst *UncondBr =
1140 BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
1141 UncondBr->setDebugLoc(CondBr->getDebugLoc());
1142 CondBr->eraseFromParent();
1143 if (CondCmp->use_empty())
1144 CondCmp->eraseFromParent();
1145 // We can safely replace *some* uses of the CondInst if it has
1146 // exactly one value as returned by LVI. RAUW is incorrect in the
1147 // presence of guards and assumes, that have the `Cond` as the use. This
1148 // is because we use the guards/assume to reason about the `Cond` value
1149 // at the end of block, but RAUW unconditionally replaces all uses
1150 // including the guards/assumes themselves and the uses before the
1151 // guard/assume.
1152 else if (CondCmp->getParent() == BB) {
1153 auto *CI = Ret == LazyValueInfo::True ?
1154 ConstantInt::getTrue(CondCmp->getType()) :
1155 ConstantInt::getFalse(CondCmp->getType());
1156 ReplaceFoldableUses(CondCmp, CI);
1157 }
1158 DTU->applyUpdatesPermissive(
1159 {{DominatorTree::Delete, BB, ToRemoveSucc}});
1160 return true;
1161 }
1162
1163 // We did not manage to simplify this branch, try to see whether
1164 // CondCmp depends on a known phi-select pattern.
1165 if (TryToUnfoldSelect(CondCmp, BB))
1166 return true;
1167 }
1168 }
1169
1170 if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
1171 if (TryToUnfoldSelect(SI, BB))
1172 return true;
1173
1174 // Check for some cases that are worth simplifying. Right now we want to look
1175 // for loads that are used by a switch or by the condition for the branch. If
1176 // we see one, check to see if it's partially redundant. If so, insert a PHI
1177 // which can then be used to thread the values.
1178 Value *SimplifyValue = CondInst;
1179
1180 if (auto *FI = dyn_cast<FreezeInst>(SimplifyValue))
1181 // Look into freeze's operand
1182 SimplifyValue = FI->getOperand(0);
1183
1184 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
1185 if (isa<Constant>(CondCmp->getOperand(1)))
1186 SimplifyValue = CondCmp->getOperand(0);
1187
1188 // TODO: There are other places where load PRE would be profitable, such as
1189 // more complex comparisons.
1190 if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
1191 if (SimplifyPartiallyRedundantLoad(LoadI))
1192 return true;
1193
1194 // Before threading, try to propagate profile data backwards:
1195 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
1196 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1197 updatePredecessorProfileMetadata(PN, BB);
1198
1199 // Handle a variety of cases where we are branching on something derived from
1200 // a PHI node in the current block. If we can prove that any predecessors
1201 // compute a predictable value based on a PHI node, thread those predecessors.
1202 if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
1203 return true;
1204
1205 // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in
1206 // the current block, see if we can simplify.
1207 PHINode *PN = dyn_cast<PHINode>(
1208 isa<FreezeInst>(CondInst) ? cast<FreezeInst>(CondInst)->getOperand(0)
1209 : CondInst);
1210
1211 if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1212 return ProcessBranchOnPHI(PN);
1213
1214 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
1215 if (CondInst->getOpcode() == Instruction::Xor &&
1216 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1217 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
1218
1219 // Search for a stronger dominating condition that can be used to simplify a
1220 // conditional branch leaving BB.
1221 if (ProcessImpliedCondition(BB))
1222 return true;
1223
1224 return false;
1225}
1226
1227bool JumpThreadingPass::ProcessImpliedCondition(BasicBlock *BB) {
1228 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
1229 if (!BI || !BI->isConditional())
1230 return false;
1231
1232 Value *Cond = BI->getCondition();
1233 BasicBlock *CurrentBB = BB;
1234 BasicBlock *CurrentPred = BB->getSinglePredecessor();
1235 unsigned Iter = 0;
1236
1237 auto &DL = BB->getModule()->getDataLayout();
1238
1239 while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
1240 auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
1241 if (!PBI || !PBI->isConditional())
1242 return false;
1243 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1244 return false;
1245
1246 bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB;
1247 Optional<bool> Implication =
1248 isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue);
1249 if (Implication) {
1250 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1251 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1252 RemoveSucc->removePredecessor(BB);
1253 BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI);
1254 UncondBI->setDebugLoc(BI->getDebugLoc());
1255 BI->eraseFromParent();
1256 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}});
1257 return true;
1258 }
1259 CurrentBB = CurrentPred;
1260 CurrentPred = CurrentBB->getSinglePredecessor();
1261 }
1262
1263 return false;
1264}
1265
1266/// Return true if Op is an instruction defined in the given block.
1267static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
1268 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
12
Assuming 'OpInst' is null
13
Taking false branch
1269 if (OpInst->getParent() == BB)
1270 return true;
1271 return false;
14
Returning zero, which participates in a condition later
1272}
1273
1274/// SimplifyPartiallyRedundantLoad - If LoadI is an obviously partially
1275/// redundant load instruction, eliminate it by replacing it with a PHI node.
1276/// This is an important optimization that encourages jump threading, and needs
1277/// to be run interlaced with other jump threading tasks.
1278bool JumpThreadingPass::SimplifyPartiallyRedundantLoad(LoadInst *LoadI) {
1279 // Don't hack volatile and ordered loads.
1280 if (!LoadI->isUnordered()) return false;
1
Calling 'LoadInst::isUnordered'
5
Returning from 'LoadInst::isUnordered'
6
Taking false branch
1281
1282 // If the load is defined in a block with exactly one predecessor, it can't be
1283 // partially redundant.
1284 BasicBlock *LoadBB = LoadI->getParent();
1285 if (LoadBB->getSinglePredecessor())
7
Assuming the condition is false
8
Taking false branch
1286 return false;
1287
1288 // If the load is defined in an EH pad, it can't be partially redundant,
1289 // because the edges between the invoke and the EH pad cannot have other
1290 // instructions between them.
1291 if (LoadBB->isEHPad())
9
Assuming the condition is false
10
Taking false branch
1292 return false;
1293
1294 Value *LoadedPtr = LoadI->getOperand(0);
1295
1296 // If the loaded operand is defined in the LoadBB and its not a phi,
1297 // it can't be available in predecessors.
1298 if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
11
Calling 'isOpDefinedInBlock'
15
Returning from 'isOpDefinedInBlock'
1299 return false;
1300
1301 // Scan a few instructions up from the load, to see if it is obviously live at
1302 // the entry to its block.
1303 BasicBlock::iterator BBIt(LoadI);
1304 bool IsLoadCSE;
1305 if (Value *AvailableVal = FindAvailableLoadedValue(
16
Assuming 'AvailableVal' is null
17
Taking false branch
1306 LoadI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) {
1307 // If the value of the load is locally available within the block, just use
1308 // it. This frequently occurs for reg2mem'd allocas.
1309
1310 if (IsLoadCSE) {
1311 LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
1312 combineMetadataForCSE(NLoadI, LoadI, false);
1313 };
1314
1315 // If the returned value is the load itself, replace with an undef. This can
1316 // only happen in dead loops.
1317 if (AvailableVal == LoadI)
1318 AvailableVal = UndefValue::get(LoadI->getType());
1319 if (AvailableVal->getType() != LoadI->getType())
1320 AvailableVal = CastInst::CreateBitOrPointerCast(
1321 AvailableVal, LoadI->getType(), "", LoadI);
1322 LoadI->replaceAllUsesWith(AvailableVal);
1323 LoadI->eraseFromParent();
1324 return true;
1325 }
1326
1327 // Otherwise, if we scanned the whole block and got to the top of the block,
1328 // we know the block is locally transparent to the load. If not, something
1329 // might clobber its value.
1330 if (BBIt != LoadBB->begin())
18
Calling 'operator!='
21
Returning from 'operator!='
22
Taking false branch
1331 return false;
1332
1333 // If all of the loads and stores that feed the value have the same AA tags,
1334 // then we can propagate them onto any newly inserted loads.
1335 AAMDNodes AATags;
1336 LoadI->getAAMetadata(AATags);
1337
1338 SmallPtrSet<BasicBlock*, 8> PredsScanned;
1339
1340 using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>;
1341
1342 AvailablePredsTy AvailablePreds;
1343 BasicBlock *OneUnavailablePred = nullptr;
23
'OneUnavailablePred' initialized to a null pointer value
1344 SmallVector<LoadInst*, 8> CSELoads;
1345
1346 // If we got here, the loaded value is transparent through to the start of the
1347 // block. Check to see if it is available in any of the predecessor blocks.
1348 for (BasicBlock *PredBB : predecessors(LoadBB)) {
1349 // If we already scanned this predecessor, skip it.
1350 if (!PredsScanned.insert(PredBB).second)
1351 continue;
1352
1353 BBIt = PredBB->end();
1354 unsigned NumScanedInst = 0;
1355 Value *PredAvailable = nullptr;
1356 // NOTE: We don't CSE load that is volatile or anything stronger than
1357 // unordered, that should have been checked when we entered the function.
1358 assert(LoadI->isUnordered() &&((LoadI->isUnordered() && "Attempting to CSE volatile or atomic loads"
) ? static_cast<void> (0) : __assert_fail ("LoadI->isUnordered() && \"Attempting to CSE volatile or atomic loads\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1359, __PRETTY_FUNCTION__))
1359 "Attempting to CSE volatile or atomic loads")((LoadI->isUnordered() && "Attempting to CSE volatile or atomic loads"
) ? static_cast<void> (0) : __assert_fail ("LoadI->isUnordered() && \"Attempting to CSE volatile or atomic loads\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1359, __PRETTY_FUNCTION__))
;
1360 // If this is a load on a phi pointer, phi-translate it and search
1361 // for available load/store to the pointer in predecessors.
1362 Value *Ptr = LoadedPtr->DoPHITranslation(LoadBB, PredBB);
1363 PredAvailable = FindAvailablePtrLoadStore(
1364 Ptr, LoadI->getType(), LoadI->isAtomic(), PredBB, BBIt,
1365 DefMaxInstsToScan, AA, &IsLoadCSE, &NumScanedInst);
1366
1367 // If PredBB has a single predecessor, continue scanning through the
1368 // single predecessor.
1369 BasicBlock *SinglePredBB = PredBB;
1370 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1371 NumScanedInst < DefMaxInstsToScan) {
1372 SinglePredBB = SinglePredBB->getSinglePredecessor();
1373 if (SinglePredBB) {
1374 BBIt = SinglePredBB->end();
1375 PredAvailable = FindAvailablePtrLoadStore(
1376 Ptr, LoadI->getType(), LoadI->isAtomic(), SinglePredBB, BBIt,
1377 (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
1378 &NumScanedInst);
1379 }
1380 }
1381
1382 if (!PredAvailable) {
1383 OneUnavailablePred = PredBB;
1384 continue;
1385 }
1386
1387 if (IsLoadCSE)
1388 CSELoads.push_back(cast<LoadInst>(PredAvailable));
1389
1390 // If so, this load is partially redundant. Remember this info so that we
1391 // can create a PHI node.
1392 AvailablePreds.emplace_back(PredBB, PredAvailable);
1393 }
1394
1395 // If the loaded value isn't available in any predecessor, it isn't partially
1396 // redundant.
1397 if (AvailablePreds.empty()) return false;
24
Calling 'SmallVectorBase::empty'
27
Returning from 'SmallVectorBase::empty'
28
Taking false branch
1398
1399 // Okay, the loaded value is available in at least one (and maybe all!)
1400 // predecessors. If the value is unavailable in more than one unique
1401 // predecessor, we want to insert a merge block for those common predecessors.
1402 // This ensures that we only have to insert one reload, thus not increasing
1403 // code size.
1404 BasicBlock *UnavailablePred = nullptr;
1405
1406 // If the value is unavailable in one of predecessors, we will end up
1407 // inserting a new instruction into them. It is only valid if all the
1408 // instructions before LoadI are guaranteed to pass execution to its
1409 // successor, or if LoadI is safe to speculate.
1410 // TODO: If this logic becomes more complex, and we will perform PRE insertion
1411 // farther than to a predecessor, we need to reuse the code from GVN's PRE.
1412 // It requires domination tree analysis, so for this simple case it is an
1413 // overkill.
1414 if (PredsScanned.size() != AvailablePreds.size() &&
29
Assuming the condition is false
1415 !isSafeToSpeculativelyExecute(LoadI))
1416 for (auto I = LoadBB->begin(); &*I != LoadI; ++I)
1417 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
1418 return false;
1419
1420 // If there is exactly one predecessor where the value is unavailable, the
1421 // already computed 'OneUnavailablePred' block is it. If it ends in an
1422 // unconditional branch, we know that it isn't a critical edge.
1423 if (PredsScanned.size() == AvailablePreds.size()+1 &&
30
Assuming the condition is true
1424 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
31
Called C++ object pointer is null
1425 UnavailablePred = OneUnavailablePred;
1426 } else if (PredsScanned.size() != AvailablePreds.size()) {
1427 // Otherwise, we had multiple unavailable predecessors or we had a critical
1428 // edge from the one.
1429 SmallVector<BasicBlock*, 8> PredsToSplit;
1430 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
1431
1432 for (const auto &AvailablePred : AvailablePreds)
1433 AvailablePredSet.insert(AvailablePred.first);
1434
1435 // Add all the unavailable predecessors to the PredsToSplit list.
1436 for (BasicBlock *P : predecessors(LoadBB)) {
1437 // If the predecessor is an indirect goto, we can't split the edge.
1438 // Same for CallBr.
1439 if (isa<IndirectBrInst>(P->getTerminator()) ||
1440 isa<CallBrInst>(P->getTerminator()))
1441 return false;
1442
1443 if (!AvailablePredSet.count(P))
1444 PredsToSplit.push_back(P);
1445 }
1446
1447 // Split them out to their own block.
1448 UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
1449 }
1450
1451 // If the value isn't available in all predecessors, then there will be
1452 // exactly one where it isn't available. Insert a load on that edge and add
1453 // it to the AvailablePreds list.
1454 if (UnavailablePred) {
1455 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&((UnavailablePred->getTerminator()->getNumSuccessors() ==
1 && "Can't handle critical edge here!") ? static_cast
<void> (0) : __assert_fail ("UnavailablePred->getTerminator()->getNumSuccessors() == 1 && \"Can't handle critical edge here!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1456, __PRETTY_FUNCTION__))
1456 "Can't handle critical edge here!")((UnavailablePred->getTerminator()->getNumSuccessors() ==
1 && "Can't handle critical edge here!") ? static_cast
<void> (0) : __assert_fail ("UnavailablePred->getTerminator()->getNumSuccessors() == 1 && \"Can't handle critical edge here!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1456, __PRETTY_FUNCTION__))
;
1457 LoadInst *NewVal = new LoadInst(
1458 LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
1459 LoadI->getName() + ".pr", false, LoadI->getAlign(),
1460 LoadI->getOrdering(), LoadI->getSyncScopeID(),
1461 UnavailablePred->getTerminator());
1462 NewVal->setDebugLoc(LoadI->getDebugLoc());
1463 if (AATags)
1464 NewVal->setAAMetadata(AATags);
1465
1466 AvailablePreds.emplace_back(UnavailablePred, NewVal);
1467 }
1468
1469 // Now we know that each predecessor of this block has a value in
1470 // AvailablePreds, sort them for efficient access as we're walking the preds.
1471 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
1472
1473 // Create a PHI node at the start of the block for the PRE'd load value.
1474 pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
1475 PHINode *PN = PHINode::Create(LoadI->getType(), std::distance(PB, PE), "",
1476 &LoadBB->front());
1477 PN->takeName(LoadI);
1478 PN->setDebugLoc(LoadI->getDebugLoc());
1479
1480 // Insert new entries into the PHI for each predecessor. A single block may
1481 // have multiple entries here.
1482 for (pred_iterator PI = PB; PI != PE; ++PI) {
1483 BasicBlock *P = *PI;
1484 AvailablePredsTy::iterator I =
1485 llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr));
1486
1487 assert(I != AvailablePreds.end() && I->first == P &&((I != AvailablePreds.end() && I->first == P &&
"Didn't find entry for predecessor!") ? static_cast<void>
(0) : __assert_fail ("I != AvailablePreds.end() && I->first == P && \"Didn't find entry for predecessor!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1488, __PRETTY_FUNCTION__))
1488 "Didn't find entry for predecessor!")((I != AvailablePreds.end() && I->first == P &&
"Didn't find entry for predecessor!") ? static_cast<void>
(0) : __assert_fail ("I != AvailablePreds.end() && I->first == P && \"Didn't find entry for predecessor!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1488, __PRETTY_FUNCTION__))
;
1489
1490 // If we have an available predecessor but it requires casting, insert the
1491 // cast in the predecessor and use the cast. Note that we have to update the
1492 // AvailablePreds vector as we go so that all of the PHI entries for this
1493 // predecessor use the same bitcast.
1494 Value *&PredV = I->second;
1495 if (PredV->getType() != LoadI->getType())
1496 PredV = CastInst::CreateBitOrPointerCast(PredV, LoadI->getType(), "",
1497 P->getTerminator());
1498
1499 PN->addIncoming(PredV, I->first);
1500 }
1501
1502 for (LoadInst *PredLoadI : CSELoads) {
1503 combineMetadataForCSE(PredLoadI, LoadI, true);
1504 }
1505
1506 LoadI->replaceAllUsesWith(PN);
1507 LoadI->eraseFromParent();
1508
1509 return true;
1510}
1511
1512/// FindMostPopularDest - The specified list contains multiple possible
1513/// threadable destinations. Pick the one that occurs the most frequently in
1514/// the list.
1515static BasicBlock *
1516FindMostPopularDest(BasicBlock *BB,
1517 const SmallVectorImpl<std::pair<BasicBlock *,
1518 BasicBlock *>> &PredToDestList) {
1519 assert(!PredToDestList.empty())((!PredToDestList.empty()) ? static_cast<void> (0) : __assert_fail
("!PredToDestList.empty()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1519, __PRETTY_FUNCTION__))
;
1520
1521 // Determine popularity. If there are multiple possible destinations, we
1522 // explicitly choose to ignore 'undef' destinations. We prefer to thread
1523 // blocks with known and real destinations to threading undef. We'll handle
1524 // them later if interesting.
1525 MapVector<BasicBlock *, unsigned> DestPopularity;
1526
1527 // Populate DestPopularity with the successors in the order they appear in the
1528 // successor list. This way, we ensure determinism by iterating it in the
1529 // same order in std::max_element below. We map nullptr to 0 so that we can
1530 // return nullptr when PredToDestList contains nullptr only.
1531 DestPopularity[nullptr] = 0;
1532 for (auto *SuccBB : successors(BB))
1533 DestPopularity[SuccBB] = 0;
1534
1535 for (const auto &PredToDest : PredToDestList)
1536 if (PredToDest.second)
1537 DestPopularity[PredToDest.second]++;
1538
1539 // Find the most popular dest.
1540 using VT = decltype(DestPopularity)::value_type;
1541 auto MostPopular = std::max_element(
1542 DestPopularity.begin(), DestPopularity.end(),
1543 [](const VT &L, const VT &R) { return L.second < R.second; });
1544
1545 // Okay, we have finally picked the most popular destination.
1546 return MostPopular->first;
1547}
1548
1549// Try to evaluate the value of V when the control flows from PredPredBB to
1550// BB->getSinglePredecessor() and then on to BB.
1551Constant *JumpThreadingPass::EvaluateOnPredecessorEdge(BasicBlock *BB,
1552 BasicBlock *PredPredBB,
1553 Value *V) {
1554 BasicBlock *PredBB = BB->getSinglePredecessor();
1555 assert(PredBB && "Expected a single predecessor")((PredBB && "Expected a single predecessor") ? static_cast
<void> (0) : __assert_fail ("PredBB && \"Expected a single predecessor\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1555, __PRETTY_FUNCTION__))
;
1556
1557 if (Constant *Cst = dyn_cast<Constant>(V)) {
1558 return Cst;
1559 }
1560
1561 // Consult LVI if V is not an instruction in BB or PredBB.
1562 Instruction *I = dyn_cast<Instruction>(V);
1563 if (!I || (I->getParent() != BB && I->getParent() != PredBB)) {
1564 return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr);
1565 }
1566
1567 // Look into a PHI argument.
1568 if (PHINode *PHI = dyn_cast<PHINode>(V)) {
1569 if (PHI->getParent() == PredBB)
1570 return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB));
1571 return nullptr;
1572 }
1573
1574 // If we have a CmpInst, try to fold it for each incoming edge into PredBB.
1575 if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) {
1576 if (CondCmp->getParent() == BB) {
1577 Constant *Op0 =
1578 EvaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0));
1579 Constant *Op1 =
1580 EvaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1));
1581 if (Op0 && Op1) {
1582 return ConstantExpr::getCompare(CondCmp->getPredicate(), Op0, Op1);
1583 }
1584 }
1585 return nullptr;
1586 }
1587
1588 return nullptr;
1589}
1590
1591bool JumpThreadingPass::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
1592 ConstantPreference Preference,
1593 Instruction *CxtI) {
1594 // If threading this would thread across a loop header, don't even try to
1595 // thread the edge.
1596 if (LoopHeaders.count(BB))
1597 return false;
1598
1599 PredValueInfoTy PredValues;
1600 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference,
1601 CxtI)) {
1602 // We don't have known values in predecessors. See if we can thread through
1603 // BB and its sole predecessor.
1604 return MaybeThreadThroughTwoBasicBlocks(BB, Cond);
1605 }
1606
1607 assert(!PredValues.empty() &&((!PredValues.empty() && "ComputeValueKnownInPredecessors returned true with no values"
) ? static_cast<void> (0) : __assert_fail ("!PredValues.empty() && \"ComputeValueKnownInPredecessors returned true with no values\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1608, __PRETTY_FUNCTION__))
1608 "ComputeValueKnownInPredecessors returned true with no values")((!PredValues.empty() && "ComputeValueKnownInPredecessors returned true with no values"
) ? static_cast<void> (0) : __assert_fail ("!PredValues.empty() && \"ComputeValueKnownInPredecessors returned true with no values\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1608, __PRETTY_FUNCTION__))
;
1609
1610 LLVM_DEBUG(dbgs() << "IN BB: " << *BB;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1611 for (const auto &PredValue : PredValues) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1612 dbgs() << " BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1613 << "': FOUND condition = " << *PredValue.firstdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1614 << " for pred '" << PredValue.second->getName() << "'.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
1615 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "IN BB: " << *BB;
for (const auto &PredValue : PredValues) { dbgs() <<
" BB '" << BB->getName() << "': FOUND condition = "
<< *PredValue.first << " for pred '" << PredValue
.second->getName() << "'.\n"; }; } } while (false)
;
1616
1617 // Decide what we want to thread through. Convert our list of known values to
1618 // a list of known destinations for each pred. This also discards duplicate
1619 // predecessors and keeps track of the undefined inputs (which are represented
1620 // as a null dest in the PredToDestList).
1621 SmallPtrSet<BasicBlock*, 16> SeenPreds;
1622 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1623
1624 BasicBlock *OnlyDest = nullptr;
1625 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1626 Constant *OnlyVal = nullptr;
1627 Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
1628
1629 for (const auto &PredValue : PredValues) {
1630 BasicBlock *Pred = PredValue.second;
1631 if (!SeenPreds.insert(Pred).second)
1632 continue; // Duplicate predecessor entry.
1633
1634 Constant *Val = PredValue.first;
1635
1636 BasicBlock *DestBB;
1637 if (isa<UndefValue>(Val))
1638 DestBB = nullptr;
1639 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1640 assert(isa<ConstantInt>(Val) && "Expecting a constant integer")((isa<ConstantInt>(Val) && "Expecting a constant integer"
) ? static_cast<void> (0) : __assert_fail ("isa<ConstantInt>(Val) && \"Expecting a constant integer\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1640, __PRETTY_FUNCTION__))
;
1641 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1642 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1643 assert(isa<ConstantInt>(Val) && "Expecting a constant integer")((isa<ConstantInt>(Val) && "Expecting a constant integer"
) ? static_cast<void> (0) : __assert_fail ("isa<ConstantInt>(Val) && \"Expecting a constant integer\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1643, __PRETTY_FUNCTION__))
;
1644 DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1645 } else {
1646 assert(isa<IndirectBrInst>(BB->getTerminator())((isa<IndirectBrInst>(BB->getTerminator()) &&
"Unexpected terminator") ? static_cast<void> (0) : __assert_fail
("isa<IndirectBrInst>(BB->getTerminator()) && \"Unexpected terminator\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1647, __PRETTY_FUNCTION__))
1647 && "Unexpected terminator")((isa<IndirectBrInst>(BB->getTerminator()) &&
"Unexpected terminator") ? static_cast<void> (0) : __assert_fail
("isa<IndirectBrInst>(BB->getTerminator()) && \"Unexpected terminator\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1647, __PRETTY_FUNCTION__))
;
1648 assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress")((isa<BlockAddress>(Val) && "Expecting a constant blockaddress"
) ? static_cast<void> (0) : __assert_fail ("isa<BlockAddress>(Val) && \"Expecting a constant blockaddress\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1648, __PRETTY_FUNCTION__))
;
1649 DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1650 }
1651
1652 // If we have exactly one destination, remember it for efficiency below.
1653 if (PredToDestList.empty()) {
1654 OnlyDest = DestBB;
1655 OnlyVal = Val;
1656 } else {
1657 if (OnlyDest != DestBB)
1658 OnlyDest = MultipleDestSentinel;
1659 // It possible we have same destination, but different value, e.g. default
1660 // case in switchinst.
1661 if (Val != OnlyVal)
1662 OnlyVal = MultipleVal;
1663 }
1664
1665 // If the predecessor ends with an indirect goto, we can't change its
1666 // destination. Same for CallBr.
1667 if (isa<IndirectBrInst>(Pred->getTerminator()) ||
1668 isa<CallBrInst>(Pred->getTerminator()))
1669 continue;
1670
1671 PredToDestList.emplace_back(Pred, DestBB);
1672 }
1673
1674 // If all edges were unthreadable, we fail.
1675 if (PredToDestList.empty())
1676 return false;
1677
1678 // If all the predecessors go to a single known successor, we want to fold,
1679 // not thread. By doing so, we do not need to duplicate the current block and
1680 // also miss potential opportunities in case we dont/cant duplicate.
1681 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1682 if (BB->hasNPredecessors(PredToDestList.size())) {
1683 bool SeenFirstBranchToOnlyDest = false;
1684 std::vector <DominatorTree::UpdateType> Updates;
1685 Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1);
1686 for (BasicBlock *SuccBB : successors(BB)) {
1687 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
1688 SeenFirstBranchToOnlyDest = true; // Don't modify the first branch.
1689 } else {
1690 SuccBB->removePredecessor(BB, true); // This is unreachable successor.
1691 Updates.push_back({DominatorTree::Delete, BB, SuccBB});
1692 }
1693 }
1694
1695 // Finally update the terminator.
1696 Instruction *Term = BB->getTerminator();
1697 BranchInst::Create(OnlyDest, Term);
1698 Term->eraseFromParent();
1699 DTU->applyUpdatesPermissive(Updates);
1700
1701 // If the condition is now dead due to the removal of the old terminator,
1702 // erase it.
1703 if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
1704 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1705 CondInst->eraseFromParent();
1706 // We can safely replace *some* uses of the CondInst if it has
1707 // exactly one value as returned by LVI. RAUW is incorrect in the
1708 // presence of guards and assumes, that have the `Cond` as the use. This
1709 // is because we use the guards/assume to reason about the `Cond` value
1710 // at the end of block, but RAUW unconditionally replaces all uses
1711 // including the guards/assumes themselves and the uses before the
1712 // guard/assume.
1713 else if (OnlyVal && OnlyVal != MultipleVal &&
1714 CondInst->getParent() == BB)
1715 ReplaceFoldableUses(CondInst, OnlyVal);
1716 }
1717 return true;
1718 }
1719 }
1720
1721 // Determine which is the most common successor. If we have many inputs and
1722 // this block is a switch, we want to start by threading the batch that goes
1723 // to the most popular destination first. If we only know about one
1724 // threadable destination (the common case) we can avoid this.
1725 BasicBlock *MostPopularDest = OnlyDest;
1726
1727 if (MostPopularDest == MultipleDestSentinel) {
1728 // Remove any loop headers from the Dest list, ThreadEdge conservatively
1729 // won't process them, but we might have other destination that are eligible
1730 // and we still want to process.
1731 erase_if(PredToDestList,
1732 [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1733 return LoopHeaders.count(PredToDest.second) != 0;
1734 });
1735
1736 if (PredToDestList.empty())
1737 return false;
1738
1739 MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1740 }
1741
1742 // Now that we know what the most popular destination is, factor all
1743 // predecessors that will jump to it into a single predecessor.
1744 SmallVector<BasicBlock*, 16> PredsToFactor;
1745 for (const auto &PredToDest : PredToDestList)
1746 if (PredToDest.second == MostPopularDest) {
1747 BasicBlock *Pred = PredToDest.first;
1748
1749 // This predecessor may be a switch or something else that has multiple
1750 // edges to the block. Factor each of these edges by listing them
1751 // according to # occurrences in PredsToFactor.
1752 for (BasicBlock *Succ : successors(Pred))
1753 if (Succ == BB)
1754 PredsToFactor.push_back(Pred);
1755 }
1756
1757 // If the threadable edges are branching on an undefined value, we get to pick
1758 // the destination that these predecessors should get to.
1759 if (!MostPopularDest)
1760 MostPopularDest = BB->getTerminator()->
1761 getSuccessor(GetBestDestForJumpOnUndef(BB));
1762
1763 // Ok, try to thread it!
1764 return TryThreadEdge(BB, PredsToFactor, MostPopularDest);
1765}
1766
1767/// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
1768/// a PHI node (or freeze PHI) in the current block. See if there are any
1769/// simplifications we can do based on inputs to the phi node.
1770bool JumpThreadingPass::ProcessBranchOnPHI(PHINode *PN) {
1771 BasicBlock *BB = PN->getParent();
1772
1773 // TODO: We could make use of this to do it once for blocks with common PHI
1774 // values.
1775 SmallVector<BasicBlock*, 1> PredBBs;
1776 PredBBs.resize(1);
1777
1778 // If any of the predecessor blocks end in an unconditional branch, we can
1779 // *duplicate* the conditional branch into that block in order to further
1780 // encourage jump threading and to eliminate cases where we have branch on a
1781 // phi of an icmp (branch on icmp is much better).
1782 // This is still beneficial when a frozen phi is used as the branch condition
1783 // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp))
1784 // to br(icmp(freeze ...)).
1785 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1786 BasicBlock *PredBB = PN->getIncomingBlock(i);
1787 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1788 if (PredBr->isUnconditional()) {
1789 PredBBs[0] = PredBB;
1790 // Try to duplicate BB into PredBB.
1791 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1792 return true;
1793 }
1794 }
1795
1796 return false;
1797}
1798
1799/// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
1800/// a xor instruction in the current block. See if there are any
1801/// simplifications we can do based on inputs to the xor.
1802bool JumpThreadingPass::ProcessBranchOnXOR(BinaryOperator *BO) {
1803 BasicBlock *BB = BO->getParent();
1804
1805 // If either the LHS or RHS of the xor is a constant, don't do this
1806 // optimization.
1807 if (isa<ConstantInt>(BO->getOperand(0)) ||
1808 isa<ConstantInt>(BO->getOperand(1)))
1809 return false;
1810
1811 // If the first instruction in BB isn't a phi, we won't be able to infer
1812 // anything special about any particular predecessor.
1813 if (!isa<PHINode>(BB->front()))
1814 return false;
1815
1816 // If this BB is a landing pad, we won't be able to split the edge into it.
1817 if (BB->isEHPad())
1818 return false;
1819
1820 // If we have a xor as the branch input to this block, and we know that the
1821 // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1822 // the condition into the predecessor and fix that value to true, saving some
1823 // logical ops on that path and encouraging other paths to simplify.
1824 //
1825 // This copies something like this:
1826 //
1827 // BB:
1828 // %X = phi i1 [1], [%X']
1829 // %Y = icmp eq i32 %A, %B
1830 // %Z = xor i1 %X, %Y
1831 // br i1 %Z, ...
1832 //
1833 // Into:
1834 // BB':
1835 // %Y = icmp ne i32 %A, %B
1836 // br i1 %Y, ...
1837
1838 PredValueInfoTy XorOpValues;
1839 bool isLHS = true;
1840 if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
1841 WantInteger, BO)) {
1842 assert(XorOpValues.empty())((XorOpValues.empty()) ? static_cast<void> (0) : __assert_fail
("XorOpValues.empty()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1842, __PRETTY_FUNCTION__))
;
1843 if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
1844 WantInteger, BO))
1845 return false;
1846 isLHS = false;
1847 }
1848
1849 assert(!XorOpValues.empty() &&((!XorOpValues.empty() && "ComputeValueKnownInPredecessors returned true with no values"
) ? static_cast<void> (0) : __assert_fail ("!XorOpValues.empty() && \"ComputeValueKnownInPredecessors returned true with no values\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1850, __PRETTY_FUNCTION__))
1850 "ComputeValueKnownInPredecessors returned true with no values")((!XorOpValues.empty() && "ComputeValueKnownInPredecessors returned true with no values"
) ? static_cast<void> (0) : __assert_fail ("!XorOpValues.empty() && \"ComputeValueKnownInPredecessors returned true with no values\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 1850, __PRETTY_FUNCTION__))
;
1851
1852 // Scan the information to see which is most popular: true or false. The
1853 // predecessors can be of the set true, false, or undef.
1854 unsigned NumTrue = 0, NumFalse = 0;
1855 for (const auto &XorOpValue : XorOpValues) {
1856 if (isa<UndefValue>(XorOpValue.first))
1857 // Ignore undefs for the count.
1858 continue;
1859 if (cast<ConstantInt>(XorOpValue.first)->isZero())
1860 ++NumFalse;
1861 else
1862 ++NumTrue;
1863 }
1864
1865 // Determine which value to split on, true, false, or undef if neither.
1866 ConstantInt *SplitVal = nullptr;
1867 if (NumTrue > NumFalse)
1868 SplitVal = ConstantInt::getTrue(BB->getContext());
1869 else if (NumTrue != 0 || NumFalse != 0)
1870 SplitVal = ConstantInt::getFalse(BB->getContext());
1871
1872 // Collect all of the blocks that this can be folded into so that we can
1873 // factor this once and clone it once.
1874 SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1875 for (const auto &XorOpValue : XorOpValues) {
1876 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1877 continue;
1878
1879 BlocksToFoldInto.push_back(XorOpValue.second);
1880 }
1881
1882 // If we inferred a value for all of the predecessors, then duplication won't
1883 // help us. However, we can just replace the LHS or RHS with the constant.
1884 if (BlocksToFoldInto.size() ==
1885 cast<PHINode>(BB->front()).getNumIncomingValues()) {
1886 if (!SplitVal) {
1887 // If all preds provide undef, just nuke the xor, because it is undef too.
1888 BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1889 BO->eraseFromParent();
1890 } else if (SplitVal->isZero()) {
1891 // If all preds provide 0, replace the xor with the other input.
1892 BO->replaceAllUsesWith(BO->getOperand(isLHS));
1893 BO->eraseFromParent();
1894 } else {
1895 // If all preds provide 1, set the computed value to 1.
1896 BO->setOperand(!isLHS, SplitVal);
1897 }
1898
1899 return true;
1900 }
1901
1902 // If any of predecessors end with an indirect goto, we can't change its
1903 // destination. Same for CallBr.
1904 if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) {
1905 return isa<IndirectBrInst>(Pred->getTerminator()) ||
1906 isa<CallBrInst>(Pred->getTerminator());
1907 }))
1908 return false;
1909
1910 // Try to duplicate BB into PredBB.
1911 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1912}
1913
1914/// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1915/// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1916/// NewPred using the entries from OldPred (suitably mapped).
1917static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1918 BasicBlock *OldPred,
1919 BasicBlock *NewPred,
1920 DenseMap<Instruction*, Value*> &ValueMap) {
1921 for (PHINode &PN : PHIBB->phis()) {
1922 // Ok, we have a PHI node. Figure out what the incoming value was for the
1923 // DestBlock.
1924 Value *IV = PN.getIncomingValueForBlock(OldPred);
1925
1926 // Remap the value if necessary.
1927 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1928 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1929 if (I != ValueMap.end())
1930 IV = I->second;
1931 }
1932
1933 PN.addIncoming(IV, NewPred);
1934 }
1935}
1936
1937/// Merge basic block BB into its sole predecessor if possible.
1938bool JumpThreadingPass::MaybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) {
1939 BasicBlock *SinglePred = BB->getSinglePredecessor();
1940 if (!SinglePred)
1941 return false;
1942
1943 const Instruction *TI = SinglePred->getTerminator();
1944 if (TI->isExceptionalTerminator() || TI->getNumSuccessors() != 1 ||
1945 SinglePred == BB || hasAddressTakenAndUsed(BB))
1946 return false;
1947
1948 // If SinglePred was a loop header, BB becomes one.
1949 if (LoopHeaders.erase(SinglePred))
1950 LoopHeaders.insert(BB);
1951
1952 LVI->eraseBlock(SinglePred);
1953 MergeBasicBlockIntoOnlyPred(BB, DTU);
1954
1955 // Now that BB is merged into SinglePred (i.e. SinglePred code followed by
1956 // BB code within one basic block `BB`), we need to invalidate the LVI
1957 // information associated with BB, because the LVI information need not be
1958 // true for all of BB after the merge. For example,
1959 // Before the merge, LVI info and code is as follows:
1960 // SinglePred: <LVI info1 for %p val>
1961 // %y = use of %p
1962 // call @exit() // need not transfer execution to successor.
1963 // assume(%p) // from this point on %p is true
1964 // br label %BB
1965 // BB: <LVI info2 for %p val, i.e. %p is true>
1966 // %x = use of %p
1967 // br label exit
1968 //
1969 // Note that this LVI info for blocks BB and SinglPred is correct for %p
1970 // (info2 and info1 respectively). After the merge and the deletion of the
1971 // LVI info1 for SinglePred. We have the following code:
1972 // BB: <LVI info2 for %p val>
1973 // %y = use of %p
1974 // call @exit()
1975 // assume(%p)
1976 // %x = use of %p <-- LVI info2 is correct from here onwards.
1977 // br label exit
1978 // LVI info2 for BB is incorrect at the beginning of BB.
1979
1980 // Invalidate LVI information for BB if the LVI is not provably true for
1981 // all of BB.
1982 if (!isGuaranteedToTransferExecutionToSuccessor(BB))
1983 LVI->eraseBlock(BB);
1984 return true;
1985}
1986
1987/// Update the SSA form. NewBB contains instructions that are copied from BB.
1988/// ValueMapping maps old values in BB to new ones in NewBB.
1989void JumpThreadingPass::UpdateSSA(
1990 BasicBlock *BB, BasicBlock *NewBB,
1991 DenseMap<Instruction *, Value *> &ValueMapping) {
1992 // If there were values defined in BB that are used outside the block, then we
1993 // now have to update all uses of the value to use either the original value,
1994 // the cloned value, or some PHI derived value. This can require arbitrary
1995 // PHI insertion, of which we are prepared to do, clean these up now.
1996 SSAUpdater SSAUpdate;
1997 SmallVector<Use *, 16> UsesToRename;
1998
1999 for (Instruction &I : *BB) {
2000 // Scan all uses of this instruction to see if it is used outside of its
2001 // block, and if so, record them in UsesToRename.
2002 for (Use &U : I.uses()) {
2003 Instruction *User = cast<Instruction>(U.getUser());
2004 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
2005 if (UserPN->getIncomingBlock(U) == BB)
2006 continue;
2007 } else if (User->getParent() == BB)
2008 continue;
2009
2010 UsesToRename.push_back(&U);
2011 }
2012
2013 // If there are no uses outside the block, we're done with this instruction.
2014 if (UsesToRename.empty())
2015 continue;
2016 LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "JT: Renaming non-local uses of: "
<< I << "\n"; } } while (false)
;
2017
2018 // We found a use of I outside of BB. Rename all uses of I that are outside
2019 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
2020 // with the two values we know.
2021 SSAUpdate.Initialize(I.getType(), I.getName());
2022 SSAUpdate.AddAvailableValue(BB, &I);
2023 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
2024
2025 while (!UsesToRename.empty())
2026 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
2027 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "\n"; } } while (false)
;
2028 }
2029}
2030
2031/// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone
2032/// arguments that come from PredBB. Return the map from the variables in the
2033/// source basic block to the variables in the newly created basic block.
2034DenseMap<Instruction *, Value *>
2035JumpThreadingPass::CloneInstructions(BasicBlock::iterator BI,
2036 BasicBlock::iterator BE, BasicBlock *NewBB,
2037 BasicBlock *PredBB) {
2038 // We are going to have to map operands from the source basic block to the new
2039 // copy of the block 'NewBB'. If there are PHI nodes in the source basic
2040 // block, evaluate them to account for entry from PredBB.
2041 DenseMap<Instruction *, Value *> ValueMapping;
2042
2043 // Clone the phi nodes of the source basic block into NewBB. The resulting
2044 // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater
2045 // might need to rewrite the operand of the cloned phi.
2046 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2047 PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB);
2048 NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB);
2049 ValueMapping[PN] = NewPN;
2050 }
2051
2052 // Clone the non-phi instructions of the source basic block into NewBB,
2053 // keeping track of the mapping and using it to remap operands in the cloned
2054 // instructions.
2055 for (; BI != BE; ++BI) {
2056 Instruction *New = BI->clone();
2057 New->setName(BI->getName());
2058 NewBB->getInstList().push_back(New);
2059 ValueMapping[&*BI] = New;
2060
2061 // Remap operands to patch up intra-block references.
2062 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2063 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2064 DenseMap<Instruction *, Value *>::iterator I = ValueMapping.find(Inst);
2065 if (I != ValueMapping.end())
2066 New->setOperand(i, I->second);
2067 }
2068 }
2069
2070 return ValueMapping;
2071}
2072
2073/// Attempt to thread through two successive basic blocks.
2074bool JumpThreadingPass::MaybeThreadThroughTwoBasicBlocks(BasicBlock *BB,
2075 Value *Cond) {
2076 // Consider:
2077 //
2078 // PredBB:
2079 // %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ]
2080 // %tobool = icmp eq i32 %cond, 0
2081 // br i1 %tobool, label %BB, label ...
2082 //
2083 // BB:
2084 // %cmp = icmp eq i32* %var, null
2085 // br i1 %cmp, label ..., label ...
2086 //
2087 // We don't know the value of %var at BB even if we know which incoming edge
2088 // we take to BB. However, once we duplicate PredBB for each of its incoming
2089 // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of
2090 // PredBB. Then we can thread edges PredBB1->BB and PredBB2->BB through BB.
2091
2092 // Require that BB end with a Branch for simplicity.
2093 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2094 if (!CondBr)
2095 return false;
2096
2097 // BB must have exactly one predecessor.
2098 BasicBlock *PredBB = BB->getSinglePredecessor();
2099 if (!PredBB)
2100 return false;
2101
2102 // Require that PredBB end with a conditional Branch. If PredBB ends with an
2103 // unconditional branch, we should be merging PredBB and BB instead. For
2104 // simplicity, we don't deal with a switch.
2105 BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2106 if (!PredBBBranch || PredBBBranch->isUnconditional())
2107 return false;
2108
2109 // If PredBB has exactly one incoming edge, we don't gain anything by copying
2110 // PredBB.
2111 if (PredBB->getSinglePredecessor())
2112 return false;
2113
2114 // Don't thread through PredBB if it contains a successor edge to itself, in
2115 // which case we would infinite loop. Suppose we are threading an edge from
2116 // PredPredBB through PredBB and BB to SuccBB with PredBB containing a
2117 // successor edge to itself. If we allowed jump threading in this case, we
2118 // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread. Since
2119 // PredBB.thread has a successor edge to PredBB, we would immediately come up
2120 // with another jump threading opportunity from PredBB.thread through PredBB
2121 // and BB to SuccBB. This jump threading would repeatedly occur. That is, we
2122 // would keep peeling one iteration from PredBB.
2123 if (llvm::is_contained(successors(PredBB), PredBB))
2124 return false;
2125
2126 // Don't thread across a loop header.
2127 if (LoopHeaders.count(PredBB))
2128 return false;
2129
2130 // Avoid complication with duplicating EH pads.
2131 if (PredBB->isEHPad())
2132 return false;
2133
2134 // Find a predecessor that we can thread. For simplicity, we only consider a
2135 // successor edge out of BB to which we thread exactly one incoming edge into
2136 // PredBB.
2137 unsigned ZeroCount = 0;
2138 unsigned OneCount = 0;
2139 BasicBlock *ZeroPred = nullptr;
2140 BasicBlock *OnePred = nullptr;
2141 for (BasicBlock *P : predecessors(PredBB)) {
2142 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(
2143 EvaluateOnPredecessorEdge(BB, P, Cond))) {
2144 if (CI->isZero()) {
2145 ZeroCount++;
2146 ZeroPred = P;
2147 } else if (CI->isOne()) {
2148 OneCount++;
2149 OnePred = P;
2150 }
2151 }
2152 }
2153
2154 // Disregard complicated cases where we have to thread multiple edges.
2155 BasicBlock *PredPredBB;
2156 if (ZeroCount == 1) {
2157 PredPredBB = ZeroPred;
2158 } else if (OneCount == 1) {
2159 PredPredBB = OnePred;
2160 } else {
2161 return false;
2162 }
2163
2164 BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred);
2165
2166 // If threading to the same block as we come from, we would infinite loop.
2167 if (SuccBB == BB) {
2168 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
2169 << "' - would thread to self!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
;
2170 return false;
2171 }
2172
2173 // If threading this would thread across a loop header, don't thread the edge.
2174 // See the comments above FindLoopHeaders for justifications and caveats.
2175 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2176 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2177 bool BBIsHeader = LoopHeaders.count(BB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2178 bool SuccIsHeader = LoopHeaders.count(SuccBB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2179 dbgs() << " Not threading across "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2180 << (BBIsHeader ? "loop header BB '" : "block BB '")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2181 << BB->getName() << "' to dest "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2182 << (SuccIsHeader ? "loop header BB '" : "block BB '")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2183 << SuccBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2184 << "' - it might create an irreducible loop!\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2185 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
;
2186 return false;
2187 }
2188
2189 // Compute the cost of duplicating BB and PredBB.
2190 unsigned BBCost =
2191 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold);
2192 unsigned PredBBCost = getJumpThreadDuplicationCost(
2193 PredBB, PredBB->getTerminator(), BBDupThreshold);
2194
2195 // Give up if costs are too high. We need to check BBCost and PredBBCost
2196 // individually before checking their sum because getJumpThreadDuplicationCost
2197 // return (unsigned)~0 for those basic blocks that cannot be duplicated.
2198 if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold ||
2199 BBCost + PredBBCost > BBDupThreshold) {
2200 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << PredBBCost
<< " for PredBB, " << BBCost << "for BB\n"
; } } while (false)
2201 << "' - Cost is too high: " << PredBBCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << PredBBCost
<< " for PredBB, " << BBCost << "for BB\n"
; } } while (false)
2202 << " for PredBB, " << BBCost << "for BB\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << PredBBCost
<< " for PredBB, " << BBCost << "for BB\n"
; } } while (false)
;
2203 return false;
2204 }
2205
2206 // Now we are ready to duplicate PredBB.
2207 ThreadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB);
2208 return true;
2209}
2210
2211void JumpThreadingPass::ThreadThroughTwoBasicBlocks(BasicBlock *PredPredBB,
2212 BasicBlock *PredBB,
2213 BasicBlock *BB,
2214 BasicBlock *SuccBB) {
2215 LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading through '"
<< PredBB->getName() << "' and '" << BB
->getName() << "'\n"; } } while (false)
2216 << BB->getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading through '"
<< PredBB->getName() << "' and '" << BB
->getName() << "'\n"; } } while (false)
;
2217
2218 BranchInst *CondBr = cast<BranchInst>(BB->getTerminator());
2219 BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator());
2220
2221 BasicBlock *NewBB =
2222 BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread",
2223 PredBB->getParent(), PredBB);
2224 NewBB->moveAfter(PredBB);
2225
2226 // Set the block frequency of NewBB.
2227 if (HasProfileData) {
2228 auto NewBBFreq = BFI->getBlockFreq(PredPredBB) *
2229 BPI->getEdgeProbability(PredPredBB, PredBB);
2230 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2231 }
2232
2233 // We are going to have to map operands from the original BB block to the new
2234 // copy of the block 'NewBB'. If there are PHI nodes in PredBB, evaluate them
2235 // to account for entry from PredPredBB.
2236 DenseMap<Instruction *, Value *> ValueMapping =
2237 CloneInstructions(PredBB->begin(), PredBB->end(), NewBB, PredPredBB);
2238
2239 // Copy the edge probabilities from PredBB to NewBB.
2240 if (HasProfileData) {
2241 SmallVector<BranchProbability, 4> Probs;
2242 for (BasicBlock *Succ : successors(PredBB))
2243 Probs.push_back(BPI->getEdgeProbability(PredBB, Succ));
2244 BPI->setEdgeProbability(NewBB, Probs);
2245 }
2246
2247 // Update the terminator of PredPredBB to jump to NewBB instead of PredBB.
2248 // This eliminates predecessors from PredPredBB, which requires us to simplify
2249 // any PHI nodes in PredBB.
2250 Instruction *PredPredTerm = PredPredBB->getTerminator();
2251 for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i)
2252 if (PredPredTerm->getSuccessor(i) == PredBB) {
2253 PredBB->removePredecessor(PredPredBB, true);
2254 PredPredTerm->setSuccessor(i, NewBB);
2255 }
2256
2257 AddPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB,
2258 ValueMapping);
2259 AddPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB,
2260 ValueMapping);
2261
2262 DTU->applyUpdatesPermissive(
2263 {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)},
2264 {DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)},
2265 {DominatorTree::Insert, PredPredBB, NewBB},
2266 {DominatorTree::Delete, PredPredBB, PredBB}});
2267
2268 UpdateSSA(PredBB, NewBB, ValueMapping);
2269
2270 // Clean up things like PHI nodes with single operands, dead instructions,
2271 // etc.
2272 SimplifyInstructionsInBlock(NewBB, TLI);
2273 SimplifyInstructionsInBlock(PredBB, TLI);
2274
2275 SmallVector<BasicBlock *, 1> PredsToFactor;
2276 PredsToFactor.push_back(NewBB);
2277 ThreadEdge(BB, PredsToFactor, SuccBB);
2278}
2279
2280/// TryThreadEdge - Thread an edge if it's safe and profitable to do so.
2281bool JumpThreadingPass::TryThreadEdge(
2282 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs,
2283 BasicBlock *SuccBB) {
2284 // If threading to the same block as we come from, we would infinite loop.
2285 if (SuccBB == BB) {
2286 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
2287 << "' - would thread to self!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading across BB '"
<< BB->getName() << "' - would thread to self!\n"
; } } while (false)
;
2288 return false;
2289 }
2290
2291 // If threading this would thread across a loop header, don't thread the edge.
2292 // See the comments above FindLoopHeaders for justifications and caveats.
2293 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2294 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2295 bool BBIsHeader = LoopHeaders.count(BB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2296 bool SuccIsHeader = LoopHeaders.count(SuccBB);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2297 dbgs() << " Not threading across "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2298 << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2299 << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2300 << SuccBB->getName() << "' - it might create an irreducible loop!\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
2301 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { { bool BBIsHeader = LoopHeaders.count(BB
); bool SuccIsHeader = LoopHeaders.count(SuccBB); dbgs() <<
" Not threading across " << (BBIsHeader ? "loop header BB '"
: "block BB '") << BB->getName() << "' to dest "
<< (SuccIsHeader ? "loop header BB '" : "block BB '") <<
SuccBB->getName() << "' - it might create an irreducible loop!\n"
; }; } } while (false)
;
2302 return false;
2303 }
2304
2305 unsigned JumpThreadCost =
2306 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold);
2307 if (JumpThreadCost > BBDupThreshold) {
2308 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << JumpThreadCost
<< "\n"; } } while (false)
2309 << "' - Cost is too high: " << JumpThreadCost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not threading BB '" <<
BB->getName() << "' - Cost is too high: " << JumpThreadCost
<< "\n"; } } while (false)
;
2310 return false;
2311 }
2312
2313 ThreadEdge(BB, PredBBs, SuccBB);
2314 return true;
2315}
2316
2317/// ThreadEdge - We have decided that it is safe and profitable to factor the
2318/// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
2319/// across BB. Transform the IR to reflect this change.
2320void JumpThreadingPass::ThreadEdge(BasicBlock *BB,
2321 const SmallVectorImpl<BasicBlock *> &PredBBs,
2322 BasicBlock *SuccBB) {
2323 assert(SuccBB != BB && "Don't create an infinite loop")((SuccBB != BB && "Don't create an infinite loop") ? static_cast
<void> (0) : __assert_fail ("SuccBB != BB && \"Don't create an infinite loop\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2323, __PRETTY_FUNCTION__))
;
2324
2325 assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&((!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB
) && "Don't thread across loop headers") ? static_cast
<void> (0) : __assert_fail ("!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) && \"Don't thread across loop headers\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2326, __PRETTY_FUNCTION__))
2326 "Don't thread across loop headers")((!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB
) && "Don't thread across loop headers") ? static_cast
<void> (0) : __assert_fail ("!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) && \"Don't thread across loop headers\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2326, __PRETTY_FUNCTION__))
;
2327
2328 // And finally, do it! Start by factoring the predecessors if needed.
2329 BasicBlock *PredBB;
2330 if (PredBBs.size() == 1)
2331 PredBB = PredBBs[0];
2332 else {
2333 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
2334 << " common predecessors.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
;
2335 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
2336 }
2337
2338 // And finally, do it!
2339 LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading edge from '"
<< PredBB->getName() << "' to '" << SuccBB
->getName() << ", across block:\n " << *BB <<
"\n"; } } while (false)
2340 << "' to '" << SuccBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading edge from '"
<< PredBB->getName() << "' to '" << SuccBB
->getName() << ", across block:\n " << *BB <<
"\n"; } } while (false)
2341 << ", across block:\n " << *BB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Threading edge from '"
<< PredBB->getName() << "' to '" << SuccBB
->getName() << ", across block:\n " << *BB <<
"\n"; } } while (false)
;
2342
2343 LVI->threadEdge(PredBB, BB, SuccBB);
2344
2345 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
2346 BB->getName()+".thread",
2347 BB->getParent(), BB);
2348 NewBB->moveAfter(PredBB);
2349
2350 // Set the block frequency of NewBB.
2351 if (HasProfileData) {
2352 auto NewBBFreq =
2353 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
2354 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2355 }
2356
2357 // Copy all the instructions from BB to NewBB except the terminator.
2358 DenseMap<Instruction *, Value *> ValueMapping =
2359 CloneInstructions(BB->begin(), std::prev(BB->end()), NewBB, PredBB);
2360
2361 // We didn't copy the terminator from BB over to NewBB, because there is now
2362 // an unconditional jump to SuccBB. Insert the unconditional jump.
2363 BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
2364 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
2365
2366 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
2367 // PHI nodes for NewBB now.
2368 AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
2369
2370 // Update the terminator of PredBB to jump to NewBB instead of BB. This
2371 // eliminates predecessors from BB, which requires us to simplify any PHI
2372 // nodes in BB.
2373 Instruction *PredTerm = PredBB->getTerminator();
2374 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
2375 if (PredTerm->getSuccessor(i) == BB) {
2376 BB->removePredecessor(PredBB, true);
2377 PredTerm->setSuccessor(i, NewBB);
2378 }
2379
2380 // Enqueue required DT updates.
2381 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB},
2382 {DominatorTree::Insert, PredBB, NewBB},
2383 {DominatorTree::Delete, PredBB, BB}});
2384
2385 UpdateSSA(BB, NewBB, ValueMapping);
2386
2387 // At this point, the IR is fully up to date and consistent. Do a quick scan
2388 // over the new instructions and zap any that are constants or dead. This
2389 // frequently happens because of phi translation.
2390 SimplifyInstructionsInBlock(NewBB, TLI);
2391
2392 // Update the edge weight from BB to SuccBB, which should be less than before.
2393 UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
2394
2395 // Threaded an edge!
2396 ++NumThreads;
2397}
2398
2399/// Create a new basic block that will be the predecessor of BB and successor of
2400/// all blocks in Preds. When profile data is available, update the frequency of
2401/// this new block.
2402BasicBlock *JumpThreadingPass::SplitBlockPreds(BasicBlock *BB,
2403 ArrayRef<BasicBlock *> Preds,
2404 const char *Suffix) {
2405 SmallVector<BasicBlock *, 2> NewBBs;
2406
2407 // Collect the frequencies of all predecessors of BB, which will be used to
2408 // update the edge weight of the result of splitting predecessors.
2409 DenseMap<BasicBlock *, BlockFrequency> FreqMap;
2410 if (HasProfileData)
2411 for (auto Pred : Preds)
2412 FreqMap.insert(std::make_pair(
2413 Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
2414
2415 // In the case when BB is a LandingPad block we create 2 new predecessors
2416 // instead of just one.
2417 if (BB->isLandingPad()) {
2418 std::string NewName = std::string(Suffix) + ".split-lp";
2419 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs);
2420 } else {
2421 NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix));
2422 }
2423
2424 std::vector<DominatorTree::UpdateType> Updates;
2425 Updates.reserve((2 * Preds.size()) + NewBBs.size());
2426 for (auto NewBB : NewBBs) {
2427 BlockFrequency NewBBFreq(0);
2428 Updates.push_back({DominatorTree::Insert, NewBB, BB});
2429 for (auto Pred : predecessors(NewBB)) {
2430 Updates.push_back({DominatorTree::Delete, Pred, BB});
2431 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
2432 if (HasProfileData) // Update frequencies between Pred -> NewBB.
2433 NewBBFreq += FreqMap.lookup(Pred);
2434 }
2435 if (HasProfileData) // Apply the summed frequency to NewBB.
2436 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2437 }
2438
2439 DTU->applyUpdatesPermissive(Updates);
2440 return NewBBs[0];
2441}
2442
2443bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
2444 const Instruction *TI = BB->getTerminator();
2445 assert(TI->getNumSuccessors() > 1 && "not a split")((TI->getNumSuccessors() > 1 && "not a split") ?
static_cast<void> (0) : __assert_fail ("TI->getNumSuccessors() > 1 && \"not a split\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2445, __PRETTY_FUNCTION__))
;
2446
2447 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
2448 if (!WeightsNode)
2449 return false;
2450
2451 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
2452 if (MDName->getString() != "branch_weights")
2453 return false;
2454
2455 // Ensure there are weights for all of the successors. Note that the first
2456 // operand to the metadata node is a name, not a weight.
2457 return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1;
2458}
2459
2460/// Update the block frequency of BB and branch weight and the metadata on the
2461/// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
2462/// Freq(PredBB->BB) / Freq(BB->SuccBB).
2463void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
2464 BasicBlock *BB,
2465 BasicBlock *NewBB,
2466 BasicBlock *SuccBB) {
2467 if (!HasProfileData)
2468 return;
2469
2470 assert(BFI && BPI && "BFI & BPI should have been created here")((BFI && BPI && "BFI & BPI should have been created here"
) ? static_cast<void> (0) : __assert_fail ("BFI && BPI && \"BFI & BPI should have been created here\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2470, __PRETTY_FUNCTION__))
;
2471
2472 // As the edge from PredBB to BB is deleted, we have to update the block
2473 // frequency of BB.
2474 auto BBOrigFreq = BFI->getBlockFreq(BB);
2475 auto NewBBFreq = BFI->getBlockFreq(NewBB);
2476 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
2477 auto BBNewFreq = BBOrigFreq - NewBBFreq;
2478 BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
2479
2480 // Collect updated outgoing edges' frequencies from BB and use them to update
2481 // edge probabilities.
2482 SmallVector<uint64_t, 4> BBSuccFreq;
2483 for (BasicBlock *Succ : successors(BB)) {
2484 auto SuccFreq = (Succ == SuccBB)
2485 ? BB2SuccBBFreq - NewBBFreq
2486 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
2487 BBSuccFreq.push_back(SuccFreq.getFrequency());
2488 }
2489
2490 uint64_t MaxBBSuccFreq =
2491 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
2492
2493 SmallVector<BranchProbability, 4> BBSuccProbs;
2494 if (MaxBBSuccFreq == 0)
2495 BBSuccProbs.assign(BBSuccFreq.size(),
2496 {1, static_cast<unsigned>(BBSuccFreq.size())});
2497 else {
2498 for (uint64_t Freq : BBSuccFreq)
2499 BBSuccProbs.push_back(
2500 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
2501 // Normalize edge probabilities so that they sum up to one.
2502 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
2503 BBSuccProbs.end());
2504 }
2505
2506 // Update edge probabilities in BPI.
2507 BPI->setEdgeProbability(BB, BBSuccProbs);
2508
2509 // Update the profile metadata as well.
2510 //
2511 // Don't do this if the profile of the transformed blocks was statically
2512 // estimated. (This could occur despite the function having an entry
2513 // frequency in completely cold parts of the CFG.)
2514 //
2515 // In this case we don't want to suggest to subsequent passes that the
2516 // calculated weights are fully consistent. Consider this graph:
2517 //
2518 // check_1
2519 // 50% / |
2520 // eq_1 | 50%
2521 // \ |
2522 // check_2
2523 // 50% / |
2524 // eq_2 | 50%
2525 // \ |
2526 // check_3
2527 // 50% / |
2528 // eq_3 | 50%
2529 // \ |
2530 //
2531 // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
2532 // the overall probabilities are inconsistent; the total probability that the
2533 // value is either 1, 2 or 3 is 150%.
2534 //
2535 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
2536 // becomes 0%. This is even worse if the edge whose probability becomes 0% is
2537 // the loop exit edge. Then based solely on static estimation we would assume
2538 // the loop was extremely hot.
2539 //
2540 // FIXME this locally as well so that BPI and BFI are consistent as well. We
2541 // shouldn't make edges extremely likely or unlikely based solely on static
2542 // estimation.
2543 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
2544 SmallVector<uint32_t, 4> Weights;
2545 for (auto Prob : BBSuccProbs)
2546 Weights.push_back(Prob.getNumerator());
2547
2548 auto TI = BB->getTerminator();
2549 TI->setMetadata(
2550 LLVMContext::MD_prof,
2551 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
2552 }
2553}
2554
2555/// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
2556/// to BB which contains an i1 PHI node and a conditional branch on that PHI.
2557/// If we can duplicate the contents of BB up into PredBB do so now, this
2558/// improves the odds that the branch will be on an analyzable instruction like
2559/// a compare.
2560bool JumpThreadingPass::DuplicateCondBranchOnPHIIntoPred(
2561 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
2562 assert(!PredBBs.empty() && "Can't handle an empty set")((!PredBBs.empty() && "Can't handle an empty set") ? static_cast
<void> (0) : __assert_fail ("!PredBBs.empty() && \"Can't handle an empty set\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2562, __PRETTY_FUNCTION__))
;
2563
2564 // If BB is a loop header, then duplicating this block outside the loop would
2565 // cause us to transform this into an irreducible loop, don't do this.
2566 // See the comments above FindLoopHeaders for justifications and caveats.
2567 if (LoopHeaders.count(BB)) {
2568 LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating loop header '"
<< BB->getName() << "' into predecessor block '"
<< PredBBs[0]->getName() << "' - it might create an irreducible loop!\n"
; } } while (false)
2569 << "' into predecessor block '" << PredBBs[0]->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating loop header '"
<< BB->getName() << "' into predecessor block '"
<< PredBBs[0]->getName() << "' - it might create an irreducible loop!\n"
; } } while (false)
2570 << "' - it might create an irreducible loop!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating loop header '"
<< BB->getName() << "' into predecessor block '"
<< PredBBs[0]->getName() << "' - it might create an irreducible loop!\n"
; } } while (false)
;
2571 return false;
2572 }
2573
2574 unsigned DuplicationCost =
2575 getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold);
2576 if (DuplicationCost > BBDupThreshold) {
2577 LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating BB '"
<< BB->getName() << "' - Cost is too high: " <<
DuplicationCost << "\n"; } } while (false)
2578 << "' - Cost is too high: " << DuplicationCost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Not duplicating BB '"
<< BB->getName() << "' - Cost is too high: " <<
DuplicationCost << "\n"; } } while (false)
;
2579 return false;
2580 }
2581
2582 // And finally, do it! Start by factoring the predecessors if needed.
2583 std::vector<DominatorTree::UpdateType> Updates;
2584 BasicBlock *PredBB;
2585 if (PredBBs.size() == 1)
2586 PredBB = PredBBs[0];
2587 else {
2588 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
2589 << " common predecessors.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Factoring out " <<
PredBBs.size() << " common predecessors.\n"; } } while
(false)
;
2590 PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
2591 }
2592 Updates.push_back({DominatorTree::Delete, PredBB, BB});
2593
2594 // Okay, we decided to do this! Clone all the instructions in BB onto the end
2595 // of PredBB.
2596 LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
2597 << "' into end of '" << PredBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
2598 << "' to eliminate branch on phi. Cost: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
2599 << DuplicationCost << " block is:" << *BB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << " Duplicating block '"
<< BB->getName() << "' into end of '" <<
PredBB->getName() << "' to eliminate branch on phi. Cost: "
<< DuplicationCost << " block is:" << *BB <<
"\n"; } } while (false)
;
2600
2601 // Unless PredBB ends with an unconditional branch, split the edge so that we
2602 // can just clone the bits from BB into the end of the new PredBB.
2603 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2604
2605 if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2606 BasicBlock *OldPredBB = PredBB;
2607 PredBB = SplitEdge(OldPredBB, BB);
2608 Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB});
2609 Updates.push_back({DominatorTree::Insert, PredBB, BB});
2610 Updates.push_back({DominatorTree::Delete, OldPredBB, BB});
2611 OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
2612 }
2613
2614 // We are going to have to map operands from the original BB block into the
2615 // PredBB block. Evaluate PHI nodes in BB.
2616 DenseMap<Instruction*, Value*> ValueMapping;
2617
2618 BasicBlock::iterator BI = BB->begin();
2619 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
2620 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
2621 // Clone the non-phi instructions of BB into PredBB, keeping track of the
2622 // mapping and using it to remap operands in the cloned instructions.
2623 for (; BI != BB->end(); ++BI) {
2624 Instruction *New = BI->clone();
2625
2626 // Remap operands to patch up intra-block references.
2627 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2628 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2629 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
2630 if (I != ValueMapping.end())
2631 New->setOperand(i, I->second);
2632 }
2633
2634 // If this instruction can be simplified after the operands are updated,
2635 // just use the simplified value instead. This frequently happens due to
2636 // phi translation.
2637 if (Value *IV = SimplifyInstruction(
2638 New,
2639 {BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) {
2640 ValueMapping[&*BI] = IV;
2641 if (!New->mayHaveSideEffects()) {
2642 New->deleteValue();
2643 New = nullptr;
2644 }
2645 } else {
2646 ValueMapping[&*BI] = New;
2647 }
2648 if (New) {
2649 // Otherwise, insert the new instruction into the block.
2650 New->setName(BI->getName());
2651 PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
2652 // Update Dominance from simplified New instruction operands.
2653 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2654 if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i)))
2655 Updates.push_back({DominatorTree::Insert, PredBB, SuccBB});
2656 }
2657 }
2658
2659 // Check to see if the targets of the branch had PHI nodes. If so, we need to
2660 // add entries to the PHI nodes for branch from PredBB now.
2661 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
2662 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
2663 ValueMapping);
2664 AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
2665 ValueMapping);
2666
2667 UpdateSSA(BB, PredBB, ValueMapping);
2668
2669 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
2670 // that we nuked.
2671 BB->removePredecessor(PredBB, true);
2672
2673 // Remove the unconditional branch at the end of the PredBB block.
2674 OldPredBranch->eraseFromParent();
2675 DTU->applyUpdatesPermissive(Updates);
2676
2677 ++NumDupes;
2678 return true;
2679}
2680
2681// Pred is a predecessor of BB with an unconditional branch to BB. SI is
2682// a Select instruction in Pred. BB has other predecessors and SI is used in
2683// a PHI node in BB. SI has no other use.
2684// A new basic block, NewBB, is created and SI is converted to compare and
2685// conditional branch. SI is erased from parent.
2686void JumpThreadingPass::UnfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB,
2687 SelectInst *SI, PHINode *SIUse,
2688 unsigned Idx) {
2689 // Expand the select.
2690 //
2691 // Pred --
2692 // | v
2693 // | NewBB
2694 // | |
2695 // |-----
2696 // v
2697 // BB
2698 BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator());
2699 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
2700 BB->getParent(), BB);
2701 // Move the unconditional branch to NewBB.
2702 PredTerm->removeFromParent();
2703 NewBB->getInstList().insert(NewBB->end(), PredTerm);
2704 // Create a conditional branch and update PHI nodes.
2705 BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
2706 SIUse->setIncomingValue(Idx, SI->getFalseValue());
2707 SIUse->addIncoming(SI->getTrueValue(), NewBB);
2708
2709 // The select is now dead.
2710 SI->eraseFromParent();
2711 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB},
2712 {DominatorTree::Insert, Pred, NewBB}});
2713
2714 // Update any other PHI nodes in BB.
2715 for (BasicBlock::iterator BI = BB->begin();
2716 PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
2717 if (Phi != SIUse)
2718 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
2719}
2720
2721bool JumpThreadingPass::TryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) {
2722 PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition());
2723
2724 if (!CondPHI || CondPHI->getParent() != BB)
2725 return false;
2726
2727 for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) {
2728 BasicBlock *Pred = CondPHI->getIncomingBlock(I);
2729 SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I));
2730
2731 // The second and third condition can be potentially relaxed. Currently
2732 // the conditions help to simplify the code and allow us to reuse existing
2733 // code, developed for TryToUnfoldSelect(CmpInst *, BasicBlock *)
2734 if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse())
2735 continue;
2736
2737 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2738 if (!PredTerm || !PredTerm->isUnconditional())
2739 continue;
2740
2741 UnfoldSelectInstr(Pred, BB, PredSI, CondPHI, I);
2742 return true;
2743 }
2744 return false;
2745}
2746
2747/// TryToUnfoldSelect - Look for blocks of the form
2748/// bb1:
2749/// %a = select
2750/// br bb2
2751///
2752/// bb2:
2753/// %p = phi [%a, %bb1] ...
2754/// %c = icmp %p
2755/// br i1 %c
2756///
2757/// And expand the select into a branch structure if one of its arms allows %c
2758/// to be folded. This later enables threading from bb1 over bb2.
2759bool JumpThreadingPass::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
2760 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2761 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
2762 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
2763
2764 if (!CondBr || !CondBr->isConditional() || !CondLHS ||
2765 CondLHS->getParent() != BB)
2766 return false;
2767
2768 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
2769 BasicBlock *Pred = CondLHS->getIncomingBlock(I);
2770 SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
2771
2772 // Look if one of the incoming values is a select in the corresponding
2773 // predecessor.
2774 if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
2775 continue;
2776
2777 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2778 if (!PredTerm || !PredTerm->isUnconditional())
2779 continue;
2780
2781 // Now check if one of the select values would allow us to constant fold the
2782 // terminator in BB. We don't do the transform if both sides fold, those
2783 // cases will be threaded in any case.
2784 LazyValueInfo::Tristate LHSFolds =
2785 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
2786 CondRHS, Pred, BB, CondCmp);
2787 LazyValueInfo::Tristate RHSFolds =
2788 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
2789 CondRHS, Pred, BB, CondCmp);
2790 if ((LHSFolds != LazyValueInfo::Unknown ||
2791 RHSFolds != LazyValueInfo::Unknown) &&
2792 LHSFolds != RHSFolds) {
2793 UnfoldSelectInstr(Pred, BB, SI, CondLHS, I);
2794 return true;
2795 }
2796 }
2797 return false;
2798}
2799
2800/// TryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the
2801/// same BB in the form
2802/// bb:
2803/// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
2804/// %s = select %p, trueval, falseval
2805///
2806/// or
2807///
2808/// bb:
2809/// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ...
2810/// %c = cmp %p, 0
2811/// %s = select %c, trueval, falseval
2812///
2813/// And expand the select into a branch structure. This later enables
2814/// jump-threading over bb in this pass.
2815///
2816/// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
2817/// select if the associated PHI has at least one constant. If the unfolded
2818/// select is not jump-threaded, it will be folded again in the later
2819/// optimizations.
2820bool JumpThreadingPass::TryToUnfoldSelectInCurrBB(BasicBlock *BB) {
2821 // This transform would reduce the quality of msan diagnostics.
2822 // Disable this transform under MemorySanitizer.
2823 if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
2824 return false;
2825
2826 // If threading this would thread across a loop header, don't thread the edge.
2827 // See the comments above FindLoopHeaders for justifications and caveats.
2828 if (LoopHeaders.count(BB))
2829 return false;
2830
2831 for (BasicBlock::iterator BI = BB->begin();
2832 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2833 // Look for a Phi having at least one constant incoming value.
2834 if (llvm::all_of(PN->incoming_values(),
2835 [](Value *V) { return !isa<ConstantInt>(V); }))
2836 continue;
2837
2838 auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
2839 // Check if SI is in BB and use V as condition.
2840 if (SI->getParent() != BB)
2841 return false;
2842 Value *Cond = SI->getCondition();
2843 return (Cond && Cond == V && Cond->getType()->isIntegerTy(1));
2844 };
2845
2846 SelectInst *SI = nullptr;
2847 for (Use &U : PN->uses()) {
2848 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
2849 // Look for a ICmp in BB that compares PN with a constant and is the
2850 // condition of a Select.
2851 if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
2852 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
2853 if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
2854 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
2855 SI = SelectI;
2856 break;
2857 }
2858 } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
2859 // Look for a Select in BB that uses PN as condition.
2860 if (isUnfoldCandidate(SelectI, U.get())) {
2861 SI = SelectI;
2862 break;
2863 }
2864 }
2865 }
2866
2867 if (!SI)
2868 continue;
2869 // Expand the select.
2870 Value *Cond = SI->getCondition();
2871 if (InsertFreezeWhenUnfoldingSelect &&
2872 !isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI,
2873 &DTU->getDomTree()))
2874 Cond = new FreezeInst(Cond, "cond.fr", SI);
2875 Instruction *Term = SplitBlockAndInsertIfThen(Cond, SI, false);
2876 BasicBlock *SplitBB = SI->getParent();
2877 BasicBlock *NewBB = Term->getParent();
2878 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
2879 NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
2880 NewPN->addIncoming(SI->getFalseValue(), BB);
2881 SI->replaceAllUsesWith(NewPN);
2882 SI->eraseFromParent();
2883 // NewBB and SplitBB are newly created blocks which require insertion.
2884 std::vector<DominatorTree::UpdateType> Updates;
2885 Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
2886 Updates.push_back({DominatorTree::Insert, BB, SplitBB});
2887 Updates.push_back({DominatorTree::Insert, BB, NewBB});
2888 Updates.push_back({DominatorTree::Insert, NewBB, SplitBB});
2889 // BB's successors were moved to SplitBB, update DTU accordingly.
2890 for (auto *Succ : successors(SplitBB)) {
2891 Updates.push_back({DominatorTree::Delete, BB, Succ});
2892 Updates.push_back({DominatorTree::Insert, SplitBB, Succ});
2893 }
2894 DTU->applyUpdatesPermissive(Updates);
2895 return true;
2896 }
2897 return false;
2898}
2899
2900/// Try to propagate a guard from the current BB into one of its predecessors
2901/// in case if another branch of execution implies that the condition of this
2902/// guard is always true. Currently we only process the simplest case that
2903/// looks like:
2904///
2905/// Start:
2906/// %cond = ...
2907/// br i1 %cond, label %T1, label %F1
2908/// T1:
2909/// br label %Merge
2910/// F1:
2911/// br label %Merge
2912/// Merge:
2913/// %condGuard = ...
2914/// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
2915///
2916/// And cond either implies condGuard or !condGuard. In this case all the
2917/// instructions before the guard can be duplicated in both branches, and the
2918/// guard is then threaded to one of them.
2919bool JumpThreadingPass::ProcessGuards(BasicBlock *BB) {
2920 using namespace PatternMatch;
2921
2922 // We only want to deal with two predecessors.
2923 BasicBlock *Pred1, *Pred2;
2924 auto PI = pred_begin(BB), PE = pred_end(BB);
2925 if (PI == PE)
2926 return false;
2927 Pred1 = *PI++;
2928 if (PI == PE)
2929 return false;
2930 Pred2 = *PI++;
2931 if (PI != PE)
2932 return false;
2933 if (Pred1 == Pred2)
2934 return false;
2935
2936 // Try to thread one of the guards of the block.
2937 // TODO: Look up deeper than to immediate predecessor?
2938 auto *Parent = Pred1->getSinglePredecessor();
2939 if (!Parent || Parent != Pred2->getSinglePredecessor())
2940 return false;
2941
2942 if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
2943 for (auto &I : *BB)
2944 if (isGuard(&I) && ThreadGuard(BB, cast<IntrinsicInst>(&I), BI))
2945 return true;
2946
2947 return false;
2948}
2949
2950/// Try to propagate the guard from BB which is the lower block of a diamond
2951/// to one of its branches, in case if diamond's condition implies guard's
2952/// condition.
2953bool JumpThreadingPass::ThreadGuard(BasicBlock *BB, IntrinsicInst *Guard,
2954 BranchInst *BI) {
2955 assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?")((BI->getNumSuccessors() == 2 && "Wrong number of successors?"
) ? static_cast<void> (0) : __assert_fail ("BI->getNumSuccessors() == 2 && \"Wrong number of successors?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2955, __PRETTY_FUNCTION__))
;
2956 assert(BI->isConditional() && "Unconditional branch has 2 successors?")((BI->isConditional() && "Unconditional branch has 2 successors?"
) ? static_cast<void> (0) : __assert_fail ("BI->isConditional() && \"Unconditional branch has 2 successors?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2956, __PRETTY_FUNCTION__))
;
2957 Value *GuardCond = Guard->getArgOperand(0);
2958 Value *BranchCond = BI->getCondition();
2959 BasicBlock *TrueDest = BI->getSuccessor(0);
2960 BasicBlock *FalseDest = BI->getSuccessor(1);
2961
2962 auto &DL = BB->getModule()->getDataLayout();
2963 bool TrueDestIsSafe = false;
2964 bool FalseDestIsSafe = false;
2965
2966 // True dest is safe if BranchCond => GuardCond.
2967 auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
2968 if (Impl && *Impl)
2969 TrueDestIsSafe = true;
2970 else {
2971 // False dest is safe if !BranchCond => GuardCond.
2972 Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false);
2973 if (Impl && *Impl)
2974 FalseDestIsSafe = true;
2975 }
2976
2977 if (!TrueDestIsSafe && !FalseDestIsSafe)
2978 return false;
2979
2980 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
2981 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
2982
2983 ValueToValueMapTy UnguardedMapping, GuardedMapping;
2984 Instruction *AfterGuard = Guard->getNextNode();
2985 unsigned Cost = getJumpThreadDuplicationCost(BB, AfterGuard, BBDupThreshold);
2986 if (Cost > BBDupThreshold)
2987 return false;
2988 // Duplicate all instructions before the guard and the guard itself to the
2989 // branch where implication is not proved.
2990 BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween(
2991 BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
2992 assert(GuardedBlock && "Could not create the guarded block?")((GuardedBlock && "Could not create the guarded block?"
) ? static_cast<void> (0) : __assert_fail ("GuardedBlock && \"Could not create the guarded block?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2992, __PRETTY_FUNCTION__))
;
2993 // Duplicate all instructions before the guard in the unguarded branch.
2994 // Since we have successfully duplicated the guarded block and this block
2995 // has fewer instructions, we expect it to succeed.
2996 BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween(
2997 BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
2998 assert(UnguardedBlock && "Could not create the unguarded block?")((UnguardedBlock && "Could not create the unguarded block?"
) ? static_cast<void> (0) : __assert_fail ("UnguardedBlock && \"Could not create the unguarded block?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 2998, __PRETTY_FUNCTION__))
;
2999 LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "Moved guard " <<
*Guard << " to block " << GuardedBlock->getName
() << "\n"; } } while (false)
3000 << GuardedBlock->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("jump-threading")) { dbgs() << "Moved guard " <<
*Guard << " to block " << GuardedBlock->getName
() << "\n"; } } while (false)
;
3001 // Some instructions before the guard may still have uses. For them, we need
3002 // to create Phi nodes merging their copies in both guarded and unguarded
3003 // branches. Those instructions that have no uses can be just removed.
3004 SmallVector<Instruction *, 4> ToRemove;
3005 for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
3006 if (!isa<PHINode>(&*BI))
3007 ToRemove.push_back(&*BI);
3008
3009 Instruction *InsertionPoint = &*BB->getFirstInsertionPt();
3010 assert(InsertionPoint && "Empty block?")((InsertionPoint && "Empty block?") ? static_cast<
void> (0) : __assert_fail ("InsertionPoint && \"Empty block?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/lib/Transforms/Scalar/JumpThreading.cpp"
, 3010, __PRETTY_FUNCTION__))
;
3011 // Substitute with Phis & remove.
3012 for (auto *Inst : reverse(ToRemove)) {
3013 if (!Inst->use_empty()) {
3014 PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
3015 NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
3016 NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
3017 NewPN->insertBefore(InsertionPoint);
3018 Inst->replaceAllUsesWith(NewPN);
3019 }
3020 Inst->eraseFromParent();
3021 }
3022 return true;
3023}

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h

1//===- llvm/Instructions.h - Instruction subclass definitions ---*- 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 exposes the class definitions of all of the subclasses of the
10// Instruction class. This is meant to be an easy way to get access to all
11// instruction subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_INSTRUCTIONS_H
16#define LLVM_IR_INSTRUCTIONS_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/Bitfields.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/ADT/iterator.h"
26#include "llvm/ADT/iterator_range.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/BasicBlock.h"
29#include "llvm/IR/CallingConv.h"
30#include "llvm/IR/CFG.h"
31#include "llvm/IR/Constant.h"
32#include "llvm/IR/DerivedTypes.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/InstrTypes.h"
35#include "llvm/IR/Instruction.h"
36#include "llvm/IR/OperandTraits.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Use.h"
39#include "llvm/IR/User.h"
40#include "llvm/IR/Value.h"
41#include "llvm/Support/AtomicOrdering.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/ErrorHandling.h"
44#include <cassert>
45#include <cstddef>
46#include <cstdint>
47#include <iterator>
48
49namespace llvm {
50
51class APInt;
52class ConstantInt;
53class DataLayout;
54class LLVMContext;
55
56//===----------------------------------------------------------------------===//
57// AllocaInst Class
58//===----------------------------------------------------------------------===//
59
60/// an instruction to allocate memory on the stack
61class AllocaInst : public UnaryInstruction {
62 Type *AllocatedType;
63
64 using AlignmentField = AlignmentBitfieldElementT<0>;
65 using UsedWithInAllocaField = BoolBitfieldElementT<AlignmentField::NextBit>;
66 using SwiftErrorField = BoolBitfieldElementT<UsedWithInAllocaField::NextBit>;
67 static_assert(Bitfield::areContiguous<AlignmentField, UsedWithInAllocaField,
68 SwiftErrorField>(),
69 "Bitfields must be contiguous");
70
71protected:
72 // Note: Instruction needs to be a friend here to call cloneImpl.
73 friend class Instruction;
74
75 AllocaInst *cloneImpl() const;
76
77public:
78 explicit AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
79 const Twine &Name, Instruction *InsertBefore);
80 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
81 const Twine &Name, BasicBlock *InsertAtEnd);
82
83 AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
84 Instruction *InsertBefore);
85 AllocaInst(Type *Ty, unsigned AddrSpace,
86 const Twine &Name, BasicBlock *InsertAtEnd);
87
88 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align,
89 const Twine &Name = "", Instruction *InsertBefore = nullptr);
90 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align,
91 const Twine &Name, BasicBlock *InsertAtEnd);
92
93 /// Return true if there is an allocation size parameter to the allocation
94 /// instruction that is not 1.
95 bool isArrayAllocation() const;
96
97 /// Get the number of elements allocated. For a simple allocation of a single
98 /// element, this will return a constant 1 value.
99 const Value *getArraySize() const { return getOperand(0); }
100 Value *getArraySize() { return getOperand(0); }
101
102 /// Overload to return most specific pointer type.
103 PointerType *getType() const {
104 return cast<PointerType>(Instruction::getType());
105 }
106
107 /// Get allocation size in bits. Returns None if size can't be determined,
108 /// e.g. in case of a VLA.
109 Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const;
110
111 /// Return the type that is being allocated by the instruction.
112 Type *getAllocatedType() const { return AllocatedType; }
113 /// for use only in special circumstances that need to generically
114 /// transform a whole instruction (eg: IR linking and vectorization).
115 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
116
117 /// Return the alignment of the memory that is being allocated by the
118 /// instruction.
119 Align getAlign() const {
120 return Align(1ULL << getSubclassData<AlignmentField>());
121 }
122
123 void setAlignment(Align Align) {
124 setSubclassData<AlignmentField>(Log2(Align));
125 }
126
127 // FIXME: Remove this one transition to Align is over.
128 unsigned getAlignment() const { return getAlign().value(); }
129
130 /// Return true if this alloca is in the entry block of the function and is a
131 /// constant size. If so, the code generator will fold it into the
132 /// prolog/epilog code, so it is basically free.
133 bool isStaticAlloca() const;
134
135 /// Return true if this alloca is used as an inalloca argument to a call. Such
136 /// allocas are never considered static even if they are in the entry block.
137 bool isUsedWithInAlloca() const {
138 return getSubclassData<UsedWithInAllocaField>();
139 }
140
141 /// Specify whether this alloca is used to represent the arguments to a call.
142 void setUsedWithInAlloca(bool V) {
143 setSubclassData<UsedWithInAllocaField>(V);
144 }
145
146 /// Return true if this alloca is used as a swifterror argument to a call.
147 bool isSwiftError() const { return getSubclassData<SwiftErrorField>(); }
148 /// Specify whether this alloca is used to represent a swifterror.
149 void setSwiftError(bool V) { setSubclassData<SwiftErrorField>(V); }
150
151 // Methods for support type inquiry through isa, cast, and dyn_cast:
152 static bool classof(const Instruction *I) {
153 return (I->getOpcode() == Instruction::Alloca);
154 }
155 static bool classof(const Value *V) {
156 return isa<Instruction>(V) && classof(cast<Instruction>(V));
157 }
158
159private:
160 // Shadow Instruction::setInstructionSubclassData with a private forwarding
161 // method so that subclasses cannot accidentally use it.
162 template <typename Bitfield>
163 void setSubclassData(typename Bitfield::Type Value) {
164 Instruction::setSubclassData<Bitfield>(Value);
165 }
166};
167
168//===----------------------------------------------------------------------===//
169// LoadInst Class
170//===----------------------------------------------------------------------===//
171
172/// An instruction for reading from memory. This uses the SubclassData field in
173/// Value to store whether or not the load is volatile.
174class LoadInst : public UnaryInstruction {
175 using VolatileField = BoolBitfieldElementT<0>;
176 using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>;
177 using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>;
178 static_assert(
179 Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(),
180 "Bitfields must be contiguous");
181
182 void AssertOK();
183
184protected:
185 // Note: Instruction needs to be a friend here to call cloneImpl.
186 friend class Instruction;
187
188 LoadInst *cloneImpl() const;
189
190public:
191 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr,
192 Instruction *InsertBefore);
193 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 Instruction *InsertBefore);
196 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
197 BasicBlock *InsertAtEnd);
198 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
199 Align Align, Instruction *InsertBefore = nullptr);
200 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
201 Align Align, BasicBlock *InsertAtEnd);
202 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
203 Align Align, AtomicOrdering Order,
204 SyncScope::ID SSID = SyncScope::System,
205 Instruction *InsertBefore = nullptr);
206 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
207 Align Align, AtomicOrdering Order, SyncScope::ID SSID,
208 BasicBlock *InsertAtEnd);
209
210 /// Return true if this is a load from a volatile memory location.
211 bool isVolatile() const { return getSubclassData<VolatileField>(); }
212
213 /// Specify whether this is a volatile load or not.
214 void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
215
216 /// Return the alignment of the access that is being performed.
217 /// FIXME: Remove this function once transition to Align is over.
218 /// Use getAlign() instead.
219 unsigned getAlignment() const { return getAlign().value(); }
220
221 /// Return the alignment of the access that is being performed.
222 Align getAlign() const {
223 return Align(1ULL << (getSubclassData<AlignmentField>()));
224 }
225
226 void setAlignment(Align Align) {
227 setSubclassData<AlignmentField>(Log2(Align));
228 }
229
230 /// Returns the ordering constraint of this load instruction.
231 AtomicOrdering getOrdering() const {
232 return getSubclassData<OrderingField>();
233 }
234 /// Sets the ordering constraint of this load instruction. May not be Release
235 /// or AcquireRelease.
236 void setOrdering(AtomicOrdering Ordering) {
237 setSubclassData<OrderingField>(Ordering);
238 }
239
240 /// Returns the synchronization scope ID of this load instruction.
241 SyncScope::ID getSyncScopeID() const {
242 return SSID;
243 }
244
245 /// Sets the synchronization scope ID of this load instruction.
246 void setSyncScopeID(SyncScope::ID SSID) {
247 this->SSID = SSID;
248 }
249
250 /// Sets the ordering constraint and the synchronization scope ID of this load
251 /// instruction.
252 void setAtomic(AtomicOrdering Ordering,
253 SyncScope::ID SSID = SyncScope::System) {
254 setOrdering(Ordering);
255 setSyncScopeID(SSID);
256 }
257
258 bool isSimple() const { return !isAtomic() && !isVolatile(); }
259
260 bool isUnordered() const {
261 return (getOrdering() == AtomicOrdering::NotAtomic ||
2
Assuming the condition is true
4
Returning the value 1, which participates in a condition later
262 getOrdering() == AtomicOrdering::Unordered) &&
263 !isVolatile();
3
Assuming the condition is true
264 }
265
266 Value *getPointerOperand() { return getOperand(0); }
267 const Value *getPointerOperand() const { return getOperand(0); }
268 static unsigned getPointerOperandIndex() { return 0U; }
269 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
270
271 /// Returns the address space of the pointer operand.
272 unsigned getPointerAddressSpace() const {
273 return getPointerOperandType()->getPointerAddressSpace();
274 }
275
276 // Methods for support type inquiry through isa, cast, and dyn_cast:
277 static bool classof(const Instruction *I) {
278 return I->getOpcode() == Instruction::Load;
279 }
280 static bool classof(const Value *V) {
281 return isa<Instruction>(V) && classof(cast<Instruction>(V));
282 }
283
284private:
285 // Shadow Instruction::setInstructionSubclassData with a private forwarding
286 // method so that subclasses cannot accidentally use it.
287 template <typename Bitfield>
288 void setSubclassData(typename Bitfield::Type Value) {
289 Instruction::setSubclassData<Bitfield>(Value);
290 }
291
292 /// The synchronization scope ID of this load instruction. Not quite enough
293 /// room in SubClassData for everything, so synchronization scope ID gets its
294 /// own field.
295 SyncScope::ID SSID;
296};
297
298//===----------------------------------------------------------------------===//
299// StoreInst Class
300//===----------------------------------------------------------------------===//
301
302/// An instruction for storing to memory.
303class StoreInst : public Instruction {
304 using VolatileField = BoolBitfieldElementT<0>;
305 using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>;
306 using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>;
307 static_assert(
308 Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(),
309 "Bitfields must be contiguous");
310
311 void AssertOK();
312
313protected:
314 // Note: Instruction needs to be a friend here to call cloneImpl.
315 friend class Instruction;
316
317 StoreInst *cloneImpl() const;
318
319public:
320 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
321 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
322 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore);
323 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
324 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
325 Instruction *InsertBefore = nullptr);
326 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
327 BasicBlock *InsertAtEnd);
328 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
329 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
330 Instruction *InsertBefore = nullptr);
331 StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align,
332 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
333
334 // allocate space for exactly two operands
335 void *operator new(size_t s) {
336 return User::operator new(s, 2);
337 }
338
339 /// Return true if this is a store to a volatile memory location.
340 bool isVolatile() const { return getSubclassData<VolatileField>(); }
341
342 /// Specify whether this is a volatile store or not.
343 void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
344
345 /// Transparently provide more efficient getOperand methods.
346 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
347
348 /// Return the alignment of the access that is being performed
349 /// FIXME: Remove this function once transition to Align is over.
350 /// Use getAlign() instead.
351 unsigned getAlignment() const { return getAlign().value(); }
352
353 Align getAlign() const {
354 return Align(1ULL << (getSubclassData<AlignmentField>()));
355 }
356
357 void setAlignment(Align Align) {
358 setSubclassData<AlignmentField>(Log2(Align));
359 }
360
361 /// Returns the ordering constraint of this store instruction.
362 AtomicOrdering getOrdering() const {
363 return getSubclassData<OrderingField>();
364 }
365
366 /// Sets the ordering constraint of this store instruction. May not be
367 /// Acquire or AcquireRelease.
368 void setOrdering(AtomicOrdering Ordering) {
369 setSubclassData<OrderingField>(Ordering);
370 }
371
372 /// Returns the synchronization scope ID of this store instruction.
373 SyncScope::ID getSyncScopeID() const {
374 return SSID;
375 }
376
377 /// Sets the synchronization scope ID of this store instruction.
378 void setSyncScopeID(SyncScope::ID SSID) {
379 this->SSID = SSID;
380 }
381
382 /// Sets the ordering constraint and the synchronization scope ID of this
383 /// store instruction.
384 void setAtomic(AtomicOrdering Ordering,
385 SyncScope::ID SSID = SyncScope::System) {
386 setOrdering(Ordering);
387 setSyncScopeID(SSID);
388 }
389
390 bool isSimple() const { return !isAtomic() && !isVolatile(); }
391
392 bool isUnordered() const {
393 return (getOrdering() == AtomicOrdering::NotAtomic ||
394 getOrdering() == AtomicOrdering::Unordered) &&
395 !isVolatile();
396 }
397
398 Value *getValueOperand() { return getOperand(0); }
399 const Value *getValueOperand() const { return getOperand(0); }
400
401 Value *getPointerOperand() { return getOperand(1); }
402 const Value *getPointerOperand() const { return getOperand(1); }
403 static unsigned getPointerOperandIndex() { return 1U; }
404 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
405
406 /// Returns the address space of the pointer operand.
407 unsigned getPointerAddressSpace() const {
408 return getPointerOperandType()->getPointerAddressSpace();
409 }
410
411 // Methods for support type inquiry through isa, cast, and dyn_cast:
412 static bool classof(const Instruction *I) {
413 return I->getOpcode() == Instruction::Store;
414 }
415 static bool classof(const Value *V) {
416 return isa<Instruction>(V) && classof(cast<Instruction>(V));
417 }
418
419private:
420 // Shadow Instruction::setInstructionSubclassData with a private forwarding
421 // method so that subclasses cannot accidentally use it.
422 template <typename Bitfield>
423 void setSubclassData(typename Bitfield::Type Value) {
424 Instruction::setSubclassData<Bitfield>(Value);
425 }
426
427 /// The synchronization scope ID of this store instruction. Not quite enough
428 /// room in SubClassData for everything, so synchronization scope ID gets its
429 /// own field.
430 SyncScope::ID SSID;
431};
432
433template <>
434struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
435};
436
437DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits
<StoreInst>::op_begin(this); } StoreInst::const_op_iterator
StoreInst::op_begin() const { return OperandTraits<StoreInst
>::op_begin(const_cast<StoreInst*>(this)); } StoreInst
::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst
>::op_end(this); } StoreInst::const_op_iterator StoreInst::
op_end() const { return OperandTraits<StoreInst>::op_end
(const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand
(unsigned i_nocapture) const { ((i_nocapture < OperandTraits
<StoreInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 437, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<StoreInst>::op_begin(const_cast<StoreInst
*>(this))[i_nocapture].get()); } void StoreInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<StoreInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 437, __PRETTY_FUNCTION__)); OperandTraits<StoreInst>::
op_begin(this)[i_nocapture] = Val_nocapture; } unsigned StoreInst
::getNumOperands() const { return OperandTraits<StoreInst>
::operands(this); } template <int Idx_nocapture> Use &
StoreInst::Op() { return this->OpFrom<Idx_nocapture>
(this); } template <int Idx_nocapture> const Use &StoreInst
::Op() const { return this->OpFrom<Idx_nocapture>(this
); }
438
439//===----------------------------------------------------------------------===//
440// FenceInst Class
441//===----------------------------------------------------------------------===//
442
443/// An instruction for ordering other memory operations.
444class FenceInst : public Instruction {
445 using OrderingField = AtomicOrderingBitfieldElementT<0>;
446
447 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
448
449protected:
450 // Note: Instruction needs to be a friend here to call cloneImpl.
451 friend class Instruction;
452
453 FenceInst *cloneImpl() const;
454
455public:
456 // Ordering may only be Acquire, Release, AcquireRelease, or
457 // SequentiallyConsistent.
458 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
459 SyncScope::ID SSID = SyncScope::System,
460 Instruction *InsertBefore = nullptr);
461 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
462 BasicBlock *InsertAtEnd);
463
464 // allocate space for exactly zero operands
465 void *operator new(size_t s) {
466 return User::operator new(s, 0);
467 }
468
469 /// Returns the ordering constraint of this fence instruction.
470 AtomicOrdering getOrdering() const {
471 return getSubclassData<OrderingField>();
472 }
473
474 /// Sets the ordering constraint of this fence instruction. May only be
475 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
476 void setOrdering(AtomicOrdering Ordering) {
477 setSubclassData<OrderingField>(Ordering);
478 }
479
480 /// Returns the synchronization scope ID of this fence instruction.
481 SyncScope::ID getSyncScopeID() const {
482 return SSID;
483 }
484
485 /// Sets the synchronization scope ID of this fence instruction.
486 void setSyncScopeID(SyncScope::ID SSID) {
487 this->SSID = SSID;
488 }
489
490 // Methods for support type inquiry through isa, cast, and dyn_cast:
491 static bool classof(const Instruction *I) {
492 return I->getOpcode() == Instruction::Fence;
493 }
494 static bool classof(const Value *V) {
495 return isa<Instruction>(V) && classof(cast<Instruction>(V));
496 }
497
498private:
499 // Shadow Instruction::setInstructionSubclassData with a private forwarding
500 // method so that subclasses cannot accidentally use it.
501 template <typename Bitfield>
502 void setSubclassData(typename Bitfield::Type Value) {
503 Instruction::setSubclassData<Bitfield>(Value);
504 }
505
506 /// The synchronization scope ID of this fence instruction. Not quite enough
507 /// room in SubClassData for everything, so synchronization scope ID gets its
508 /// own field.
509 SyncScope::ID SSID;
510};
511
512//===----------------------------------------------------------------------===//
513// AtomicCmpXchgInst Class
514//===----------------------------------------------------------------------===//
515
516/// An instruction that atomically checks whether a
517/// specified value is in a memory location, and, if it is, stores a new value
518/// there. The value returned by this instruction is a pair containing the
519/// original value as first element, and an i1 indicating success (true) or
520/// failure (false) as second element.
521///
522class AtomicCmpXchgInst : public Instruction {
523 void Init(Value *Ptr, Value *Cmp, Value *NewVal, Align Align,
524 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
525 SyncScope::ID SSID);
526
527 template <unsigned Offset>
528 using AtomicOrderingBitfieldElement =
529 typename Bitfield::Element<AtomicOrdering, Offset, 3,
530 AtomicOrdering::LAST>;
531
532protected:
533 // Note: Instruction needs to be a friend here to call cloneImpl.
534 friend class Instruction;
535
536 AtomicCmpXchgInst *cloneImpl() const;
537
538public:
539 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment,
540 AtomicOrdering SuccessOrdering,
541 AtomicOrdering FailureOrdering, SyncScope::ID SSID,
542 Instruction *InsertBefore = nullptr);
543 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment,
544 AtomicOrdering SuccessOrdering,
545 AtomicOrdering FailureOrdering, SyncScope::ID SSID,
546 BasicBlock *InsertAtEnd);
547
548 // allocate space for exactly three operands
549 void *operator new(size_t s) {
550 return User::operator new(s, 3);
551 }
552
553 using VolatileField = BoolBitfieldElementT<0>;
554 using WeakField = BoolBitfieldElementT<VolatileField::NextBit>;
555 using SuccessOrderingField =
556 AtomicOrderingBitfieldElementT<WeakField::NextBit>;
557 using FailureOrderingField =
558 AtomicOrderingBitfieldElementT<SuccessOrderingField::NextBit>;
559 using AlignmentField =
560 AlignmentBitfieldElementT<FailureOrderingField::NextBit>;
561 static_assert(
562 Bitfield::areContiguous<VolatileField, WeakField, SuccessOrderingField,
563 FailureOrderingField, AlignmentField>(),
564 "Bitfields must be contiguous");
565
566 /// Return the alignment of the memory that is being allocated by the
567 /// instruction.
568 Align getAlign() const {
569 return Align(1ULL << getSubclassData<AlignmentField>());
570 }
571
572 void setAlignment(Align Align) {
573 setSubclassData<AlignmentField>(Log2(Align));
574 }
575
576 /// Return true if this is a cmpxchg from a volatile memory
577 /// location.
578 ///
579 bool isVolatile() const { return getSubclassData<VolatileField>(); }
580
581 /// Specify whether this is a volatile cmpxchg.
582 ///
583 void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
584
585 /// Return true if this cmpxchg may spuriously fail.
586 bool isWeak() const { return getSubclassData<WeakField>(); }
587
588 void setWeak(bool IsWeak) { setSubclassData<WeakField>(IsWeak); }
589
590 /// Transparently provide more efficient getOperand methods.
591 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
592
593 /// Returns the success ordering constraint of this cmpxchg instruction.
594 AtomicOrdering getSuccessOrdering() const {
595 return getSubclassData<SuccessOrderingField>();
596 }
597
598 /// Sets the success ordering constraint of this cmpxchg instruction.
599 void setSuccessOrdering(AtomicOrdering Ordering) {
600 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 601, __PRETTY_FUNCTION__))
601 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 601, __PRETTY_FUNCTION__))
;
602 setSubclassData<SuccessOrderingField>(Ordering);
603 }
604
605 /// Returns the failure ordering constraint of this cmpxchg instruction.
606 AtomicOrdering getFailureOrdering() const {
607 return getSubclassData<FailureOrderingField>();
608 }
609
610 /// Sets the failure ordering constraint of this cmpxchg instruction.
611 void setFailureOrdering(AtomicOrdering Ordering) {
612 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 613, __PRETTY_FUNCTION__))
613 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 613, __PRETTY_FUNCTION__))
;
614 setSubclassData<FailureOrderingField>(Ordering);
615 }
616
617 /// Returns the synchronization scope ID of this cmpxchg instruction.
618 SyncScope::ID getSyncScopeID() const {
619 return SSID;
620 }
621
622 /// Sets the synchronization scope ID of this cmpxchg instruction.
623 void setSyncScopeID(SyncScope::ID SSID) {
624 this->SSID = SSID;
625 }
626
627 Value *getPointerOperand() { return getOperand(0); }
628 const Value *getPointerOperand() const { return getOperand(0); }
629 static unsigned getPointerOperandIndex() { return 0U; }
630
631 Value *getCompareOperand() { return getOperand(1); }
632 const Value *getCompareOperand() const { return getOperand(1); }
633
634 Value *getNewValOperand() { return getOperand(2); }
635 const Value *getNewValOperand() const { return getOperand(2); }
636
637 /// Returns the address space of the pointer operand.
638 unsigned getPointerAddressSpace() const {
639 return getPointerOperand()->getType()->getPointerAddressSpace();
640 }
641
642 /// Returns the strongest permitted ordering on failure, given the
643 /// desired ordering on success.
644 ///
645 /// If the comparison in a cmpxchg operation fails, there is no atomic store
646 /// so release semantics cannot be provided. So this function drops explicit
647 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
648 /// operation would remain SequentiallyConsistent.
649 static AtomicOrdering
650 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
651 switch (SuccessOrdering) {
652 default:
653 llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 653)
;
654 case AtomicOrdering::Release:
655 case AtomicOrdering::Monotonic:
656 return AtomicOrdering::Monotonic;
657 case AtomicOrdering::AcquireRelease:
658 case AtomicOrdering::Acquire:
659 return AtomicOrdering::Acquire;
660 case AtomicOrdering::SequentiallyConsistent:
661 return AtomicOrdering::SequentiallyConsistent;
662 }
663 }
664
665 // Methods for support type inquiry through isa, cast, and dyn_cast:
666 static bool classof(const Instruction *I) {
667 return I->getOpcode() == Instruction::AtomicCmpXchg;
668 }
669 static bool classof(const Value *V) {
670 return isa<Instruction>(V) && classof(cast<Instruction>(V));
671 }
672
673private:
674 // Shadow Instruction::setInstructionSubclassData with a private forwarding
675 // method so that subclasses cannot accidentally use it.
676 template <typename Bitfield>
677 void setSubclassData(typename Bitfield::Type Value) {
678 Instruction::setSubclassData<Bitfield>(Value);
679 }
680
681 /// The synchronization scope ID of this cmpxchg instruction. Not quite
682 /// enough room in SubClassData for everything, so synchronization scope ID
683 /// gets its own field.
684 SyncScope::ID SSID;
685};
686
687template <>
688struct OperandTraits<AtomicCmpXchgInst> :
689 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
690};
691
692DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() {
return OperandTraits<AtomicCmpXchgInst>::op_begin(this
); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst::
op_begin() const { return OperandTraits<AtomicCmpXchgInst>
::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst
::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits
<AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst::
const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits
<AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst
*>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<AtomicCmpXchgInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 692, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<AtomicCmpXchgInst>::op_begin(const_cast
<AtomicCmpXchgInst*>(this))[i_nocapture].get()); } void
AtomicCmpXchgInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<AtomicCmpXchgInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 692, __PRETTY_FUNCTION__)); OperandTraits<AtomicCmpXchgInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
AtomicCmpXchgInst::getNumOperands() const { return OperandTraits
<AtomicCmpXchgInst>::operands(this); } template <int
Idx_nocapture> Use &AtomicCmpXchgInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &AtomicCmpXchgInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
693
694//===----------------------------------------------------------------------===//
695// AtomicRMWInst Class
696//===----------------------------------------------------------------------===//
697
698/// an instruction that atomically reads a memory location,
699/// combines it with another value, and then stores the result back. Returns
700/// the old value.
701///
702class AtomicRMWInst : public Instruction {
703protected:
704 // Note: Instruction needs to be a friend here to call cloneImpl.
705 friend class Instruction;
706
707 AtomicRMWInst *cloneImpl() const;
708
709public:
710 /// This enumeration lists the possible modifications atomicrmw can make. In
711 /// the descriptions, 'p' is the pointer to the instruction's memory location,
712 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
713 /// instruction. These instructions always return 'old'.
714 enum BinOp : unsigned {
715 /// *p = v
716 Xchg,
717 /// *p = old + v
718 Add,
719 /// *p = old - v
720 Sub,
721 /// *p = old & v
722 And,
723 /// *p = ~(old & v)
724 Nand,
725 /// *p = old | v
726 Or,
727 /// *p = old ^ v
728 Xor,
729 /// *p = old >signed v ? old : v
730 Max,
731 /// *p = old <signed v ? old : v
732 Min,
733 /// *p = old >unsigned v ? old : v
734 UMax,
735 /// *p = old <unsigned v ? old : v
736 UMin,
737
738 /// *p = old + v
739 FAdd,
740
741 /// *p = old - v
742 FSub,
743
744 FIRST_BINOP = Xchg,
745 LAST_BINOP = FSub,
746 BAD_BINOP
747 };
748
749private:
750 template <unsigned Offset>
751 using AtomicOrderingBitfieldElement =
752 typename Bitfield::Element<AtomicOrdering, Offset, 3,
753 AtomicOrdering::LAST>;
754
755 template <unsigned Offset>
756 using BinOpBitfieldElement =
757 typename Bitfield::Element<BinOp, Offset, 4, BinOp::LAST_BINOP>;
758
759public:
760 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment,
761 AtomicOrdering Ordering, SyncScope::ID SSID,
762 Instruction *InsertBefore = nullptr);
763 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment,
764 AtomicOrdering Ordering, SyncScope::ID SSID,
765 BasicBlock *InsertAtEnd);
766
767 // allocate space for exactly two operands
768 void *operator new(size_t s) {
769 return User::operator new(s, 2);
770 }
771
772 using VolatileField = BoolBitfieldElementT<0>;
773 using AtomicOrderingField =
774 AtomicOrderingBitfieldElementT<VolatileField::NextBit>;
775 using OperationField = BinOpBitfieldElement<AtomicOrderingField::NextBit>;
776 using AlignmentField = AlignmentBitfieldElementT<OperationField::NextBit>;
777 static_assert(Bitfield::areContiguous<VolatileField, AtomicOrderingField,
778 OperationField, AlignmentField>(),
779 "Bitfields must be contiguous");
780
781 BinOp getOperation() const { return getSubclassData<OperationField>(); }
782
783 static StringRef getOperationName(BinOp Op);
784
785 static bool isFPOperation(BinOp Op) {
786 switch (Op) {
787 case AtomicRMWInst::FAdd:
788 case AtomicRMWInst::FSub:
789 return true;
790 default:
791 return false;
792 }
793 }
794
795 void setOperation(BinOp Operation) {
796 setSubclassData<OperationField>(Operation);
797 }
798
799 /// Return the alignment of the memory that is being allocated by the
800 /// instruction.
801 Align getAlign() const {
802 return Align(1ULL << getSubclassData<AlignmentField>());
803 }
804
805 void setAlignment(Align Align) {
806 setSubclassData<AlignmentField>(Log2(Align));
807 }
808
809 /// Return true if this is a RMW on a volatile memory location.
810 ///
811 bool isVolatile() const { return getSubclassData<VolatileField>(); }
812
813 /// Specify whether this is a volatile RMW or not.
814 ///
815 void setVolatile(bool V) { setSubclassData<VolatileField>(V); }
816
817 /// Transparently provide more efficient getOperand methods.
818 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
819
820 /// Returns the ordering constraint of this rmw instruction.
821 AtomicOrdering getOrdering() const {
822 return getSubclassData<AtomicOrderingField>();
823 }
824
825 /// Sets the ordering constraint of this rmw instruction.
826 void setOrdering(AtomicOrdering Ordering) {
827 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 828, __PRETTY_FUNCTION__))
828 "atomicrmw instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 828, __PRETTY_FUNCTION__))
;
829 setSubclassData<AtomicOrderingField>(Ordering);
830 }
831
832 /// Returns the synchronization scope ID of this rmw instruction.
833 SyncScope::ID getSyncScopeID() const {
834 return SSID;
835 }
836
837 /// Sets the synchronization scope ID of this rmw instruction.
838 void setSyncScopeID(SyncScope::ID SSID) {
839 this->SSID = SSID;
840 }
841
842 Value *getPointerOperand() { return getOperand(0); }
843 const Value *getPointerOperand() const { return getOperand(0); }
844 static unsigned getPointerOperandIndex() { return 0U; }
845
846 Value *getValOperand() { return getOperand(1); }
847 const Value *getValOperand() const { return getOperand(1); }
848
849 /// Returns the address space of the pointer operand.
850 unsigned getPointerAddressSpace() const {
851 return getPointerOperand()->getType()->getPointerAddressSpace();
852 }
853
854 bool isFloatingPointOperation() const {
855 return isFPOperation(getOperation());
856 }
857
858 // Methods for support type inquiry through isa, cast, and dyn_cast:
859 static bool classof(const Instruction *I) {
860 return I->getOpcode() == Instruction::AtomicRMW;
861 }
862 static bool classof(const Value *V) {
863 return isa<Instruction>(V) && classof(cast<Instruction>(V));
864 }
865
866private:
867 void Init(BinOp Operation, Value *Ptr, Value *Val, Align Align,
868 AtomicOrdering Ordering, SyncScope::ID SSID);
869
870 // Shadow Instruction::setInstructionSubclassData with a private forwarding
871 // method so that subclasses cannot accidentally use it.
872 template <typename Bitfield>
873 void setSubclassData(typename Bitfield::Type Value) {
874 Instruction::setSubclassData<Bitfield>(Value);
875 }
876
877 /// The synchronization scope ID of this rmw instruction. Not quite enough
878 /// room in SubClassData for everything, so synchronization scope ID gets its
879 /// own field.
880 SyncScope::ID SSID;
881};
882
883template <>
884struct OperandTraits<AtomicRMWInst>
885 : public FixedNumOperandTraits<AtomicRMWInst,2> {
886};
887
888DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return
OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst
::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits
<AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*>
(this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end()
{ return OperandTraits<AtomicRMWInst>::op_end(this); }
AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const
{ return OperandTraits<AtomicRMWInst>::op_end(const_cast
<AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand
(unsigned i_nocapture) const { ((i_nocapture < OperandTraits
<AtomicRMWInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 888, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<AtomicRMWInst>::op_begin(const_cast<
AtomicRMWInst*>(this))[i_nocapture].get()); } void AtomicRMWInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<AtomicRMWInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 888, __PRETTY_FUNCTION__)); OperandTraits<AtomicRMWInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicRMWInst
::getNumOperands() const { return OperandTraits<AtomicRMWInst
>::operands(this); } template <int Idx_nocapture> Use
&AtomicRMWInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
AtomicRMWInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
889
890//===----------------------------------------------------------------------===//
891// GetElementPtrInst Class
892//===----------------------------------------------------------------------===//
893
894// checkGEPType - Simple wrapper function to give a better assertion failure
895// message on bad indexes for a gep instruction.
896//
897inline Type *checkGEPType(Type *Ty) {
898 assert(Ty && "Invalid GetElementPtrInst indices for type!")((Ty && "Invalid GetElementPtrInst indices for type!"
) ? static_cast<void> (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 898, __PRETTY_FUNCTION__))
;
899 return Ty;
900}
901
902/// an instruction for type-safe pointer arithmetic to
903/// access elements of arrays and structs
904///
905class GetElementPtrInst : public Instruction {
906 Type *SourceElementType;
907 Type *ResultElementType;
908
909 GetElementPtrInst(const GetElementPtrInst &GEPI);
910
911 /// Constructors - Create a getelementptr instruction with a base pointer an
912 /// list of indices. The first ctor can optionally insert before an existing
913 /// instruction, the second appends the new instruction to the specified
914 /// BasicBlock.
915 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
916 ArrayRef<Value *> IdxList, unsigned Values,
917 const Twine &NameStr, Instruction *InsertBefore);
918 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
919 ArrayRef<Value *> IdxList, unsigned Values,
920 const Twine &NameStr, BasicBlock *InsertAtEnd);
921
922 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
923
924protected:
925 // Note: Instruction needs to be a friend here to call cloneImpl.
926 friend class Instruction;
927
928 GetElementPtrInst *cloneImpl() const;
929
930public:
931 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
932 ArrayRef<Value *> IdxList,
933 const Twine &NameStr = "",
934 Instruction *InsertBefore = nullptr) {
935 unsigned Values = 1 + unsigned(IdxList.size());
936 if (!PointeeType)
937 PointeeType =
938 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
939 else
940 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 942, __PRETTY_FUNCTION__))
941 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 942, __PRETTY_FUNCTION__))
942 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 942, __PRETTY_FUNCTION__))
;
943 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
944 NameStr, InsertBefore);
945 }
946
947 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
948 ArrayRef<Value *> IdxList,
949 const Twine &NameStr,
950 BasicBlock *InsertAtEnd) {
951 unsigned Values = 1 + unsigned(IdxList.size());
952 if (!PointeeType)
953 PointeeType =
954 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
955 else
956 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 958, __PRETTY_FUNCTION__))
957 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 958, __PRETTY_FUNCTION__))
958 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 958, __PRETTY_FUNCTION__))
;
959 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
960 NameStr, InsertAtEnd);
961 }
962
963 /// Create an "inbounds" getelementptr. See the documentation for the
964 /// "inbounds" flag in LangRef.html for details.
965 static GetElementPtrInst *CreateInBounds(Value *Ptr,
966 ArrayRef<Value *> IdxList,
967 const Twine &NameStr = "",
968 Instruction *InsertBefore = nullptr){
969 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
970 }
971
972 static GetElementPtrInst *
973 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
974 const Twine &NameStr = "",
975 Instruction *InsertBefore = nullptr) {
976 GetElementPtrInst *GEP =
977 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
978 GEP->setIsInBounds(true);
979 return GEP;
980 }
981
982 static GetElementPtrInst *CreateInBounds(Value *Ptr,
983 ArrayRef<Value *> IdxList,
984 const Twine &NameStr,
985 BasicBlock *InsertAtEnd) {
986 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
987 }
988
989 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
990 ArrayRef<Value *> IdxList,
991 const Twine &NameStr,
992 BasicBlock *InsertAtEnd) {
993 GetElementPtrInst *GEP =
994 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
995 GEP->setIsInBounds(true);
996 return GEP;
997 }
998
999 /// Transparently provide more efficient getOperand methods.
1000 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1001
1002 Type *getSourceElementType() const { return SourceElementType; }
1003
1004 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
1005 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
1006
1007 Type *getResultElementType() const {
1008 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1009, __PRETTY_FUNCTION__))
1009 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1009, __PRETTY_FUNCTION__))
;
1010 return ResultElementType;
1011 }
1012
1013 /// Returns the address space of this instruction's pointer type.
1014 unsigned getAddressSpace() const {
1015 // Note that this is always the same as the pointer operand's address space
1016 // and that is cheaper to compute, so cheat here.
1017 return getPointerAddressSpace();
1018 }
1019
1020 /// Returns the result type of a getelementptr with the given source
1021 /// element type and indexes.
1022 ///
1023 /// Null is returned if the indices are invalid for the specified
1024 /// source element type.
1025 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1026 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1027 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1028
1029 /// Return the type of the element at the given index of an indexable
1030 /// type. This is equivalent to "getIndexedType(Agg, {Zero, Idx})".
1031 ///
1032 /// Returns null if the type can't be indexed, or the given index is not
1033 /// legal for the given type.
1034 static Type *getTypeAtIndex(Type *Ty, Value *Idx);
1035 static Type *getTypeAtIndex(Type *Ty, uint64_t Idx);
1036
1037 inline op_iterator idx_begin() { return op_begin()+1; }
1038 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1039 inline op_iterator idx_end() { return op_end(); }
1040 inline const_op_iterator idx_end() const { return op_end(); }
1041
1042 inline iterator_range<op_iterator> indices() {
1043 return make_range(idx_begin(), idx_end());
1044 }
1045
1046 inline iterator_range<const_op_iterator> indices() const {
1047 return make_range(idx_begin(), idx_end());
1048 }
1049
1050 Value *getPointerOperand() {
1051 return getOperand(0);
1052 }
1053 const Value *getPointerOperand() const {
1054 return getOperand(0);
1055 }
1056 static unsigned getPointerOperandIndex() {
1057 return 0U; // get index for modifying correct operand.
1058 }
1059
1060 /// Method to return the pointer operand as a
1061 /// PointerType.
1062 Type *getPointerOperandType() const {
1063 return getPointerOperand()->getType();
1064 }
1065
1066 /// Returns the address space of the pointer operand.
1067 unsigned getPointerAddressSpace() const {
1068 return getPointerOperandType()->getPointerAddressSpace();
1069 }
1070
1071 /// Returns the pointer type returned by the GEP
1072 /// instruction, which may be a vector of pointers.
1073 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1074 ArrayRef<Value *> IdxList) {
1075 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1076 Ptr->getType()->getPointerAddressSpace());
1077 // Vector GEP
1078 if (auto *PtrVTy = dyn_cast<VectorType>(Ptr->getType())) {
1079 ElementCount EltCount = PtrVTy->getElementCount();
1080 return VectorType::get(PtrTy, EltCount);
1081 }
1082 for (Value *Index : IdxList)
1083 if (auto *IndexVTy = dyn_cast<VectorType>(Index->getType())) {
1084 ElementCount EltCount = IndexVTy->getElementCount();
1085 return VectorType::get(PtrTy, EltCount);
1086 }
1087 // Scalar GEP
1088 return PtrTy;
1089 }
1090
1091 unsigned getNumIndices() const { // Note: always non-negative
1092 return getNumOperands() - 1;
1093 }
1094
1095 bool hasIndices() const {
1096 return getNumOperands() > 1;
1097 }
1098
1099 /// Return true if all of the indices of this GEP are
1100 /// zeros. If so, the result pointer and the first operand have the same
1101 /// value, just potentially different types.
1102 bool hasAllZeroIndices() const;
1103
1104 /// Return true if all of the indices of this GEP are
1105 /// constant integers. If so, the result pointer and the first operand have
1106 /// a constant offset between them.
1107 bool hasAllConstantIndices() const;
1108
1109 /// Set or clear the inbounds flag on this GEP instruction.
1110 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1111 void setIsInBounds(bool b = true);
1112
1113 /// Determine whether the GEP has the inbounds flag.
1114 bool isInBounds() const;
1115
1116 /// Accumulate the constant address offset of this GEP if possible.
1117 ///
1118 /// This routine accepts an APInt into which it will accumulate the constant
1119 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1120 /// all-constant, it returns false and the value of the offset APInt is
1121 /// undefined (it is *not* preserved!). The APInt passed into this routine
1122 /// must be at least as wide as the IntPtr type for the address space of
1123 /// the base GEP pointer.
1124 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1125
1126 // Methods for support type inquiry through isa, cast, and dyn_cast:
1127 static bool classof(const Instruction *I) {
1128 return (I->getOpcode() == Instruction::GetElementPtr);
1129 }
1130 static bool classof(const Value *V) {
1131 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1132 }
1133};
1134
1135template <>
1136struct OperandTraits<GetElementPtrInst> :
1137 public VariadicOperandTraits<GetElementPtrInst, 1> {
1138};
1139
1140GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1141 ArrayRef<Value *> IdxList, unsigned Values,
1142 const Twine &NameStr,
1143 Instruction *InsertBefore)
1144 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1145 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1146 Values, InsertBefore),
1147 SourceElementType(PointeeType),
1148 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1149 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1150, __PRETTY_FUNCTION__))
1150 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1150, __PRETTY_FUNCTION__))
;
1151 init(Ptr, IdxList, NameStr);
1152}
1153
1154GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1155 ArrayRef<Value *> IdxList, unsigned Values,
1156 const Twine &NameStr,
1157 BasicBlock *InsertAtEnd)
1158 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1159 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1160 Values, InsertAtEnd),
1161 SourceElementType(PointeeType),
1162 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1163 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1164, __PRETTY_FUNCTION__))
1164 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1164, __PRETTY_FUNCTION__))
;
1165 init(Ptr, IdxList, NameStr);
1166}
1167
1168DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() {
return OperandTraits<GetElementPtrInst>::op_begin(this
); } GetElementPtrInst::const_op_iterator GetElementPtrInst::
op_begin() const { return OperandTraits<GetElementPtrInst>
::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst
::op_iterator GetElementPtrInst::op_end() { return OperandTraits
<GetElementPtrInst>::op_end(this); } GetElementPtrInst::
const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits
<GetElementPtrInst>::op_end(const_cast<GetElementPtrInst
*>(this)); } Value *GetElementPtrInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<GetElementPtrInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1168, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<GetElementPtrInst>::op_begin(const_cast
<GetElementPtrInst*>(this))[i_nocapture].get()); } void
GetElementPtrInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<GetElementPtrInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1168, __PRETTY_FUNCTION__)); OperandTraits<GetElementPtrInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
GetElementPtrInst::getNumOperands() const { return OperandTraits
<GetElementPtrInst>::operands(this); } template <int
Idx_nocapture> Use &GetElementPtrInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &GetElementPtrInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
1169
1170//===----------------------------------------------------------------------===//
1171// ICmpInst Class
1172//===----------------------------------------------------------------------===//
1173
1174/// This instruction compares its operands according to the predicate given
1175/// to the constructor. It only operates on integers or pointers. The operands
1176/// must be identical types.
1177/// Represent an integer comparison operator.
1178class ICmpInst: public CmpInst {
1179 void AssertOK() {
1180 assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1181, __PRETTY_FUNCTION__))
1181 "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1181, __PRETTY_FUNCTION__))
;
1182 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1183, __PRETTY_FUNCTION__))
1183 "Both operands to ICmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1183, __PRETTY_FUNCTION__))
;
1184 // Check that the operands are the right type
1185 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1187, __PRETTY_FUNCTION__))
1186 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1187, __PRETTY_FUNCTION__))
1187 "Invalid operand types for ICmp instruction")(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1187, __PRETTY_FUNCTION__))
;
1188 }
1189
1190protected:
1191 // Note: Instruction needs to be a friend here to call cloneImpl.
1192 friend class Instruction;
1193
1194 /// Clone an identical ICmpInst
1195 ICmpInst *cloneImpl() const;
1196
1197public:
1198 /// Constructor with insert-before-instruction semantics.
1199 ICmpInst(
1200 Instruction *InsertBefore, ///< Where to insert
1201 Predicate pred, ///< The predicate to use for the comparison
1202 Value *LHS, ///< The left-hand-side of the expression
1203 Value *RHS, ///< The right-hand-side of the expression
1204 const Twine &NameStr = "" ///< Name of the instruction
1205 ) : CmpInst(makeCmpResultType(LHS->getType()),
1206 Instruction::ICmp, pred, LHS, RHS, NameStr,
1207 InsertBefore) {
1208#ifndef NDEBUG
1209 AssertOK();
1210#endif
1211 }
1212
1213 /// Constructor with insert-at-end semantics.
1214 ICmpInst(
1215 BasicBlock &InsertAtEnd, ///< Block to insert into.
1216 Predicate pred, ///< The predicate to use for the comparison
1217 Value *LHS, ///< The left-hand-side of the expression
1218 Value *RHS, ///< The right-hand-side of the expression
1219 const Twine &NameStr = "" ///< Name of the instruction
1220 ) : CmpInst(makeCmpResultType(LHS->getType()),
1221 Instruction::ICmp, pred, LHS, RHS, NameStr,
1222 &InsertAtEnd) {
1223#ifndef NDEBUG
1224 AssertOK();
1225#endif
1226 }
1227
1228 /// Constructor with no-insertion semantics
1229 ICmpInst(
1230 Predicate pred, ///< The predicate to use for the comparison
1231 Value *LHS, ///< The left-hand-side of the expression
1232 Value *RHS, ///< The right-hand-side of the expression
1233 const Twine &NameStr = "" ///< Name of the instruction
1234 ) : CmpInst(makeCmpResultType(LHS->getType()),
1235 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1236#ifndef NDEBUG
1237 AssertOK();
1238#endif
1239 }
1240
1241 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1242 /// @returns the predicate that would be the result if the operand were
1243 /// regarded as signed.
1244 /// Return the signed version of the predicate
1245 Predicate getSignedPredicate() const {
1246 return getSignedPredicate(getPredicate());
1247 }
1248
1249 /// This is a static version that you can use without an instruction.
1250 /// Return the signed version of the predicate.
1251 static Predicate getSignedPredicate(Predicate pred);
1252
1253 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1254 /// @returns the predicate that would be the result if the operand were
1255 /// regarded as unsigned.
1256 /// Return the unsigned version of the predicate
1257 Predicate getUnsignedPredicate() const {
1258 return getUnsignedPredicate(getPredicate());
1259 }
1260
1261 /// This is a static version that you can use without an instruction.
1262 /// Return the unsigned version of the predicate.
1263 static Predicate getUnsignedPredicate(Predicate pred);
1264
1265 /// Return true if this predicate is either EQ or NE. This also
1266 /// tests for commutativity.
1267 static bool isEquality(Predicate P) {
1268 return P == ICMP_EQ || P == ICMP_NE;
1269 }
1270
1271 /// Return true if this predicate is either EQ or NE. This also
1272 /// tests for commutativity.
1273 bool isEquality() const {
1274 return isEquality(getPredicate());
1275 }
1276
1277 /// @returns true if the predicate of this ICmpInst is commutative
1278 /// Determine if this relation is commutative.
1279 bool isCommutative() const { return isEquality(); }
1280
1281 /// Return true if the predicate is relational (not EQ or NE).
1282 ///
1283 bool isRelational() const {
1284 return !isEquality();
1285 }
1286
1287 /// Return true if the predicate is relational (not EQ or NE).
1288 ///
1289 static bool isRelational(Predicate P) {
1290 return !isEquality(P);
1291 }
1292
1293 /// Return true if the predicate is SGT or UGT.
1294 ///
1295 static bool isGT(Predicate P) {
1296 return P == ICMP_SGT || P == ICMP_UGT;
1297 }
1298
1299 /// Return true if the predicate is SLT or ULT.
1300 ///
1301 static bool isLT(Predicate P) {
1302 return P == ICMP_SLT || P == ICMP_ULT;
1303 }
1304
1305 /// Return true if the predicate is SGE or UGE.
1306 ///
1307 static bool isGE(Predicate P) {
1308 return P == ICMP_SGE || P == ICMP_UGE;
1309 }
1310
1311 /// Return true if the predicate is SLE or ULE.
1312 ///
1313 static bool isLE(Predicate P) {
1314 return P == ICMP_SLE || P == ICMP_ULE;
1315 }
1316
1317 /// Exchange the two operands to this instruction in such a way that it does
1318 /// not modify the semantics of the instruction. The predicate value may be
1319 /// changed to retain the same result if the predicate is order dependent
1320 /// (e.g. ult).
1321 /// Swap operands and adjust predicate.
1322 void swapOperands() {
1323 setPredicate(getSwappedPredicate());
1324 Op<0>().swap(Op<1>());
1325 }
1326
1327 // Methods for support type inquiry through isa, cast, and dyn_cast:
1328 static bool classof(const Instruction *I) {
1329 return I->getOpcode() == Instruction::ICmp;
1330 }
1331 static bool classof(const Value *V) {
1332 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1333 }
1334};
1335
1336//===----------------------------------------------------------------------===//
1337// FCmpInst Class
1338//===----------------------------------------------------------------------===//
1339
1340/// This instruction compares its operands according to the predicate given
1341/// to the constructor. It only operates on floating point values or packed
1342/// vectors of floating point values. The operands must be identical types.
1343/// Represents a floating point comparison operator.
1344class FCmpInst: public CmpInst {
1345 void AssertOK() {
1346 assert(isFPPredicate() && "Invalid FCmp predicate value")((isFPPredicate() && "Invalid FCmp predicate value") ?
static_cast<void> (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1346, __PRETTY_FUNCTION__))
;
1347 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1348, __PRETTY_FUNCTION__))
1348 "Both operands to FCmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1348, __PRETTY_FUNCTION__))
;
1349 // Check that the operands are the right type
1350 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1351, __PRETTY_FUNCTION__))
1351 "Invalid operand types for FCmp instruction")((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1351, __PRETTY_FUNCTION__))
;
1352 }
1353
1354protected:
1355 // Note: Instruction needs to be a friend here to call cloneImpl.
1356 friend class Instruction;
1357
1358 /// Clone an identical FCmpInst
1359 FCmpInst *cloneImpl() const;
1360
1361public:
1362 /// Constructor with insert-before-instruction semantics.
1363 FCmpInst(
1364 Instruction *InsertBefore, ///< Where to insert
1365 Predicate pred, ///< The predicate to use for the comparison
1366 Value *LHS, ///< The left-hand-side of the expression
1367 Value *RHS, ///< The right-hand-side of the expression
1368 const Twine &NameStr = "" ///< Name of the instruction
1369 ) : CmpInst(makeCmpResultType(LHS->getType()),
1370 Instruction::FCmp, pred, LHS, RHS, NameStr,
1371 InsertBefore) {
1372 AssertOK();
1373 }
1374
1375 /// Constructor with insert-at-end semantics.
1376 FCmpInst(
1377 BasicBlock &InsertAtEnd, ///< Block to insert into.
1378 Predicate pred, ///< The predicate to use for the comparison
1379 Value *LHS, ///< The left-hand-side of the expression
1380 Value *RHS, ///< The right-hand-side of the expression
1381 const Twine &NameStr = "" ///< Name of the instruction
1382 ) : CmpInst(makeCmpResultType(LHS->getType()),
1383 Instruction::FCmp, pred, LHS, RHS, NameStr,
1384 &InsertAtEnd) {
1385 AssertOK();
1386 }
1387
1388 /// Constructor with no-insertion semantics
1389 FCmpInst(
1390 Predicate Pred, ///< The predicate to use for the comparison
1391 Value *LHS, ///< The left-hand-side of the expression
1392 Value *RHS, ///< The right-hand-side of the expression
1393 const Twine &NameStr = "", ///< Name of the instruction
1394 Instruction *FlagsSource = nullptr
1395 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1396 RHS, NameStr, nullptr, FlagsSource) {
1397 AssertOK();
1398 }
1399
1400 /// @returns true if the predicate of this instruction is EQ or NE.
1401 /// Determine if this is an equality predicate.
1402 static bool isEquality(Predicate Pred) {
1403 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1404 Pred == FCMP_UNE;
1405 }
1406
1407 /// @returns true if the predicate of this instruction is EQ or NE.
1408 /// Determine if this is an equality predicate.
1409 bool isEquality() const { return isEquality(getPredicate()); }
1410
1411 /// @returns true if the predicate of this instruction is commutative.
1412 /// Determine if this is a commutative predicate.
1413 bool isCommutative() const {
1414 return isEquality() ||
1415 getPredicate() == FCMP_FALSE ||
1416 getPredicate() == FCMP_TRUE ||
1417 getPredicate() == FCMP_ORD ||
1418 getPredicate() == FCMP_UNO;
1419 }
1420
1421 /// @returns true if the predicate is relational (not EQ or NE).
1422 /// Determine if this a relational predicate.
1423 bool isRelational() const { return !isEquality(); }
1424
1425 /// Exchange the two operands to this instruction in such a way that it does
1426 /// not modify the semantics of the instruction. The predicate value may be
1427 /// changed to retain the same result if the predicate is order dependent
1428 /// (e.g. ult).
1429 /// Swap operands and adjust predicate.
1430 void swapOperands() {
1431 setPredicate(getSwappedPredicate());
1432 Op<0>().swap(Op<1>());
1433 }
1434
1435 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1436 static bool classof(const Instruction *I) {
1437 return I->getOpcode() == Instruction::FCmp;
1438 }
1439 static bool classof(const Value *V) {
1440 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1441 }
1442};
1443
1444//===----------------------------------------------------------------------===//
1445/// This class represents a function call, abstracting a target
1446/// machine's calling convention. This class uses low bit of the SubClassData
1447/// field to indicate whether or not this is a tail call. The rest of the bits
1448/// hold the calling convention of the call.
1449///
1450class CallInst : public CallBase {
1451 CallInst(const CallInst &CI);
1452
1453 /// Construct a CallInst given a range of arguments.
1454 /// Construct a CallInst from a range of arguments
1455 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1456 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1457 Instruction *InsertBefore);
1458
1459 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1460 const Twine &NameStr, Instruction *InsertBefore)
1461 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1462
1463 /// Construct a CallInst given a range of arguments.
1464 /// Construct a CallInst from a range of arguments
1465 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1466 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1467 BasicBlock *InsertAtEnd);
1468
1469 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1470 Instruction *InsertBefore);
1471
1472 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1473 BasicBlock *InsertAtEnd);
1474
1475 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1476 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1477 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1478
1479 /// Compute the number of operands to allocate.
1480 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1481 // We need one operand for the called function, plus the input operand
1482 // counts provided.
1483 return 1 + NumArgs + NumBundleInputs;
1484 }
1485
1486protected:
1487 // Note: Instruction needs to be a friend here to call cloneImpl.
1488 friend class Instruction;
1489
1490 CallInst *cloneImpl() const;
1491
1492public:
1493 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1494 Instruction *InsertBefore = nullptr) {
1495 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1496 }
1497
1498 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1499 const Twine &NameStr,
1500 Instruction *InsertBefore = nullptr) {
1501 return new (ComputeNumOperands(Args.size()))
1502 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1503 }
1504
1505 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1506 ArrayRef<OperandBundleDef> Bundles = None,
1507 const Twine &NameStr = "",
1508 Instruction *InsertBefore = nullptr) {
1509 const int NumOperands =
1510 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1511 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1512
1513 return new (NumOperands, DescriptorBytes)
1514 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1515 }
1516
1517 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1518 BasicBlock *InsertAtEnd) {
1519 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1520 }
1521
1522 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1523 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1524 return new (ComputeNumOperands(Args.size()))
1525 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1526 }
1527
1528 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1529 ArrayRef<OperandBundleDef> Bundles,
1530 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1531 const int NumOperands =
1532 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1533 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1534
1535 return new (NumOperands, DescriptorBytes)
1536 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1537 }
1538
1539 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1540 Instruction *InsertBefore = nullptr) {
1541 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1542 InsertBefore);
1543 }
1544
1545 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1546 ArrayRef<OperandBundleDef> Bundles = None,
1547 const Twine &NameStr = "",
1548 Instruction *InsertBefore = nullptr) {
1549 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1550 NameStr, InsertBefore);
1551 }
1552
1553 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1554 const Twine &NameStr,
1555 Instruction *InsertBefore = nullptr) {
1556 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1557 InsertBefore);
1558 }
1559
1560 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1561 BasicBlock *InsertAtEnd) {
1562 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1563 InsertAtEnd);
1564 }
1565
1566 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1567 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1568 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1569 InsertAtEnd);
1570 }
1571
1572 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1573 ArrayRef<OperandBundleDef> Bundles,
1574 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1575 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1576 NameStr, InsertAtEnd);
1577 }
1578
1579 /// Create a clone of \p CI with a different set of operand bundles and
1580 /// insert it before \p InsertPt.
1581 ///
1582 /// The returned call instruction is identical \p CI in every way except that
1583 /// the operand bundles for the new instruction are set to the operand bundles
1584 /// in \p Bundles.
1585 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1586 Instruction *InsertPt = nullptr);
1587
1588 /// Create a clone of \p CI with a different set of operand bundles and
1589 /// insert it before \p InsertPt.
1590 ///
1591 /// The returned call instruction is identical \p CI in every way except that
1592 /// the operand bundle for the new instruction is set to the operand bundle
1593 /// in \p Bundle.
1594 static CallInst *CreateWithReplacedBundle(CallInst *CI,
1595 OperandBundleDef Bundle,
1596 Instruction *InsertPt = nullptr);
1597
1598 /// Generate the IR for a call to malloc:
1599 /// 1. Compute the malloc call's argument as the specified type's size,
1600 /// possibly multiplied by the array size if the array size is not
1601 /// constant 1.
1602 /// 2. Call malloc with that argument.
1603 /// 3. Bitcast the result of the malloc call to the specified type.
1604 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1605 Type *AllocTy, Value *AllocSize,
1606 Value *ArraySize = nullptr,
1607 Function *MallocF = nullptr,
1608 const Twine &Name = "");
1609 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1610 Type *AllocTy, Value *AllocSize,
1611 Value *ArraySize = nullptr,
1612 Function *MallocF = nullptr,
1613 const Twine &Name = "");
1614 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1615 Type *AllocTy, Value *AllocSize,
1616 Value *ArraySize = nullptr,
1617 ArrayRef<OperandBundleDef> Bundles = None,
1618 Function *MallocF = nullptr,
1619 const Twine &Name = "");
1620 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1621 Type *AllocTy, Value *AllocSize,
1622 Value *ArraySize = nullptr,
1623 ArrayRef<OperandBundleDef> Bundles = None,
1624 Function *MallocF = nullptr,
1625 const Twine &Name = "");
1626 /// Generate the IR for a call to the builtin free function.
1627 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1628 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1629 static Instruction *CreateFree(Value *Source,
1630 ArrayRef<OperandBundleDef> Bundles,
1631 Instruction *InsertBefore);
1632 static Instruction *CreateFree(Value *Source,
1633 ArrayRef<OperandBundleDef> Bundles,
1634 BasicBlock *InsertAtEnd);
1635
1636 // Note that 'musttail' implies 'tail'.
1637 enum TailCallKind : unsigned {
1638 TCK_None = 0,
1639 TCK_Tail = 1,
1640 TCK_MustTail = 2,
1641 TCK_NoTail = 3,
1642 TCK_LAST = TCK_NoTail
1643 };
1644
1645 using TailCallKindField = Bitfield::Element<TailCallKind, 0, 2, TCK_LAST>;
1646 static_assert(
1647 Bitfield::areContiguous<TailCallKindField, CallBase::CallingConvField>(),
1648 "Bitfields must be contiguous");
1649
1650 TailCallKind getTailCallKind() const {
1651 return getSubclassData<TailCallKindField>();
1652 }
1653
1654 bool isTailCall() const {
1655 TailCallKind Kind = getTailCallKind();
1656 return Kind == TCK_Tail || Kind == TCK_MustTail;
1657 }
1658
1659 bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; }
1660
1661 bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; }
1662
1663 void setTailCallKind(TailCallKind TCK) {
1664 setSubclassData<TailCallKindField>(TCK);
1665 }
1666
1667 void setTailCall(bool IsTc = true) {
1668 setTailCallKind(IsTc ? TCK_Tail : TCK_None);
1669 }
1670
1671 /// Return true if the call can return twice
1672 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1673 void setCanReturnTwice() {
1674 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1675 }
1676
1677 // Methods for support type inquiry through isa, cast, and dyn_cast:
1678 static bool classof(const Instruction *I) {
1679 return I->getOpcode() == Instruction::Call;
1680 }
1681 static bool classof(const Value *V) {
1682 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1683 }
1684
1685 /// Updates profile metadata by scaling it by \p S / \p T.
1686 void updateProfWeight(uint64_t S, uint64_t T);
1687
1688private:
1689 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1690 // method so that subclasses cannot accidentally use it.
1691 template <typename Bitfield>
1692 void setSubclassData(typename Bitfield::Type Value) {
1693 Instruction::setSubclassData<Bitfield>(Value);
1694 }
1695};
1696
1697CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1698 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1699 BasicBlock *InsertAtEnd)
1700 : CallBase(Ty->getReturnType(), Instruction::Call,
1701 OperandTraits<CallBase>::op_end(this) -
1702 (Args.size() + CountBundleInputs(Bundles) + 1),
1703 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1704 InsertAtEnd) {
1705 init(Ty, Func, Args, Bundles, NameStr);
1706}
1707
1708CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1709 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1710 Instruction *InsertBefore)
1711 : CallBase(Ty->getReturnType(), Instruction::Call,
1712 OperandTraits<CallBase>::op_end(this) -
1713 (Args.size() + CountBundleInputs(Bundles) + 1),
1714 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1715 InsertBefore) {
1716 init(Ty, Func, Args, Bundles, NameStr);
1717}
1718
1719//===----------------------------------------------------------------------===//
1720// SelectInst Class
1721//===----------------------------------------------------------------------===//
1722
1723/// This class represents the LLVM 'select' instruction.
1724///
1725class SelectInst : public Instruction {
1726 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1727 Instruction *InsertBefore)
1728 : Instruction(S1->getType(), Instruction::Select,
1729 &Op<0>(), 3, InsertBefore) {
1730 init(C, S1, S2);
1731 setName(NameStr);
1732 }
1733
1734 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1735 BasicBlock *InsertAtEnd)
1736 : Instruction(S1->getType(), Instruction::Select,
1737 &Op<0>(), 3, InsertAtEnd) {
1738 init(C, S1, S2);
1739 setName(NameStr);
1740 }
1741
1742 void init(Value *C, Value *S1, Value *S2) {
1743 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")((!areInvalidOperands(C, S1, S2) && "Invalid operands for select"
) ? static_cast<void> (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1743, __PRETTY_FUNCTION__))
;
1744 Op<0>() = C;
1745 Op<1>() = S1;
1746 Op<2>() = S2;
1747 }
1748
1749protected:
1750 // Note: Instruction needs to be a friend here to call cloneImpl.
1751 friend class Instruction;
1752
1753 SelectInst *cloneImpl() const;
1754
1755public:
1756 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1757 const Twine &NameStr = "",
1758 Instruction *InsertBefore = nullptr,
1759 Instruction *MDFrom = nullptr) {
1760 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1761 if (MDFrom)
1762 Sel->copyMetadata(*MDFrom);
1763 return Sel;
1764 }
1765
1766 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1767 const Twine &NameStr,
1768 BasicBlock *InsertAtEnd) {
1769 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1770 }
1771
1772 const Value *getCondition() const { return Op<0>(); }
1773 const Value *getTrueValue() const { return Op<1>(); }
1774 const Value *getFalseValue() const { return Op<2>(); }
1775 Value *getCondition() { return Op<0>(); }
1776 Value *getTrueValue() { return Op<1>(); }
1777 Value *getFalseValue() { return Op<2>(); }
1778
1779 void setCondition(Value *V) { Op<0>() = V; }
1780 void setTrueValue(Value *V) { Op<1>() = V; }
1781 void setFalseValue(Value *V) { Op<2>() = V; }
1782
1783 /// Swap the true and false values of the select instruction.
1784 /// This doesn't swap prof metadata.
1785 void swapValues() { Op<1>().swap(Op<2>()); }
1786
1787 /// Return a string if the specified operands are invalid
1788 /// for a select operation, otherwise return null.
1789 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1790
1791 /// Transparently provide more efficient getOperand methods.
1792 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1793
1794 OtherOps getOpcode() const {
1795 return static_cast<OtherOps>(Instruction::getOpcode());
1796 }
1797
1798 // Methods for support type inquiry through isa, cast, and dyn_cast:
1799 static bool classof(const Instruction *I) {
1800 return I->getOpcode() == Instruction::Select;
1801 }
1802 static bool classof(const Value *V) {
1803 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1804 }
1805};
1806
1807template <>
1808struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1809};
1810
1811DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits
<SelectInst>::op_begin(this); } SelectInst::const_op_iterator
SelectInst::op_begin() const { return OperandTraits<SelectInst
>::op_begin(const_cast<SelectInst*>(this)); } SelectInst
::op_iterator SelectInst::op_end() { return OperandTraits<
SelectInst>::op_end(this); } SelectInst::const_op_iterator
SelectInst::op_end() const { return OperandTraits<SelectInst
>::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1811, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<SelectInst>::op_begin(const_cast<SelectInst
*>(this))[i_nocapture].get()); } void SelectInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1811, __PRETTY_FUNCTION__)); OperandTraits<SelectInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SelectInst
::getNumOperands() const { return OperandTraits<SelectInst
>::operands(this); } template <int Idx_nocapture> Use
&SelectInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
SelectInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
1812
1813//===----------------------------------------------------------------------===//
1814// VAArgInst Class
1815//===----------------------------------------------------------------------===//
1816
1817/// This class represents the va_arg llvm instruction, which returns
1818/// an argument of the specified type given a va_list and increments that list
1819///
1820class VAArgInst : public UnaryInstruction {
1821protected:
1822 // Note: Instruction needs to be a friend here to call cloneImpl.
1823 friend class Instruction;
1824
1825 VAArgInst *cloneImpl() const;
1826
1827public:
1828 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1829 Instruction *InsertBefore = nullptr)
1830 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1831 setName(NameStr);
1832 }
1833
1834 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1835 BasicBlock *InsertAtEnd)
1836 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1837 setName(NameStr);
1838 }
1839
1840 Value *getPointerOperand() { return getOperand(0); }
1841 const Value *getPointerOperand() const { return getOperand(0); }
1842 static unsigned getPointerOperandIndex() { return 0U; }
1843
1844 // Methods for support type inquiry through isa, cast, and dyn_cast:
1845 static bool classof(const Instruction *I) {
1846 return I->getOpcode() == VAArg;
1847 }
1848 static bool classof(const Value *V) {
1849 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1850 }
1851};
1852
1853//===----------------------------------------------------------------------===//
1854// ExtractElementInst Class
1855//===----------------------------------------------------------------------===//
1856
1857/// This instruction extracts a single (scalar)
1858/// element from a VectorType value
1859///
1860class ExtractElementInst : public Instruction {
1861 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1862 Instruction *InsertBefore = nullptr);
1863 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1864 BasicBlock *InsertAtEnd);
1865
1866protected:
1867 // Note: Instruction needs to be a friend here to call cloneImpl.
1868 friend class Instruction;
1869
1870 ExtractElementInst *cloneImpl() const;
1871
1872public:
1873 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1874 const Twine &NameStr = "",
1875 Instruction *InsertBefore = nullptr) {
1876 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1877 }
1878
1879 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1880 const Twine &NameStr,
1881 BasicBlock *InsertAtEnd) {
1882 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1883 }
1884
1885 /// Return true if an extractelement instruction can be
1886 /// formed with the specified operands.
1887 static bool isValidOperands(const Value *Vec, const Value *Idx);
1888
1889 Value *getVectorOperand() { return Op<0>(); }
1890 Value *getIndexOperand() { return Op<1>(); }
1891 const Value *getVectorOperand() const { return Op<0>(); }
1892 const Value *getIndexOperand() const { return Op<1>(); }
1893
1894 VectorType *getVectorOperandType() const {
1895 return cast<VectorType>(getVectorOperand()->getType());
1896 }
1897
1898 /// Transparently provide more efficient getOperand methods.
1899 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1900
1901 // Methods for support type inquiry through isa, cast, and dyn_cast:
1902 static bool classof(const Instruction *I) {
1903 return I->getOpcode() == Instruction::ExtractElement;
1904 }
1905 static bool classof(const Value *V) {
1906 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1907 }
1908};
1909
1910template <>
1911struct OperandTraits<ExtractElementInst> :
1912 public FixedNumOperandTraits<ExtractElementInst, 2> {
1913};
1914
1915DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin(
) { return OperandTraits<ExtractElementInst>::op_begin(
this); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_begin() const { return OperandTraits<ExtractElementInst
>::op_begin(const_cast<ExtractElementInst*>(this)); }
ExtractElementInst::op_iterator ExtractElementInst::op_end()
{ return OperandTraits<ExtractElementInst>::op_end(this
); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_end() const { return OperandTraits<ExtractElementInst
>::op_end(const_cast<ExtractElementInst*>(this)); } Value
*ExtractElementInst::getOperand(unsigned i_nocapture) const {
((i_nocapture < OperandTraits<ExtractElementInst>::
operands(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1915, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ExtractElementInst>::op_begin(const_cast
<ExtractElementInst*>(this))[i_nocapture].get()); } void
ExtractElementInst::setOperand(unsigned i_nocapture, Value *
Val_nocapture) { ((i_nocapture < OperandTraits<ExtractElementInst
>::operands(this) && "setOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1915, __PRETTY_FUNCTION__)); OperandTraits<ExtractElementInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
ExtractElementInst::getNumOperands() const { return OperandTraits
<ExtractElementInst>::operands(this); } template <int
Idx_nocapture> Use &ExtractElementInst::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &ExtractElementInst::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
1916
1917//===----------------------------------------------------------------------===//
1918// InsertElementInst Class
1919//===----------------------------------------------------------------------===//
1920
1921/// This instruction inserts a single (scalar)
1922/// element into a VectorType value
1923///
1924class InsertElementInst : public Instruction {
1925 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1926 const Twine &NameStr = "",
1927 Instruction *InsertBefore = nullptr);
1928 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1929 BasicBlock *InsertAtEnd);
1930
1931protected:
1932 // Note: Instruction needs to be a friend here to call cloneImpl.
1933 friend class Instruction;
1934
1935 InsertElementInst *cloneImpl() const;
1936
1937public:
1938 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1939 const Twine &NameStr = "",
1940 Instruction *InsertBefore = nullptr) {
1941 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1942 }
1943
1944 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1945 const Twine &NameStr,
1946 BasicBlock *InsertAtEnd) {
1947 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1948 }
1949
1950 /// Return true if an insertelement instruction can be
1951 /// formed with the specified operands.
1952 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1953 const Value *Idx);
1954
1955 /// Overload to return most specific vector type.
1956 ///
1957 VectorType *getType() const {
1958 return cast<VectorType>(Instruction::getType());
1959 }
1960
1961 /// Transparently provide more efficient getOperand methods.
1962 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1963
1964 // Methods for support type inquiry through isa, cast, and dyn_cast:
1965 static bool classof(const Instruction *I) {
1966 return I->getOpcode() == Instruction::InsertElement;
1967 }
1968 static bool classof(const Value *V) {
1969 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1970 }
1971};
1972
1973template <>
1974struct OperandTraits<InsertElementInst> :
1975 public FixedNumOperandTraits<InsertElementInst, 3> {
1976};
1977
1978DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() {
return OperandTraits<InsertElementInst>::op_begin(this
); } InsertElementInst::const_op_iterator InsertElementInst::
op_begin() const { return OperandTraits<InsertElementInst>
::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst
::op_iterator InsertElementInst::op_end() { return OperandTraits
<InsertElementInst>::op_end(this); } InsertElementInst::
const_op_iterator InsertElementInst::op_end() const { return OperandTraits
<InsertElementInst>::op_end(const_cast<InsertElementInst
*>(this)); } Value *InsertElementInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<InsertElementInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1978, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<InsertElementInst>::op_begin(const_cast
<InsertElementInst*>(this))[i_nocapture].get()); } void
InsertElementInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<InsertElementInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 1978, __PRETTY_FUNCTION__)); OperandTraits<InsertElementInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
InsertElementInst::getNumOperands() const { return OperandTraits
<InsertElementInst>::operands(this); } template <int
Idx_nocapture> Use &InsertElementInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &InsertElementInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
1979
1980//===----------------------------------------------------------------------===//
1981// ShuffleVectorInst Class
1982//===----------------------------------------------------------------------===//
1983
1984constexpr int UndefMaskElem = -1;
1985
1986/// This instruction constructs a fixed permutation of two
1987/// input vectors.
1988///
1989/// For each element of the result vector, the shuffle mask selects an element
1990/// from one of the input vectors to copy to the result. Non-negative elements
1991/// in the mask represent an index into the concatenated pair of input vectors.
1992/// UndefMaskElem (-1) specifies that the result element is undefined.
1993///
1994/// For scalable vectors, all the elements of the mask must be 0 or -1. This
1995/// requirement may be relaxed in the future.
1996class ShuffleVectorInst : public Instruction {
1997 SmallVector<int, 4> ShuffleMask;
1998 Constant *ShuffleMaskForBitcode;
1999
2000protected:
2001 // Note: Instruction needs to be a friend here to call cloneImpl.
2002 friend class Instruction;
2003
2004 ShuffleVectorInst *cloneImpl() const;
2005
2006public:
2007 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2008 const Twine &NameStr = "",
2009 Instruction *InsertBefor = nullptr);
2010 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
2011 const Twine &NameStr, BasicBlock *InsertAtEnd);
2012 ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
2013 const Twine &NameStr = "",
2014 Instruction *InsertBefor = nullptr);
2015 ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
2016 const Twine &NameStr, BasicBlock *InsertAtEnd);
2017
2018 void *operator new(size_t s) { return User::operator new(s, 2); }
2019
2020 /// Swap the operands and adjust the mask to preserve the semantics
2021 /// of the instruction.
2022 void commute();
2023
2024 /// Return true if a shufflevector instruction can be
2025 /// formed with the specified operands.
2026 static bool isValidOperands(const Value *V1, const Value *V2,
2027 const Value *Mask);
2028 static bool isValidOperands(const Value *V1, const Value *V2,
2029 ArrayRef<int> Mask);
2030
2031 /// Overload to return most specific vector type.
2032 ///
2033 VectorType *getType() const {
2034 return cast<VectorType>(Instruction::getType());
2035 }
2036
2037 /// Transparently provide more efficient getOperand methods.
2038 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2039
2040 /// Return the shuffle mask value of this instruction for the given element
2041 /// index. Return UndefMaskElem if the element is undef.
2042 int getMaskValue(unsigned Elt) const { return ShuffleMask[Elt]; }
2043
2044 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2045 /// elements of the mask are returned as UndefMaskElem.
2046 static void getShuffleMask(const Constant *Mask,
2047 SmallVectorImpl<int> &Result);
2048
2049 /// Return the mask for this instruction as a vector of integers. Undefined
2050 /// elements of the mask are returned as UndefMaskElem.
2051 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2052 Result.assign(ShuffleMask.begin(), ShuffleMask.end());
2053 }
2054
2055 /// Return the mask for this instruction, for use in bitcode.
2056 ///
2057 /// TODO: This is temporary until we decide a new bitcode encoding for
2058 /// shufflevector.
2059 Constant *getShuffleMaskForBitcode() const { return ShuffleMaskForBitcode; }
2060
2061 static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask,
2062 Type *ResultTy);
2063
2064 void setShuffleMask(ArrayRef<int> Mask);
2065
2066 ArrayRef<int> getShuffleMask() const { return ShuffleMask; }
2067
2068 /// Return true if this shuffle returns a vector with a different number of
2069 /// elements than its source vectors.
2070 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2071 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2072 bool changesLength() const {
2073 unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType())
2074 ->getElementCount()
2075 .getKnownMinValue();
2076 unsigned NumMaskElts = ShuffleMask.size();
2077 return NumSourceElts != NumMaskElts;
2078 }
2079
2080 /// Return true if this shuffle returns a vector with a greater number of
2081 /// elements than its source vectors.
2082 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2083 bool increasesLength() const {
2084 unsigned NumSourceElts =
2085 cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2086 unsigned NumMaskElts = ShuffleMask.size();
2087 return NumSourceElts < NumMaskElts;
2088 }
2089
2090 /// Return true if this shuffle mask chooses elements from exactly one source
2091 /// vector.
2092 /// Example: <7,5,undef,7>
2093 /// This assumes that vector operands are the same length as the mask.
2094 static bool isSingleSourceMask(ArrayRef<int> Mask);
2095 static bool isSingleSourceMask(const Constant *Mask) {
2096 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2096, __PRETTY_FUNCTION__))
;
2097 SmallVector<int, 16> MaskAsInts;
2098 getShuffleMask(Mask, MaskAsInts);
2099 return isSingleSourceMask(MaskAsInts);
2100 }
2101
2102 /// Return true if this shuffle chooses elements from exactly one source
2103 /// vector without changing the length of that vector.
2104 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2105 /// TODO: Optionally allow length-changing shuffles.
2106 bool isSingleSource() const {
2107 return !changesLength() && isSingleSourceMask(ShuffleMask);
2108 }
2109
2110 /// Return true if this shuffle mask chooses elements from exactly one source
2111 /// vector without lane crossings. A shuffle using this mask is not
2112 /// necessarily a no-op because it may change the number of elements from its
2113 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2114 /// Example: <undef,undef,2,3>
2115 static bool isIdentityMask(ArrayRef<int> Mask);
2116 static bool isIdentityMask(const Constant *Mask) {
2117 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2117, __PRETTY_FUNCTION__))
;
2118 SmallVector<int, 16> MaskAsInts;
2119 getShuffleMask(Mask, MaskAsInts);
2120 return isIdentityMask(MaskAsInts);
2121 }
2122
2123 /// Return true if this shuffle chooses elements from exactly one source
2124 /// vector without lane crossings and does not change the number of elements
2125 /// from its input vectors.
2126 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2127 bool isIdentity() const {
2128 return !changesLength() && isIdentityMask(ShuffleMask);
2129 }
2130
2131 /// Return true if this shuffle lengthens exactly one source vector with
2132 /// undefs in the high elements.
2133 bool isIdentityWithPadding() const;
2134
2135 /// Return true if this shuffle extracts the first N elements of exactly one
2136 /// source vector.
2137 bool isIdentityWithExtract() const;
2138
2139 /// Return true if this shuffle concatenates its 2 source vectors. This
2140 /// returns false if either input is undefined. In that case, the shuffle is
2141 /// is better classified as an identity with padding operation.
2142 bool isConcat() const;
2143
2144 /// Return true if this shuffle mask chooses elements from its source vectors
2145 /// without lane crossings. A shuffle using this mask would be
2146 /// equivalent to a vector select with a constant condition operand.
2147 /// Example: <4,1,6,undef>
2148 /// This returns false if the mask does not choose from both input vectors.
2149 /// In that case, the shuffle is better classified as an identity shuffle.
2150 /// This assumes that vector operands are the same length as the mask
2151 /// (a length-changing shuffle can never be equivalent to a vector select).
2152 static bool isSelectMask(ArrayRef<int> Mask);
2153 static bool isSelectMask(const Constant *Mask) {
2154 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2154, __PRETTY_FUNCTION__))
;
2155 SmallVector<int, 16> MaskAsInts;
2156 getShuffleMask(Mask, MaskAsInts);
2157 return isSelectMask(MaskAsInts);
2158 }
2159
2160 /// Return true if this shuffle chooses elements from its source vectors
2161 /// without lane crossings and all operands have the same number of elements.
2162 /// In other words, this shuffle is equivalent to a vector select with a
2163 /// constant condition operand.
2164 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2165 /// This returns false if the mask does not choose from both input vectors.
2166 /// In that case, the shuffle is better classified as an identity shuffle.
2167 /// TODO: Optionally allow length-changing shuffles.
2168 bool isSelect() const {
2169 return !changesLength() && isSelectMask(ShuffleMask);
2170 }
2171
2172 /// Return true if this shuffle mask swaps the order of elements from exactly
2173 /// one source vector.
2174 /// Example: <7,6,undef,4>
2175 /// This assumes that vector operands are the same length as the mask.
2176 static bool isReverseMask(ArrayRef<int> Mask);
2177 static bool isReverseMask(const Constant *Mask) {
2178 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2178, __PRETTY_FUNCTION__))
;
2179 SmallVector<int, 16> MaskAsInts;
2180 getShuffleMask(Mask, MaskAsInts);
2181 return isReverseMask(MaskAsInts);
2182 }
2183
2184 /// Return true if this shuffle swaps the order of elements from exactly
2185 /// one source vector.
2186 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2187 /// TODO: Optionally allow length-changing shuffles.
2188 bool isReverse() const {
2189 return !changesLength() && isReverseMask(ShuffleMask);
2190 }
2191
2192 /// Return true if this shuffle mask chooses all elements with the same value
2193 /// as the first element of exactly one source vector.
2194 /// Example: <4,undef,undef,4>
2195 /// This assumes that vector operands are the same length as the mask.
2196 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2197 static bool isZeroEltSplatMask(const Constant *Mask) {
2198 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2198, __PRETTY_FUNCTION__))
;
2199 SmallVector<int, 16> MaskAsInts;
2200 getShuffleMask(Mask, MaskAsInts);
2201 return isZeroEltSplatMask(MaskAsInts);
2202 }
2203
2204 /// Return true if all elements of this shuffle are the same value as the
2205 /// first element of exactly one source vector without changing the length
2206 /// of that vector.
2207 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2208 /// TODO: Optionally allow length-changing shuffles.
2209 /// TODO: Optionally allow splats from other elements.
2210 bool isZeroEltSplat() const {
2211 return !changesLength() && isZeroEltSplatMask(ShuffleMask);
2212 }
2213
2214 /// Return true if this shuffle mask is a transpose mask.
2215 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2216 /// even- or odd-numbered vector elements from two n-dimensional source
2217 /// vectors and write each result into consecutive elements of an
2218 /// n-dimensional destination vector. Two shuffles are necessary to complete
2219 /// the transpose, one for the even elements and another for the odd elements.
2220 /// This description closely follows how the TRN1 and TRN2 AArch64
2221 /// instructions operate.
2222 ///
2223 /// For example, a simple 2x2 matrix can be transposed with:
2224 ///
2225 /// ; Original matrix
2226 /// m0 = < a, b >
2227 /// m1 = < c, d >
2228 ///
2229 /// ; Transposed matrix
2230 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2231 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2232 ///
2233 /// For matrices having greater than n columns, the resulting nx2 transposed
2234 /// matrix is stored in two result vectors such that one vector contains
2235 /// interleaved elements from all the even-numbered rows and the other vector
2236 /// contains interleaved elements from all the odd-numbered rows. For example,
2237 /// a 2x4 matrix can be transposed with:
2238 ///
2239 /// ; Original matrix
2240 /// m0 = < a, b, c, d >
2241 /// m1 = < e, f, g, h >
2242 ///
2243 /// ; Transposed matrix
2244 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2245 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2246 static bool isTransposeMask(ArrayRef<int> Mask);
2247 static bool isTransposeMask(const Constant *Mask) {
2248 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2248, __PRETTY_FUNCTION__))
;
2249 SmallVector<int, 16> MaskAsInts;
2250 getShuffleMask(Mask, MaskAsInts);
2251 return isTransposeMask(MaskAsInts);
2252 }
2253
2254 /// Return true if this shuffle transposes the elements of its inputs without
2255 /// changing the length of the vectors. This operation may also be known as a
2256 /// merge or interleave. See the description for isTransposeMask() for the
2257 /// exact specification.
2258 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2259 bool isTranspose() const {
2260 return !changesLength() && isTransposeMask(ShuffleMask);
2261 }
2262
2263 /// Return true if this shuffle mask is an extract subvector mask.
2264 /// A valid extract subvector mask returns a smaller vector from a single
2265 /// source operand. The base extraction index is returned as well.
2266 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2267 int &Index);
2268 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2269 int &Index) {
2270 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2270, __PRETTY_FUNCTION__))
;
2271 SmallVector<int, 16> MaskAsInts;
2272 getShuffleMask(Mask, MaskAsInts);
2273 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2274 }
2275
2276 /// Return true if this shuffle mask is an extract subvector mask.
2277 bool isExtractSubvectorMask(int &Index) const {
2278 int NumSrcElts =
2279 cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2280 return isExtractSubvectorMask(ShuffleMask, NumSrcElts, Index);
2281 }
2282
2283 /// Change values in a shuffle permute mask assuming the two vector operands
2284 /// of length InVecNumElts have swapped position.
2285 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2286 unsigned InVecNumElts) {
2287 for (int &Idx : Mask) {
2288 if (Idx == -1)
2289 continue;
2290 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2291 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2292, __PRETTY_FUNCTION__))
2292 "shufflevector mask index out of range")((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2292, __PRETTY_FUNCTION__))
;
2293 }
2294 }
2295
2296 // Methods for support type inquiry through isa, cast, and dyn_cast:
2297 static bool classof(const Instruction *I) {
2298 return I->getOpcode() == Instruction::ShuffleVector;
2299 }
2300 static bool classof(const Value *V) {
2301 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2302 }
2303};
2304
2305template <>
2306struct OperandTraits<ShuffleVectorInst>
2307 : public FixedNumOperandTraits<ShuffleVectorInst, 2> {};
2308
2309DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() {
return OperandTraits<ShuffleVectorInst>::op_begin(this
); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst::
op_begin() const { return OperandTraits<ShuffleVectorInst>
::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst
::op_iterator ShuffleVectorInst::op_end() { return OperandTraits
<ShuffleVectorInst>::op_end(this); } ShuffleVectorInst::
const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits
<ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst
*>(this)); } Value *ShuffleVectorInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<ShuffleVectorInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2309, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ShuffleVectorInst>::op_begin(const_cast
<ShuffleVectorInst*>(this))[i_nocapture].get()); } void
ShuffleVectorInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<ShuffleVectorInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2309, __PRETTY_FUNCTION__)); OperandTraits<ShuffleVectorInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
ShuffleVectorInst::getNumOperands() const { return OperandTraits
<ShuffleVectorInst>::operands(this); } template <int
Idx_nocapture> Use &ShuffleVectorInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &ShuffleVectorInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
2310
2311//===----------------------------------------------------------------------===//
2312// ExtractValueInst Class
2313//===----------------------------------------------------------------------===//
2314
2315/// This instruction extracts a struct member or array
2316/// element value from an aggregate value.
2317///
2318class ExtractValueInst : public UnaryInstruction {
2319 SmallVector<unsigned, 4> Indices;
2320
2321 ExtractValueInst(const ExtractValueInst &EVI);
2322
2323 /// Constructors - Create a extractvalue instruction with a base aggregate
2324 /// value and a list of indices. The first ctor can optionally insert before
2325 /// an existing instruction, the second appends the new instruction to the
2326 /// specified BasicBlock.
2327 inline ExtractValueInst(Value *Agg,
2328 ArrayRef<unsigned> Idxs,
2329 const Twine &NameStr,
2330 Instruction *InsertBefore);
2331 inline ExtractValueInst(Value *Agg,
2332 ArrayRef<unsigned> Idxs,
2333 const Twine &NameStr, BasicBlock *InsertAtEnd);
2334
2335 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2336
2337protected:
2338 // Note: Instruction needs to be a friend here to call cloneImpl.
2339 friend class Instruction;
2340
2341 ExtractValueInst *cloneImpl() const;
2342
2343public:
2344 static ExtractValueInst *Create(Value *Agg,
2345 ArrayRef<unsigned> Idxs,
2346 const Twine &NameStr = "",
2347 Instruction *InsertBefore = nullptr) {
2348 return new
2349 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2350 }
2351
2352 static ExtractValueInst *Create(Value *Agg,
2353 ArrayRef<unsigned> Idxs,
2354 const Twine &NameStr,
2355 BasicBlock *InsertAtEnd) {
2356 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2357 }
2358
2359 /// Returns the type of the element that would be extracted
2360 /// with an extractvalue instruction with the specified parameters.
2361 ///
2362 /// Null is returned if the indices are invalid for the specified type.
2363 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2364
2365 using idx_iterator = const unsigned*;
2366
2367 inline idx_iterator idx_begin() const { return Indices.begin(); }
2368 inline idx_iterator idx_end() const { return Indices.end(); }
2369 inline iterator_range<idx_iterator> indices() const {
2370 return make_range(idx_begin(), idx_end());
2371 }
2372
2373 Value *getAggregateOperand() {
2374 return getOperand(0);
2375 }
2376 const Value *getAggregateOperand() const {
2377 return getOperand(0);
2378 }
2379 static unsigned getAggregateOperandIndex() {
2380 return 0U; // get index for modifying correct operand
2381 }
2382
2383 ArrayRef<unsigned> getIndices() const {
2384 return Indices;
2385 }
2386
2387 unsigned getNumIndices() const {
2388 return (unsigned)Indices.size();
2389 }
2390
2391 bool hasIndices() const {
2392 return true;
2393 }
2394
2395 // Methods for support type inquiry through isa, cast, and dyn_cast:
2396 static bool classof(const Instruction *I) {
2397 return I->getOpcode() == Instruction::ExtractValue;
2398 }
2399 static bool classof(const Value *V) {
2400 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2401 }
2402};
2403
2404ExtractValueInst::ExtractValueInst(Value *Agg,
2405 ArrayRef<unsigned> Idxs,
2406 const Twine &NameStr,
2407 Instruction *InsertBefore)
2408 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2409 ExtractValue, Agg, InsertBefore) {
2410 init(Idxs, NameStr);
2411}
2412
2413ExtractValueInst::ExtractValueInst(Value *Agg,
2414 ArrayRef<unsigned> Idxs,
2415 const Twine &NameStr,
2416 BasicBlock *InsertAtEnd)
2417 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2418 ExtractValue, Agg, InsertAtEnd) {
2419 init(Idxs, NameStr);
2420}
2421
2422//===----------------------------------------------------------------------===//
2423// InsertValueInst Class
2424//===----------------------------------------------------------------------===//
2425
2426/// This instruction inserts a struct field of array element
2427/// value into an aggregate value.
2428///
2429class InsertValueInst : public Instruction {
2430 SmallVector<unsigned, 4> Indices;
2431
2432 InsertValueInst(const InsertValueInst &IVI);
2433
2434 /// Constructors - Create a insertvalue instruction with a base aggregate
2435 /// value, a value to insert, and a list of indices. The first ctor can
2436 /// optionally insert before an existing instruction, the second appends
2437 /// the new instruction to the specified BasicBlock.
2438 inline InsertValueInst(Value *Agg, Value *Val,
2439 ArrayRef<unsigned> Idxs,
2440 const Twine &NameStr,
2441 Instruction *InsertBefore);
2442 inline InsertValueInst(Value *Agg, Value *Val,
2443 ArrayRef<unsigned> Idxs,
2444 const Twine &NameStr, BasicBlock *InsertAtEnd);
2445
2446 /// Constructors - These two constructors are convenience methods because one
2447 /// and two index insertvalue instructions are so common.
2448 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2449 const Twine &NameStr = "",
2450 Instruction *InsertBefore = nullptr);
2451 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2452 BasicBlock *InsertAtEnd);
2453
2454 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2455 const Twine &NameStr);
2456
2457protected:
2458 // Note: Instruction needs to be a friend here to call cloneImpl.
2459 friend class Instruction;
2460
2461 InsertValueInst *cloneImpl() const;
2462
2463public:
2464 // allocate space for exactly two operands
2465 void *operator new(size_t s) {
2466 return User::operator new(s, 2);
2467 }
2468
2469 static InsertValueInst *Create(Value *Agg, Value *Val,
2470 ArrayRef<unsigned> Idxs,
2471 const Twine &NameStr = "",
2472 Instruction *InsertBefore = nullptr) {
2473 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2474 }
2475
2476 static InsertValueInst *Create(Value *Agg, Value *Val,
2477 ArrayRef<unsigned> Idxs,
2478 const Twine &NameStr,
2479 BasicBlock *InsertAtEnd) {
2480 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2481 }
2482
2483 /// Transparently provide more efficient getOperand methods.
2484 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2485
2486 using idx_iterator = const unsigned*;
2487
2488 inline idx_iterator idx_begin() const { return Indices.begin(); }
2489 inline idx_iterator idx_end() const { return Indices.end(); }
2490 inline iterator_range<idx_iterator> indices() const {
2491 return make_range(idx_begin(), idx_end());
2492 }
2493
2494 Value *getAggregateOperand() {
2495 return getOperand(0);
2496 }
2497 const Value *getAggregateOperand() const {
2498 return getOperand(0);
2499 }
2500 static unsigned getAggregateOperandIndex() {
2501 return 0U; // get index for modifying correct operand
2502 }
2503
2504 Value *getInsertedValueOperand() {
2505 return getOperand(1);
2506 }
2507 const Value *getInsertedValueOperand() const {
2508 return getOperand(1);
2509 }
2510 static unsigned getInsertedValueOperandIndex() {
2511 return 1U; // get index for modifying correct operand
2512 }
2513
2514 ArrayRef<unsigned> getIndices() const {
2515 return Indices;
2516 }
2517
2518 unsigned getNumIndices() const {
2519 return (unsigned)Indices.size();
2520 }
2521
2522 bool hasIndices() const {
2523 return true;
2524 }
2525
2526 // Methods for support type inquiry through isa, cast, and dyn_cast:
2527 static bool classof(const Instruction *I) {
2528 return I->getOpcode() == Instruction::InsertValue;
2529 }
2530 static bool classof(const Value *V) {
2531 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2532 }
2533};
2534
2535template <>
2536struct OperandTraits<InsertValueInst> :
2537 public FixedNumOperandTraits<InsertValueInst, 2> {
2538};
2539
2540InsertValueInst::InsertValueInst(Value *Agg,
2541 Value *Val,
2542 ArrayRef<unsigned> Idxs,
2543 const Twine &NameStr,
2544 Instruction *InsertBefore)
2545 : Instruction(Agg->getType(), InsertValue,
2546 OperandTraits<InsertValueInst>::op_begin(this),
2547 2, InsertBefore) {
2548 init(Agg, Val, Idxs, NameStr);
2549}
2550
2551InsertValueInst::InsertValueInst(Value *Agg,
2552 Value *Val,
2553 ArrayRef<unsigned> Idxs,
2554 const Twine &NameStr,
2555 BasicBlock *InsertAtEnd)
2556 : Instruction(Agg->getType(), InsertValue,
2557 OperandTraits<InsertValueInst>::op_begin(this),
2558 2, InsertAtEnd) {
2559 init(Agg, Val, Idxs, NameStr);
2560}
2561
2562DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)InsertValueInst::op_iterator InsertValueInst::op_begin() { return
OperandTraits<InsertValueInst>::op_begin(this); } InsertValueInst
::const_op_iterator InsertValueInst::op_begin() const { return
OperandTraits<InsertValueInst>::op_begin(const_cast<
InsertValueInst*>(this)); } InsertValueInst::op_iterator InsertValueInst
::op_end() { return OperandTraits<InsertValueInst>::op_end
(this); } InsertValueInst::const_op_iterator InsertValueInst::
op_end() const { return OperandTraits<InsertValueInst>::
op_end(const_cast<InsertValueInst*>(this)); } Value *InsertValueInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<InsertValueInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2562, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<InsertValueInst>::op_begin(const_cast<
InsertValueInst*>(this))[i_nocapture].get()); } void InsertValueInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<InsertValueInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2562, __PRETTY_FUNCTION__)); OperandTraits<InsertValueInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
InsertValueInst::getNumOperands() const { return OperandTraits
<InsertValueInst>::operands(this); } template <int Idx_nocapture
> Use &InsertValueInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &InsertValueInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
2563
2564//===----------------------------------------------------------------------===//
2565// PHINode Class
2566//===----------------------------------------------------------------------===//
2567
2568// PHINode - The PHINode class is used to represent the magical mystical PHI
2569// node, that can not exist in nature, but can be synthesized in a computer
2570// scientist's overactive imagination.
2571//
2572class PHINode : public Instruction {
2573 /// The number of operands actually allocated. NumOperands is
2574 /// the number actually in use.
2575 unsigned ReservedSpace;
2576
2577 PHINode(const PHINode &PN);
2578
2579 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2580 const Twine &NameStr = "",
2581 Instruction *InsertBefore = nullptr)
2582 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2583 ReservedSpace(NumReservedValues) {
2584 setName(NameStr);
2585 allocHungoffUses(ReservedSpace);
2586 }
2587
2588 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2589 BasicBlock *InsertAtEnd)
2590 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2591 ReservedSpace(NumReservedValues) {
2592 setName(NameStr);
2593 allocHungoffUses(ReservedSpace);
2594 }
2595
2596protected:
2597 // Note: Instruction needs to be a friend here to call cloneImpl.
2598 friend class Instruction;
2599
2600 PHINode *cloneImpl() const;
2601
2602 // allocHungoffUses - this is more complicated than the generic
2603 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2604 // values and pointers to the incoming blocks, all in one allocation.
2605 void allocHungoffUses(unsigned N) {
2606 User::allocHungoffUses(N, /* IsPhi */ true);
2607 }
2608
2609public:
2610 /// Constructors - NumReservedValues is a hint for the number of incoming
2611 /// edges that this phi node will have (use 0 if you really have no idea).
2612 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2613 const Twine &NameStr = "",
2614 Instruction *InsertBefore = nullptr) {
2615 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2616 }
2617
2618 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2619 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2620 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2621 }
2622
2623 /// Provide fast operand accessors
2624 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2625
2626 // Block iterator interface. This provides access to the list of incoming
2627 // basic blocks, which parallels the list of incoming values.
2628
2629 using block_iterator = BasicBlock **;
2630 using const_block_iterator = BasicBlock * const *;
2631
2632 block_iterator block_begin() {
2633 return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
2634 }
2635
2636 const_block_iterator block_begin() const {
2637 return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
2638 }
2639
2640 block_iterator block_end() {
2641 return block_begin() + getNumOperands();
2642 }
2643
2644 const_block_iterator block_end() const {
2645 return block_begin() + getNumOperands();
2646 }
2647
2648 iterator_range<block_iterator> blocks() {
2649 return make_range(block_begin(), block_end());
2650 }
2651
2652 iterator_range<const_block_iterator> blocks() const {
2653 return make_range(block_begin(), block_end());
2654 }
2655
2656 op_range incoming_values() { return operands(); }
2657
2658 const_op_range incoming_values() const { return operands(); }
2659
2660 /// Return the number of incoming edges
2661 ///
2662 unsigned getNumIncomingValues() const { return getNumOperands(); }
2663
2664 /// Return incoming value number x
2665 ///
2666 Value *getIncomingValue(unsigned i) const {
2667 return getOperand(i);
2668 }
2669 void setIncomingValue(unsigned i, Value *V) {
2670 assert(V && "PHI node got a null value!")((V && "PHI node got a null value!") ? static_cast<
void> (0) : __assert_fail ("V && \"PHI node got a null value!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2670, __PRETTY_FUNCTION__))
;
2671 assert(getType() == V->getType() &&((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!"
) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2672, __PRETTY_FUNCTION__))
2672 "All operands to PHI node must be the same type as the PHI node!")((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!"
) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2672, __PRETTY_FUNCTION__))
;
2673 setOperand(i, V);
2674 }
2675
2676 static unsigned getOperandNumForIncomingValue(unsigned i) {
2677 return i;
2678 }
2679
2680 static unsigned getIncomingValueNumForOperand(unsigned i) {
2681 return i;
2682 }
2683
2684 /// Return incoming basic block number @p i.
2685 ///
2686 BasicBlock *getIncomingBlock(unsigned i) const {
2687 return block_begin()[i];
2688 }
2689
2690 /// Return incoming basic block corresponding
2691 /// to an operand of the PHI.
2692 ///
2693 BasicBlock *getIncomingBlock(const Use &U) const {
2694 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")((this == U.getUser() && "Iterator doesn't point to PHI's Uses?"
) ? static_cast<void> (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2694, __PRETTY_FUNCTION__))
;
2695 return getIncomingBlock(unsigned(&U - op_begin()));
2696 }
2697
2698 /// Return incoming basic block corresponding
2699 /// to value use iterator.
2700 ///
2701 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2702 return getIncomingBlock(I.getUse());
2703 }
2704
2705 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2706 assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast
<void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2706, __PRETTY_FUNCTION__))
;
2707 block_begin()[i] = BB;
2708 }
2709
2710 /// Replace every incoming basic block \p Old to basic block \p New.
2711 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
2712 assert(New && Old && "PHI node got a null basic block!")((New && Old && "PHI node got a null basic block!"
) ? static_cast<void> (0) : __assert_fail ("New && Old && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2712, __PRETTY_FUNCTION__))
;
2713 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2714 if (getIncomingBlock(Op) == Old)
2715 setIncomingBlock(Op, New);
2716 }
2717
2718 /// Add an incoming value to the end of the PHI list
2719 ///
2720 void addIncoming(Value *V, BasicBlock *BB) {
2721 if (getNumOperands() == ReservedSpace)
2722 growOperands(); // Get more space!
2723 // Initialize some new operands.
2724 setNumHungOffUseOperands(getNumOperands() + 1);
2725 setIncomingValue(getNumOperands() - 1, V);
2726 setIncomingBlock(getNumOperands() - 1, BB);
2727 }
2728
2729 /// Remove an incoming value. This is useful if a
2730 /// predecessor basic block is deleted. The value removed is returned.
2731 ///
2732 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2733 /// is true), the PHI node is destroyed and any uses of it are replaced with
2734 /// dummy values. The only time there should be zero incoming values to a PHI
2735 /// node is when the block is dead, so this strategy is sound.
2736 ///
2737 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2738
2739 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2740 int Idx = getBasicBlockIndex(BB);
2741 assert(Idx >= 0 && "Invalid basic block argument to remove!")((Idx >= 0 && "Invalid basic block argument to remove!"
) ? static_cast<void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument to remove!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2741, __PRETTY_FUNCTION__))
;
2742 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2743 }
2744
2745 /// Return the first index of the specified basic
2746 /// block in the value list for this PHI. Returns -1 if no instance.
2747 ///
2748 int getBasicBlockIndex(const BasicBlock *BB) const {
2749 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2750 if (block_begin()[i] == BB)
2751 return i;
2752 return -1;
2753 }
2754
2755 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2756 int Idx = getBasicBlockIndex(BB);
2757 assert(Idx >= 0 && "Invalid basic block argument!")((Idx >= 0 && "Invalid basic block argument!") ? static_cast
<void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2757, __PRETTY_FUNCTION__))
;
2758 return getIncomingValue(Idx);
2759 }
2760
2761 /// Set every incoming value(s) for block \p BB to \p V.
2762 void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
2763 assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast
<void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2763, __PRETTY_FUNCTION__))
;
2764 bool Found = false;
2765 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2766 if (getIncomingBlock(Op) == BB) {
2767 Found = true;
2768 setIncomingValue(Op, V);
2769 }
2770 (void)Found;
2771 assert(Found && "Invalid basic block argument to set!")((Found && "Invalid basic block argument to set!") ? static_cast
<void> (0) : __assert_fail ("Found && \"Invalid basic block argument to set!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2771, __PRETTY_FUNCTION__))
;
2772 }
2773
2774 /// If the specified PHI node always merges together the
2775 /// same value, return the value, otherwise return null.
2776 Value *hasConstantValue() const;
2777
2778 /// Whether the specified PHI node always merges
2779 /// together the same value, assuming undefs are equal to a unique
2780 /// non-undef value.
2781 bool hasConstantOrUndefValue() const;
2782
2783 /// If the PHI node is complete which means all of its parent's predecessors
2784 /// have incoming value in this PHI, return true, otherwise return false.
2785 bool isComplete() const {
2786 return llvm::all_of(predecessors(getParent()),
2787 [this](const BasicBlock *Pred) {
2788 return getBasicBlockIndex(Pred) >= 0;
2789 });
2790 }
2791
2792 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2793 static bool classof(const Instruction *I) {
2794 return I->getOpcode() == Instruction::PHI;
2795 }
2796 static bool classof(const Value *V) {
2797 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2798 }
2799
2800private:
2801 void growOperands();
2802};
2803
2804template <>
2805struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2806};
2807
2808DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)PHINode::op_iterator PHINode::op_begin() { return OperandTraits
<PHINode>::op_begin(this); } PHINode::const_op_iterator
PHINode::op_begin() const { return OperandTraits<PHINode>
::op_begin(const_cast<PHINode*>(this)); } PHINode::op_iterator
PHINode::op_end() { return OperandTraits<PHINode>::op_end
(this); } PHINode::const_op_iterator PHINode::op_end() const {
return OperandTraits<PHINode>::op_end(const_cast<PHINode
*>(this)); } Value *PHINode::getOperand(unsigned i_nocapture
) const { ((i_nocapture < OperandTraits<PHINode>::operands
(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2808, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<PHINode>::op_begin(const_cast<PHINode
*>(this))[i_nocapture].get()); } void PHINode::setOperand(
unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<PHINode>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2808, __PRETTY_FUNCTION__)); OperandTraits<PHINode>::
op_begin(this)[i_nocapture] = Val_nocapture; } unsigned PHINode
::getNumOperands() const { return OperandTraits<PHINode>
::operands(this); } template <int Idx_nocapture> Use &
PHINode::Op() { return this->OpFrom<Idx_nocapture>(this
); } template <int Idx_nocapture> const Use &PHINode
::Op() const { return this->OpFrom<Idx_nocapture>(this
); }
2809
2810//===----------------------------------------------------------------------===//
2811// LandingPadInst Class
2812//===----------------------------------------------------------------------===//
2813
2814//===---------------------------------------------------------------------------
2815/// The landingpad instruction holds all of the information
2816/// necessary to generate correct exception handling. The landingpad instruction
2817/// cannot be moved from the top of a landing pad block, which itself is
2818/// accessible only from the 'unwind' edge of an invoke. This uses the
2819/// SubclassData field in Value to store whether or not the landingpad is a
2820/// cleanup.
2821///
2822class LandingPadInst : public Instruction {
2823 using CleanupField = BoolBitfieldElementT<0>;
2824
2825 /// The number of operands actually allocated. NumOperands is
2826 /// the number actually in use.
2827 unsigned ReservedSpace;
2828
2829 LandingPadInst(const LandingPadInst &LP);
2830
2831public:
2832 enum ClauseType { Catch, Filter };
2833
2834private:
2835 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2836 const Twine &NameStr, Instruction *InsertBefore);
2837 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2838 const Twine &NameStr, BasicBlock *InsertAtEnd);
2839
2840 // Allocate space for exactly zero operands.
2841 void *operator new(size_t s) {
2842 return User::operator new(s);
2843 }
2844
2845 void growOperands(unsigned Size);
2846 void init(unsigned NumReservedValues, const Twine &NameStr);
2847
2848protected:
2849 // Note: Instruction needs to be a friend here to call cloneImpl.
2850 friend class Instruction;
2851
2852 LandingPadInst *cloneImpl() const;
2853
2854public:
2855 /// Constructors - NumReservedClauses is a hint for the number of incoming
2856 /// clauses that this landingpad will have (use 0 if you really have no idea).
2857 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2858 const Twine &NameStr = "",
2859 Instruction *InsertBefore = nullptr);
2860 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2861 const Twine &NameStr, BasicBlock *InsertAtEnd);
2862
2863 /// Provide fast operand accessors
2864 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2865
2866 /// Return 'true' if this landingpad instruction is a
2867 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2868 /// doesn't catch the exception.
2869 bool isCleanup() const { return getSubclassData<CleanupField>(); }
2870
2871 /// Indicate that this landingpad instruction is a cleanup.
2872 void setCleanup(bool V) { setSubclassData<CleanupField>(V); }
2873
2874 /// Add a catch or filter clause to the landing pad.
2875 void addClause(Constant *ClauseVal);
2876
2877 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2878 /// determine what type of clause this is.
2879 Constant *getClause(unsigned Idx) const {
2880 return cast<Constant>(getOperandList()[Idx]);
2881 }
2882
2883 /// Return 'true' if the clause and index Idx is a catch clause.
2884 bool isCatch(unsigned Idx) const {
2885 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2886 }
2887
2888 /// Return 'true' if the clause and index Idx is a filter clause.
2889 bool isFilter(unsigned Idx) const {
2890 return isa<ArrayType>(getOperandList()[Idx]->getType());
2891 }
2892
2893 /// Get the number of clauses for this landing pad.
2894 unsigned getNumClauses() const { return getNumOperands(); }
2895
2896 /// Grow the size of the operand list to accommodate the new
2897 /// number of clauses.
2898 void reserveClauses(unsigned Size) { growOperands(Size); }
2899
2900 // Methods for support type inquiry through isa, cast, and dyn_cast:
2901 static bool classof(const Instruction *I) {
2902 return I->getOpcode() == Instruction::LandingPad;
2903 }
2904 static bool classof(const Value *V) {
2905 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2906 }
2907};
2908
2909template <>
2910struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2911};
2912
2913DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)LandingPadInst::op_iterator LandingPadInst::op_begin() { return
OperandTraits<LandingPadInst>::op_begin(this); } LandingPadInst
::const_op_iterator LandingPadInst::op_begin() const { return
OperandTraits<LandingPadInst>::op_begin(const_cast<
LandingPadInst*>(this)); } LandingPadInst::op_iterator LandingPadInst
::op_end() { return OperandTraits<LandingPadInst>::op_end
(this); } LandingPadInst::const_op_iterator LandingPadInst::op_end
() const { return OperandTraits<LandingPadInst>::op_end
(const_cast<LandingPadInst*>(this)); } Value *LandingPadInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<LandingPadInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2913, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<LandingPadInst>::op_begin(const_cast<
LandingPadInst*>(this))[i_nocapture].get()); } void LandingPadInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<LandingPadInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2913, __PRETTY_FUNCTION__)); OperandTraits<LandingPadInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
LandingPadInst::getNumOperands() const { return OperandTraits
<LandingPadInst>::operands(this); } template <int Idx_nocapture
> Use &LandingPadInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &LandingPadInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
2914
2915//===----------------------------------------------------------------------===//
2916// ReturnInst Class
2917//===----------------------------------------------------------------------===//
2918
2919//===---------------------------------------------------------------------------
2920/// Return a value (possibly void), from a function. Execution
2921/// does not continue in this function any longer.
2922///
2923class ReturnInst : public Instruction {
2924 ReturnInst(const ReturnInst &RI);
2925
2926private:
2927 // ReturnInst constructors:
2928 // ReturnInst() - 'ret void' instruction
2929 // ReturnInst( null) - 'ret void' instruction
2930 // ReturnInst(Value* X) - 'ret X' instruction
2931 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2932 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2933 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2934 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2935 //
2936 // NOTE: If the Value* passed is of type void then the constructor behaves as
2937 // if it was passed NULL.
2938 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2939 Instruction *InsertBefore = nullptr);
2940 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2941 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2942
2943protected:
2944 // Note: Instruction needs to be a friend here to call cloneImpl.
2945 friend class Instruction;
2946
2947 ReturnInst *cloneImpl() const;
2948
2949public:
2950 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2951 Instruction *InsertBefore = nullptr) {
2952 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2953 }
2954
2955 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2956 BasicBlock *InsertAtEnd) {
2957 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2958 }
2959
2960 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2961 return new(0) ReturnInst(C, InsertAtEnd);
2962 }
2963
2964 /// Provide fast operand accessors
2965 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
2966
2967 /// Convenience accessor. Returns null if there is no return value.
2968 Value *getReturnValue() const {
2969 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2970 }
2971
2972 unsigned getNumSuccessors() const { return 0; }
2973
2974 // Methods for support type inquiry through isa, cast, and dyn_cast:
2975 static bool classof(const Instruction *I) {
2976 return (I->getOpcode() == Instruction::Ret);
2977 }
2978 static bool classof(const Value *V) {
2979 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2980 }
2981
2982private:
2983 BasicBlock *getSuccessor(unsigned idx) const {
2984 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2984)
;
2985 }
2986
2987 void setSuccessor(unsigned idx, BasicBlock *B) {
2988 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2988)
;
2989 }
2990};
2991
2992template <>
2993struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2994};
2995
2996DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)ReturnInst::op_iterator ReturnInst::op_begin() { return OperandTraits
<ReturnInst>::op_begin(this); } ReturnInst::const_op_iterator
ReturnInst::op_begin() const { return OperandTraits<ReturnInst
>::op_begin(const_cast<ReturnInst*>(this)); } ReturnInst
::op_iterator ReturnInst::op_end() { return OperandTraits<
ReturnInst>::op_end(this); } ReturnInst::const_op_iterator
ReturnInst::op_end() const { return OperandTraits<ReturnInst
>::op_end(const_cast<ReturnInst*>(this)); } Value *ReturnInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<ReturnInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2996, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ReturnInst>::op_begin(const_cast<ReturnInst
*>(this))[i_nocapture].get()); } void ReturnInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<ReturnInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 2996, __PRETTY_FUNCTION__)); OperandTraits<ReturnInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ReturnInst
::getNumOperands() const { return OperandTraits<ReturnInst
>::operands(this); } template <int Idx_nocapture> Use
&ReturnInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
ReturnInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
2997
2998//===----------------------------------------------------------------------===//
2999// BranchInst Class
3000//===----------------------------------------------------------------------===//
3001
3002//===---------------------------------------------------------------------------
3003/// Conditional or Unconditional Branch instruction.
3004///
3005class BranchInst : public Instruction {
3006 /// Ops list - Branches are strange. The operands are ordered:
3007 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
3008 /// they don't have to check for cond/uncond branchness. These are mostly
3009 /// accessed relative from op_end().
3010 BranchInst(const BranchInst &BI);
3011 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
3012 // BranchInst(BB *B) - 'br B'
3013 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
3014 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
3015 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
3016 // BranchInst(BB* B, BB *I) - 'br B' insert at end
3017 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
3018 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
3019 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3020 Instruction *InsertBefore = nullptr);
3021 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
3022 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
3023 BasicBlock *InsertAtEnd);
3024
3025 void AssertOK();
3026
3027protected:
3028 // Note: Instruction needs to be a friend here to call cloneImpl.
3029 friend class Instruction;
3030
3031 BranchInst *cloneImpl() const;
3032
3033public:
3034 /// Iterator type that casts an operand to a basic block.
3035 ///
3036 /// This only makes sense because the successors are stored as adjacent
3037 /// operands for branch instructions.
3038 struct succ_op_iterator
3039 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3040 std::random_access_iterator_tag, BasicBlock *,
3041 ptrdiff_t, BasicBlock *, BasicBlock *> {
3042 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3043
3044 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3045 BasicBlock *operator->() const { return operator*(); }
3046 };
3047
3048 /// The const version of `succ_op_iterator`.
3049 struct const_succ_op_iterator
3050 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3051 std::random_access_iterator_tag,
3052 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3053 const BasicBlock *> {
3054 explicit const_succ_op_iterator(const_value_op_iterator I)
3055 : iterator_adaptor_base(I) {}
3056
3057 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3058 const BasicBlock *operator->() const { return operator*(); }
3059 };
3060
3061 static BranchInst *Create(BasicBlock *IfTrue,
3062 Instruction *InsertBefore = nullptr) {
3063 return new(1) BranchInst(IfTrue, InsertBefore);
3064 }
3065
3066 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3067 Value *Cond, Instruction *InsertBefore = nullptr) {
3068 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3069 }
3070
3071 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3072 return new(1) BranchInst(IfTrue, InsertAtEnd);
3073 }
3074
3075 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3076 Value *Cond, BasicBlock *InsertAtEnd) {
3077 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3078 }
3079
3080 /// Transparently provide more efficient getOperand methods.
3081 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
3082
3083 bool isUnconditional() const { return getNumOperands() == 1; }
3084 bool isConditional() const { return getNumOperands() == 3; }
3085
3086 Value *getCondition() const {
3087 assert(isConditional() && "Cannot get condition of an uncond branch!")((isConditional() && "Cannot get condition of an uncond branch!"
) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot get condition of an uncond branch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3087, __PRETTY_FUNCTION__))
;
3088 return Op<-3>();
3089 }
3090
3091 void setCondition(Value *V) {
3092 assert(isConditional() && "Cannot set condition of unconditional branch!")((isConditional() && "Cannot set condition of unconditional branch!"
) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot set condition of unconditional branch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3092, __PRETTY_FUNCTION__))
;
3093 Op<-3>() = V;
3094 }
3095
3096 unsigned getNumSuccessors() const { return 1+isConditional(); }
3097
3098 BasicBlock *getSuccessor(unsigned i) const {
3099 assert(i < getNumSuccessors() && "Successor # out of range for Branch!")((i < getNumSuccessors() && "Successor # out of range for Branch!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3099, __PRETTY_FUNCTION__))
;
3100 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3101 }
3102
3103 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3104 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")((idx < getNumSuccessors() && "Successor # out of range for Branch!"
) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3104, __PRETTY_FUNCTION__))
;
3105 *(&Op<-1>() - idx) = NewSucc;
3106 }
3107
3108 /// Swap the successors of this branch instruction.
3109 ///
3110 /// Swaps the successors of the branch instruction. This also swaps any
3111 /// branch weight metadata associated with the instruction so that it
3112 /// continues to map correctly to each operand.
3113 void swapSuccessors();
3114
3115 iterator_range<succ_op_iterator> successors() {
3116 return make_range(
3117 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3118 succ_op_iterator(value_op_end()));
3119 }
3120
3121 iterator_range<const_succ_op_iterator> successors() const {
3122 return make_range(const_succ_op_iterator(
3123 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3124 const_succ_op_iterator(value_op_end()));
3125 }
3126
3127 // Methods for support type inquiry through isa, cast, and dyn_cast:
3128 static bool classof(const Instruction *I) {
3129 return (I->getOpcode() == Instruction::Br);
3130 }
3131 static bool classof(const Value *V) {
3132 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3133 }
3134};
3135
3136template <>
3137struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3138};
3139
3140DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)BranchInst::op_iterator BranchInst::op_begin() { return OperandTraits
<BranchInst>::op_begin(this); } BranchInst::const_op_iterator
BranchInst::op_begin() const { return OperandTraits<BranchInst
>::op_begin(const_cast<BranchInst*>(this)); } BranchInst
::op_iterator BranchInst::op_end() { return OperandTraits<
BranchInst>::op_end(this); } BranchInst::const_op_iterator
BranchInst::op_end() const { return OperandTraits<BranchInst
>::op_end(const_cast<BranchInst*>(this)); } Value *BranchInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<BranchInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3140, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<BranchInst>::op_begin(const_cast<BranchInst
*>(this))[i_nocapture].get()); } void BranchInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<BranchInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3140, __PRETTY_FUNCTION__)); OperandTraits<BranchInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned BranchInst
::getNumOperands() const { return OperandTraits<BranchInst
>::operands(this); } template <int Idx_nocapture> Use
&BranchInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
BranchInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
3141
3142//===----------------------------------------------------------------------===//
3143// SwitchInst Class
3144//===----------------------------------------------------------------------===//
3145
3146//===---------------------------------------------------------------------------
3147/// Multiway switch
3148///
3149class SwitchInst : public Instruction {
3150 unsigned ReservedSpace;
3151
3152 // Operand[0] = Value to switch on
3153 // Operand[1] = Default basic block destination
3154 // Operand[2n ] = Value to match
3155 // Operand[2n+1] = BasicBlock to go to on match
3156 SwitchInst(const SwitchInst &SI);
3157
3158 /// Create a new switch instruction, specifying a value to switch on and a
3159 /// default destination. The number of additional cases can be specified here
3160 /// to make memory allocation more efficient. This constructor can also
3161 /// auto-insert before another instruction.
3162 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3163 Instruction *InsertBefore);
3164
3165 /// Create a new switch instruction, specifying a value to switch on and a
3166 /// default destination. The number of additional cases can be specified here
3167 /// to make memory allocation more efficient. This constructor also
3168 /// auto-inserts at the end of the specified BasicBlock.
3169 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3170 BasicBlock *InsertAtEnd);
3171
3172 // allocate space for exactly zero operands
3173 void *operator new(size_t s) {
3174 return User::operator new(s);
3175 }
3176
3177 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3178 void growOperands();
3179
3180protected:
3181 // Note: Instruction needs to be a friend here to call cloneImpl.
3182 friend class Instruction;
3183
3184 SwitchInst *cloneImpl() const;
3185
3186public:
3187 // -2
3188 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3189
3190 template <typename CaseHandleT> class CaseIteratorImpl;
3191
3192 /// A handle to a particular switch case. It exposes a convenient interface
3193 /// to both the case value and the successor block.
3194 ///
3195 /// We define this as a template and instantiate it to form both a const and
3196 /// non-const handle.
3197 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3198 class CaseHandleImpl {
3199 // Directly befriend both const and non-const iterators.
3200 friend class SwitchInst::CaseIteratorImpl<
3201 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3202
3203 protected:
3204 // Expose the switch type we're parameterized with to the iterator.
3205 using SwitchInstType = SwitchInstT;
3206
3207 SwitchInstT *SI;
3208 ptrdiff_t Index;
3209
3210 CaseHandleImpl() = default;
3211 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3212
3213 public:
3214 /// Resolves case value for current case.
3215 ConstantIntT *getCaseValue() const {
3216 assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3217, __PRETTY_FUNCTION__))
3217 "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3217, __PRETTY_FUNCTION__))
;
3218 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3219 }
3220
3221 /// Resolves successor for current case.
3222 BasicBlockT *getCaseSuccessor() const {
3223 assert(((unsigned)Index < SI->getNumCases() ||((((unsigned)Index < SI->getNumCases() || (unsigned)Index
== DefaultPseudoIndex) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3225, __PRETTY_FUNCTION__))
3224 (unsigned)Index == DefaultPseudoIndex) &&((((unsigned)Index < SI->getNumCases() || (unsigned)Index
== DefaultPseudoIndex) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3225, __PRETTY_FUNCTION__))
3225 "Index out the number of cases.")((((unsigned)Index < SI->getNumCases() || (unsigned)Index
== DefaultPseudoIndex) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3225, __PRETTY_FUNCTION__))
;
3226 return SI->getSuccessor(getSuccessorIndex());
3227 }
3228
3229 /// Returns number of current case.
3230 unsigned getCaseIndex() const { return Index; }
3231
3232 /// Returns successor index for current case successor.
3233 unsigned getSuccessorIndex() const {
3234 assert(((unsigned)Index == DefaultPseudoIndex ||((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index <
SI->getNumCases()) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3236, __PRETTY_FUNCTION__))
3235 (unsigned)Index < SI->getNumCases()) &&((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index <
SI->getNumCases()) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3236, __PRETTY_FUNCTION__))
3236 "Index out the number of cases.")((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index <
SI->getNumCases()) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3236, __PRETTY_FUNCTION__))
;
3237 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3238 }
3239
3240 bool operator==(const CaseHandleImpl &RHS) const {
3241 assert(SI == RHS.SI && "Incompatible operators.")((SI == RHS.SI && "Incompatible operators.") ? static_cast
<void> (0) : __assert_fail ("SI == RHS.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3241, __PRETTY_FUNCTION__))
;
3242 return Index == RHS.Index;
3243 }
3244 };
3245
3246 using ConstCaseHandle =
3247 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3248
3249 class CaseHandle
3250 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3251 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3252
3253 public:
3254 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3255
3256 /// Sets the new value for current case.
3257 void setValue(ConstantInt *V) {
3258 assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3259, __PRETTY_FUNCTION__))
3259 "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3259, __PRETTY_FUNCTION__))
;
3260 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3261 }
3262
3263 /// Sets the new successor for current case.
3264 void setSuccessor(BasicBlock *S) {
3265 SI->setSuccessor(getSuccessorIndex(), S);
3266 }
3267 };
3268
3269 template <typename CaseHandleT>
3270 class CaseIteratorImpl
3271 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3272 std::random_access_iterator_tag,
3273 CaseHandleT> {
3274 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3275
3276 CaseHandleT Case;
3277
3278 public:
3279 /// Default constructed iterator is in an invalid state until assigned to
3280 /// a case for a particular switch.
3281 CaseIteratorImpl() = default;
3282
3283 /// Initializes case iterator for given SwitchInst and for given
3284 /// case number.
3285 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3286
3287 /// Initializes case iterator for given SwitchInst and for given
3288 /// successor index.
3289 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3290 unsigned SuccessorIndex) {
3291 assert(SuccessorIndex < SI->getNumSuccessors() &&((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!"
) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3292, __PRETTY_FUNCTION__))
3292 "Successor index # out of range!")((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!"
) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3292, __PRETTY_FUNCTION__))
;
3293 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3294 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3295 }
3296
3297 /// Support converting to the const variant. This will be a no-op for const
3298 /// variant.
3299 operator CaseIteratorImpl<ConstCaseHandle>() const {
3300 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3301 }
3302
3303 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3304 // Check index correctness after addition.
3305 // Note: Index == getNumCases() means end().
3306 assert(Case.Index + N >= 0 &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3308, __PRETTY_FUNCTION__))
3307 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3308, __PRETTY_FUNCTION__))
3308 "Case.Index out the number of cases.")((Case.Index + N >= 0 && (unsigned)(Case.Index + N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3308, __PRETTY_FUNCTION__))
;
3309 Case.Index += N;
3310 return *this;
3311 }
3312 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3313 // Check index correctness after subtraction.
3314 // Note: Case.Index == getNumCases() means end().
3315 assert(Case.Index - N >= 0 &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3317, __PRETTY_FUNCTION__))
3316 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3317, __PRETTY_FUNCTION__))
3317 "Case.Index out the number of cases.")((Case.Index - N >= 0 && (unsigned)(Case.Index - N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3317, __PRETTY_FUNCTION__))
;
3318 Case.Index -= N;
3319 return *this;
3320 }
3321 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3322 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators."
) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3322, __PRETTY_FUNCTION__))
;
3323 return Case.Index - RHS.Case.Index;
3324 }
3325 bool operator==(const CaseIteratorImpl &RHS) const {
3326 return Case == RHS.Case;
3327 }
3328 bool operator<(const CaseIteratorImpl &RHS) const {
3329 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators."
) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3329, __PRETTY_FUNCTION__))
;
3330 return Case.Index < RHS.Case.Index;
3331 }
3332 CaseHandleT &operator*() { return Case; }
3333 const CaseHandleT &operator*() const { return Case; }
3334 };
3335
3336 using CaseIt = CaseIteratorImpl<CaseHandle>;
3337 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3338
3339 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3340 unsigned NumCases,
3341 Instruction *InsertBefore = nullptr) {
3342 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3343 }
3344
3345 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3346 unsigned NumCases, BasicBlock *InsertAtEnd) {
3347 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3348 }
3349
3350 /// Provide fast operand accessors
3351 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
3352
3353 // Accessor Methods for Switch stmt
3354 Value *getCondition() const { return getOperand(0); }
3355 void setCondition(Value *V) { setOperand(0, V); }
3356
3357 BasicBlock *getDefaultDest() const {
3358 return cast<BasicBlock>(getOperand(1));
3359 }
3360
3361 void setDefaultDest(BasicBlock *DefaultCase) {
3362 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3363 }
3364
3365 /// Return the number of 'cases' in this switch instruction, excluding the
3366 /// default case.
3367 unsigned getNumCases() const {
3368 return getNumOperands()/2 - 1;
3369 }
3370
3371 /// Returns a read/write iterator that points to the first case in the
3372 /// SwitchInst.
3373 CaseIt case_begin() {
3374 return CaseIt(this, 0);
3375 }
3376
3377 /// Returns a read-only iterator that points to the first case in the
3378 /// SwitchInst.
3379 ConstCaseIt case_begin() const {
3380 return ConstCaseIt(this, 0);
3381 }
3382
3383 /// Returns a read/write iterator that points one past the last in the
3384 /// SwitchInst.
3385 CaseIt case_end() {
3386 return CaseIt(this, getNumCases());
3387 }
3388
3389 /// Returns a read-only iterator that points one past the last in the
3390 /// SwitchInst.
3391 ConstCaseIt case_end() const {
3392 return ConstCaseIt(this, getNumCases());
3393 }
3394
3395 /// Iteration adapter for range-for loops.
3396 iterator_range<CaseIt> cases() {
3397 return make_range(case_begin(), case_end());
3398 }
3399
3400 /// Constant iteration adapter for range-for loops.
3401 iterator_range<ConstCaseIt> cases() const {
3402 return make_range(case_begin(), case_end());
3403 }
3404
3405 /// Returns an iterator that points to the default case.
3406 /// Note: this iterator allows to resolve successor only. Attempt
3407 /// to resolve case value causes an assertion.
3408 /// Also note, that increment and decrement also causes an assertion and
3409 /// makes iterator invalid.
3410 CaseIt case_default() {
3411 return CaseIt(this, DefaultPseudoIndex);
3412 }
3413 ConstCaseIt case_default() const {
3414 return ConstCaseIt(this, DefaultPseudoIndex);
3415 }
3416
3417 /// Search all of the case values for the specified constant. If it is
3418 /// explicitly handled, return the case iterator of it, otherwise return
3419 /// default case iterator to indicate that it is handled by the default
3420 /// handler.
3421 CaseIt findCaseValue(const ConstantInt *C) {
3422 CaseIt I = llvm::find_if(
3423 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3424 if (I != case_end())
3425 return I;
3426
3427 return case_default();
3428 }
3429 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3430 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3431 return Case.getCaseValue() == C;
3432 });
3433 if (I != case_end())
3434 return I;
3435
3436 return case_default();
3437 }
3438
3439 /// Finds the unique case value for a given successor. Returns null if the
3440 /// successor is not found, not unique, or is the default case.
3441 ConstantInt *findCaseDest(BasicBlock *BB) {
3442 if (BB == getDefaultDest())
3443 return nullptr;
3444
3445 ConstantInt *CI = nullptr;
3446 for (auto Case : cases()) {
3447 if (Case.getCaseSuccessor() != BB)
3448 continue;
3449
3450 if (CI)
3451 return nullptr; // Multiple cases lead to BB.
3452
3453 CI = Case.getCaseValue();
3454 }
3455
3456 return CI;
3457 }
3458
3459 /// Add an entry to the switch instruction.
3460 /// Note:
3461 /// This action invalidates case_end(). Old case_end() iterator will
3462 /// point to the added case.
3463 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3464
3465 /// This method removes the specified case and its successor from the switch
3466 /// instruction. Note that this operation may reorder the remaining cases at
3467 /// index idx and above.
3468 /// Note:
3469 /// This action invalidates iterators for all cases following the one removed,
3470 /// including the case_end() iterator. It returns an iterator for the next
3471 /// case.
3472 CaseIt removeCase(CaseIt I);
3473
3474 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3475 BasicBlock *getSuccessor(unsigned idx) const {
3476 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!")((idx < getNumSuccessors() &&"Successor idx out of range for switch!"
) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() &&\"Successor idx out of range for switch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3476, __PRETTY_FUNCTION__))
;
3477 return cast<BasicBlock>(getOperand(idx*2+1));
3478 }
3479 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3480 assert(idx < getNumSuccessors() && "Successor # out of range for switch!")((idx < getNumSuccessors() && "Successor # out of range for switch!"
) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for switch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3480, __PRETTY_FUNCTION__))
;
3481 setOperand(idx * 2 + 1, NewSucc);
3482 }
3483
3484 // Methods for support type inquiry through isa, cast, and dyn_cast:
3485 static bool classof(const Instruction *I) {
3486 return I->getOpcode() == Instruction::Switch;
3487 }
3488 static bool classof(const Value *V) {
3489 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3490 }
3491};
3492
3493/// A wrapper class to simplify modification of SwitchInst cases along with
3494/// their prof branch_weights metadata.
3495class SwitchInstProfUpdateWrapper {
3496 SwitchInst &SI;
3497 Optional<SmallVector<uint32_t, 8> > Weights = None;
3498 bool Changed = false;
3499
3500protected:
3501 static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
3502
3503 MDNode *buildProfBranchWeightsMD();
3504
3505 void init();
3506
3507public:
3508 using CaseWeightOpt = Optional<uint32_t>;
3509 SwitchInst *operator->() { return &SI; }
3510 SwitchInst &operator*() { return SI; }
3511 operator SwitchInst *() { return &SI; }
3512
3513 SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
3514
3515 ~SwitchInstProfUpdateWrapper() {
3516 if (Changed)
3517 SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
3518 }
3519
3520 /// Delegate the call to the underlying SwitchInst::removeCase() and remove
3521 /// correspondent branch weight.
3522 SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
3523
3524 /// Delegate the call to the underlying SwitchInst::addCase() and set the
3525 /// specified branch weight for the added case.
3526 void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
3527
3528 /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
3529 /// this object to not touch the underlying SwitchInst in destructor.
3530 SymbolTableList<Instruction>::iterator eraseFromParent();
3531
3532 void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
3533 CaseWeightOpt getSuccessorWeight(unsigned idx);
3534
3535 static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
3536};
3537
3538template <>
3539struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3540};
3541
3542DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)SwitchInst::op_iterator SwitchInst::op_begin() { return OperandTraits
<SwitchInst>::op_begin(this); } SwitchInst::const_op_iterator
SwitchInst::op_begin() const { return OperandTraits<SwitchInst
>::op_begin(const_cast<SwitchInst*>(this)); } SwitchInst
::op_iterator SwitchInst::op_end() { return OperandTraits<
SwitchInst>::op_end(this); } SwitchInst::const_op_iterator
SwitchInst::op_end() const { return OperandTraits<SwitchInst
>::op_end(const_cast<SwitchInst*>(this)); } Value *SwitchInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<SwitchInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3542, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<SwitchInst>::op_begin(const_cast<SwitchInst
*>(this))[i_nocapture].get()); } void SwitchInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<SwitchInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3542, __PRETTY_FUNCTION__)); OperandTraits<SwitchInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SwitchInst
::getNumOperands() const { return OperandTraits<SwitchInst
>::operands(this); } template <int Idx_nocapture> Use
&SwitchInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
SwitchInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
3543
3544//===----------------------------------------------------------------------===//
3545// IndirectBrInst Class
3546//===----------------------------------------------------------------------===//
3547
3548//===---------------------------------------------------------------------------
3549/// Indirect Branch Instruction.
3550///
3551class IndirectBrInst : public Instruction {
3552 unsigned ReservedSpace;
3553
3554 // Operand[0] = Address to jump to
3555 // Operand[n+1] = n-th destination
3556 IndirectBrInst(const IndirectBrInst &IBI);
3557
3558 /// Create a new indirectbr instruction, specifying an
3559 /// Address to jump to. The number of expected destinations can be specified
3560 /// here to make memory allocation more efficient. This constructor can also
3561 /// autoinsert before another instruction.
3562 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3563
3564 /// Create a new indirectbr instruction, specifying an
3565 /// Address to jump to. The number of expected destinations can be specified
3566 /// here to make memory allocation more efficient. This constructor also
3567 /// autoinserts at the end of the specified BasicBlock.
3568 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3569
3570 // allocate space for exactly zero operands
3571 void *operator new(size_t s) {
3572 return User::operator new(s);
3573 }
3574
3575 void init(Value *Address, unsigned NumDests);
3576 void growOperands();
3577
3578protected:
3579 // Note: Instruction needs to be a friend here to call cloneImpl.
3580 friend class Instruction;
3581
3582 IndirectBrInst *cloneImpl() const;
3583
3584public:
3585 /// Iterator type that casts an operand to a basic block.
3586 ///
3587 /// This only makes sense because the successors are stored as adjacent
3588 /// operands for indirectbr instructions.
3589 struct succ_op_iterator
3590 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3591 std::random_access_iterator_tag, BasicBlock *,
3592 ptrdiff_t, BasicBlock *, BasicBlock *> {
3593 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3594
3595 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3596 BasicBlock *operator->() const { return operator*(); }
3597 };
3598
3599 /// The const version of `succ_op_iterator`.
3600 struct const_succ_op_iterator
3601 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3602 std::random_access_iterator_tag,
3603 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3604 const BasicBlock *> {
3605 explicit const_succ_op_iterator(const_value_op_iterator I)
3606 : iterator_adaptor_base(I) {}
3607
3608 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3609 const BasicBlock *operator->() const { return operator*(); }
3610 };
3611
3612 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3613 Instruction *InsertBefore = nullptr) {
3614 return new IndirectBrInst(Address, NumDests, InsertBefore);
3615 }
3616
3617 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3618 BasicBlock *InsertAtEnd) {
3619 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3620 }
3621
3622 /// Provide fast operand accessors.
3623 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
3624
3625 // Accessor Methods for IndirectBrInst instruction.
3626 Value *getAddress() { return getOperand(0); }
3627 const Value *getAddress() const { return getOperand(0); }
3628 void setAddress(Value *V) { setOperand(0, V); }
3629
3630 /// return the number of possible destinations in this
3631 /// indirectbr instruction.
3632 unsigned getNumDestinations() const { return getNumOperands()-1; }
3633
3634 /// Return the specified destination.
3635 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3636 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3637
3638 /// Add a destination.
3639 ///
3640 void addDestination(BasicBlock *Dest);
3641
3642 /// This method removes the specified successor from the
3643 /// indirectbr instruction.
3644 void removeDestination(unsigned i);
3645
3646 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3647 BasicBlock *getSuccessor(unsigned i) const {
3648 return cast<BasicBlock>(getOperand(i+1));
3649 }
3650 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3651 setOperand(i + 1, NewSucc);
3652 }
3653
3654 iterator_range<succ_op_iterator> successors() {
3655 return make_range(succ_op_iterator(std::next(value_op_begin())),
3656 succ_op_iterator(value_op_end()));
3657 }
3658
3659 iterator_range<const_succ_op_iterator> successors() const {
3660 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3661 const_succ_op_iterator(value_op_end()));
3662 }
3663
3664 // Methods for support type inquiry through isa, cast, and dyn_cast:
3665 static bool classof(const Instruction *I) {
3666 return I->getOpcode() == Instruction::IndirectBr;
3667 }
3668 static bool classof(const Value *V) {
3669 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3670 }
3671};
3672
3673template <>
3674struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3675};
3676
3677DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)IndirectBrInst::op_iterator IndirectBrInst::op_begin() { return
OperandTraits<IndirectBrInst>::op_begin(this); } IndirectBrInst
::const_op_iterator IndirectBrInst::op_begin() const { return
OperandTraits<IndirectBrInst>::op_begin(const_cast<
IndirectBrInst*>(this)); } IndirectBrInst::op_iterator IndirectBrInst
::op_end() { return OperandTraits<IndirectBrInst>::op_end
(this); } IndirectBrInst::const_op_iterator IndirectBrInst::op_end
() const { return OperandTraits<IndirectBrInst>::op_end
(const_cast<IndirectBrInst*>(this)); } Value *IndirectBrInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<IndirectBrInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3677, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<IndirectBrInst>::op_begin(const_cast<
IndirectBrInst*>(this))[i_nocapture].get()); } void IndirectBrInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<IndirectBrInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3677, __PRETTY_FUNCTION__)); OperandTraits<IndirectBrInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
IndirectBrInst::getNumOperands() const { return OperandTraits
<IndirectBrInst>::operands(this); } template <int Idx_nocapture
> Use &IndirectBrInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &IndirectBrInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
3678
3679//===----------------------------------------------------------------------===//
3680// InvokeInst Class
3681//===----------------------------------------------------------------------===//
3682
3683/// Invoke instruction. The SubclassData field is used to hold the
3684/// calling convention of the call.
3685///
3686class InvokeInst : public CallBase {
3687 /// The number of operands for this call beyond the called function,
3688 /// arguments, and operand bundles.
3689 static constexpr int NumExtraOperands = 2;
3690
3691 /// The index from the end of the operand array to the normal destination.
3692 static constexpr int NormalDestOpEndIdx = -3;
3693
3694 /// The index from the end of the operand array to the unwind destination.
3695 static constexpr int UnwindDestOpEndIdx = -2;
3696
3697 InvokeInst(const InvokeInst &BI);
3698
3699 /// Construct an InvokeInst given a range of arguments.
3700 ///
3701 /// Construct an InvokeInst from a range of arguments
3702 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3703 BasicBlock *IfException, ArrayRef<Value *> Args,
3704 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3705 const Twine &NameStr, Instruction *InsertBefore);
3706
3707 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3708 BasicBlock *IfException, ArrayRef<Value *> Args,
3709 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3710 const Twine &NameStr, BasicBlock *InsertAtEnd);
3711
3712 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3713 BasicBlock *IfException, ArrayRef<Value *> Args,
3714 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3715
3716 /// Compute the number of operands to allocate.
3717 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3718 // We need one operand for the called function, plus our extra operands and
3719 // the input operand counts provided.
3720 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3721 }
3722
3723protected:
3724 // Note: Instruction needs to be a friend here to call cloneImpl.
3725 friend class Instruction;
3726
3727 InvokeInst *cloneImpl() const;
3728
3729public:
3730 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3731 BasicBlock *IfException, ArrayRef<Value *> Args,
3732 const Twine &NameStr,
3733 Instruction *InsertBefore = nullptr) {
3734 int NumOperands = ComputeNumOperands(Args.size());
3735 return new (NumOperands)
3736 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3737 NameStr, InsertBefore);
3738 }
3739
3740 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3741 BasicBlock *IfException, ArrayRef<Value *> Args,
3742 ArrayRef<OperandBundleDef> Bundles = None,
3743 const Twine &NameStr = "",
3744 Instruction *InsertBefore = nullptr) {
3745 int NumOperands =
3746 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3747 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3748
3749 return new (NumOperands, DescriptorBytes)
3750 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3751 NameStr, InsertBefore);
3752 }
3753
3754 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3755 BasicBlock *IfException, ArrayRef<Value *> Args,
3756 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3757 int NumOperands = ComputeNumOperands(Args.size());
3758 return new (NumOperands)
3759 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3760 NameStr, InsertAtEnd);
3761 }
3762
3763 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3764 BasicBlock *IfException, ArrayRef<Value *> Args,
3765 ArrayRef<OperandBundleDef> Bundles,
3766 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3767 int NumOperands =
3768 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3769 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3770
3771 return new (NumOperands, DescriptorBytes)
3772 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3773 NameStr, InsertAtEnd);
3774 }
3775
3776 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3777 BasicBlock *IfException, ArrayRef<Value *> Args,
3778 const Twine &NameStr,
3779 Instruction *InsertBefore = nullptr) {
3780 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3781 IfException, Args, None, NameStr, InsertBefore);
3782 }
3783
3784 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3785 BasicBlock *IfException, ArrayRef<Value *> Args,
3786 ArrayRef<OperandBundleDef> Bundles = None,
3787 const Twine &NameStr = "",
3788 Instruction *InsertBefore = nullptr) {
3789 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3790 IfException, Args, Bundles, NameStr, InsertBefore);
3791 }
3792
3793 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3794 BasicBlock *IfException, ArrayRef<Value *> Args,
3795 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3796 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3797 IfException, Args, NameStr, InsertAtEnd);
3798 }
3799
3800 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3801 BasicBlock *IfException, ArrayRef<Value *> Args,
3802 ArrayRef<OperandBundleDef> Bundles,
3803 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3804 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3805 IfException, Args, Bundles, NameStr, InsertAtEnd);
3806 }
3807
3808 /// Create a clone of \p II with a different set of operand bundles and
3809 /// insert it before \p InsertPt.
3810 ///
3811 /// The returned invoke instruction is identical to \p II in every way except
3812 /// that the operand bundles for the new instruction are set to the operand
3813 /// bundles in \p Bundles.
3814 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3815 Instruction *InsertPt = nullptr);
3816
3817 /// Create a clone of \p II with a different set of operand bundles and
3818 /// insert it before \p InsertPt.
3819 ///
3820 /// The returned invoke instruction is identical to \p II in every way except
3821 /// that the operand bundle for the new instruction is set to the operand
3822 /// bundle in \p Bundle.
3823 static InvokeInst *CreateWithReplacedBundle(InvokeInst *II,
3824 OperandBundleDef Bundles,
3825 Instruction *InsertPt = nullptr);
3826
3827 // get*Dest - Return the destination basic blocks...
3828 BasicBlock *getNormalDest() const {
3829 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3830 }
3831 BasicBlock *getUnwindDest() const {
3832 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3833 }
3834 void setNormalDest(BasicBlock *B) {
3835 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3836 }
3837 void setUnwindDest(BasicBlock *B) {
3838 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3839 }
3840
3841 /// Get the landingpad instruction from the landing pad
3842 /// block (the unwind destination).
3843 LandingPadInst *getLandingPadInst() const;
3844
3845 BasicBlock *getSuccessor(unsigned i) const {
3846 assert(i < 2 && "Successor # out of range for invoke!")((i < 2 && "Successor # out of range for invoke!")
? static_cast<void> (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3846, __PRETTY_FUNCTION__))
;
3847 return i == 0 ? getNormalDest() : getUnwindDest();
3848 }
3849
3850 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3851 assert(i < 2 && "Successor # out of range for invoke!")((i < 2 && "Successor # out of range for invoke!")
? static_cast<void> (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 3851, __PRETTY_FUNCTION__))
;
3852 if (i == 0)
3853 setNormalDest(NewSucc);
3854 else
3855 setUnwindDest(NewSucc);
3856 }
3857
3858 unsigned getNumSuccessors() const { return 2; }
3859
3860 // Methods for support type inquiry through isa, cast, and dyn_cast:
3861 static bool classof(const Instruction *I) {
3862 return (I->getOpcode() == Instruction::Invoke);
3863 }
3864 static bool classof(const Value *V) {
3865 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3866 }
3867
3868private:
3869 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3870 // method so that subclasses cannot accidentally use it.
3871 template <typename Bitfield>
3872 void setSubclassData(typename Bitfield::Type Value) {
3873 Instruction::setSubclassData<Bitfield>(Value);
3874 }
3875};
3876
3877InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3878 BasicBlock *IfException, ArrayRef<Value *> Args,
3879 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3880 const Twine &NameStr, Instruction *InsertBefore)
3881 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3882 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3883 InsertBefore) {
3884 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3885}
3886
3887InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3888 BasicBlock *IfException, ArrayRef<Value *> Args,
3889 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3890 const Twine &NameStr, BasicBlock *InsertAtEnd)
3891 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3892 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3893 InsertAtEnd) {
3894 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3895}
3896
3897//===----------------------------------------------------------------------===//
3898// CallBrInst Class
3899//===----------------------------------------------------------------------===//
3900
3901/// CallBr instruction, tracking function calls that may not return control but
3902/// instead transfer it to a third location. The SubclassData field is used to
3903/// hold the calling convention of the call.
3904///
3905class CallBrInst : public CallBase {
3906
3907 unsigned NumIndirectDests;
3908
3909 CallBrInst(const CallBrInst &BI);
3910
3911 /// Construct a CallBrInst given a range of arguments.
3912 ///
3913 /// Construct a CallBrInst from a range of arguments
3914 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3915 ArrayRef<BasicBlock *> IndirectDests,
3916 ArrayRef<Value *> Args,
3917 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3918 const Twine &NameStr, Instruction *InsertBefore);
3919
3920 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3921 ArrayRef<BasicBlock *> IndirectDests,
3922 ArrayRef<Value *> Args,
3923 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3924 const Twine &NameStr, BasicBlock *InsertAtEnd);
3925
3926 void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3927 ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3928 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3929
3930 /// Should the Indirect Destinations change, scan + update the Arg list.
3931 void updateArgBlockAddresses(unsigned i, BasicBlock *B);
3932
3933 /// Compute the number of operands to allocate.
3934 static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3935 int NumBundleInputs = 0) {
3936 // We need one operand for the called function, plus our extra operands and
3937 // the input operand counts provided.
3938 return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3939 }
3940
3941protected:
3942 // Note: Instruction needs to be a friend here to call cloneImpl.
3943 friend class Instruction;
3944
3945 CallBrInst *cloneImpl() const;
3946
3947public:
3948 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3949 BasicBlock *DefaultDest,
3950 ArrayRef<BasicBlock *> IndirectDests,
3951 ArrayRef<Value *> Args, const Twine &NameStr,
3952 Instruction *InsertBefore = nullptr) {
3953 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3954 return new (NumOperands)
3955 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3956 NumOperands, NameStr, InsertBefore);
3957 }
3958
3959 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3960 BasicBlock *DefaultDest,
3961 ArrayRef<BasicBlock *> IndirectDests,
3962 ArrayRef<Value *> Args,
3963 ArrayRef<OperandBundleDef> Bundles = None,
3964 const Twine &NameStr = "",
3965 Instruction *InsertBefore = nullptr) {
3966 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3967 CountBundleInputs(Bundles));
3968 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3969
3970 return new (NumOperands, DescriptorBytes)
3971 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3972 NumOperands, NameStr, InsertBefore);
3973 }
3974
3975 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3976 BasicBlock *DefaultDest,
3977 ArrayRef<BasicBlock *> IndirectDests,
3978 ArrayRef<Value *> Args, const Twine &NameStr,
3979 BasicBlock *InsertAtEnd) {
3980 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3981 return new (NumOperands)
3982 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3983 NumOperands, NameStr, InsertAtEnd);
3984 }
3985
3986 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3987 BasicBlock *DefaultDest,
3988 ArrayRef<BasicBlock *> IndirectDests,
3989 ArrayRef<Value *> Args,
3990 ArrayRef<OperandBundleDef> Bundles,
3991 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3992 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3993 CountBundleInputs(Bundles));
3994 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3995
3996 return new (NumOperands, DescriptorBytes)
3997 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3998 NumOperands, NameStr, InsertAtEnd);
3999 }
4000
4001 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4002 ArrayRef<BasicBlock *> IndirectDests,
4003 ArrayRef<Value *> Args, const Twine &NameStr,
4004 Instruction *InsertBefore = nullptr) {
4005 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4006 IndirectDests, Args, NameStr, InsertBefore);
4007 }
4008
4009 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4010 ArrayRef<BasicBlock *> IndirectDests,
4011 ArrayRef<Value *> Args,
4012 ArrayRef<OperandBundleDef> Bundles = None,
4013 const Twine &NameStr = "",
4014 Instruction *InsertBefore = nullptr) {
4015 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4016 IndirectDests, Args, Bundles, NameStr, InsertBefore);
4017 }
4018
4019 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4020 ArrayRef<BasicBlock *> IndirectDests,
4021 ArrayRef<Value *> Args, const Twine &NameStr,
4022 BasicBlock *InsertAtEnd) {
4023 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4024 IndirectDests, Args, NameStr, InsertAtEnd);
4025 }
4026
4027 static CallBrInst *Create(FunctionCallee Func,
4028 BasicBlock *DefaultDest,
4029 ArrayRef<BasicBlock *> IndirectDests,
4030 ArrayRef<Value *> Args,
4031 ArrayRef<OperandBundleDef> Bundles,
4032 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4033 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4034 IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4035 }
4036
4037 /// Create a clone of \p CBI with a different set of operand bundles and
4038 /// insert it before \p InsertPt.
4039 ///
4040 /// The returned callbr instruction is identical to \p CBI in every way
4041 /// except that the operand bundles for the new instruction are set to the
4042 /// operand bundles in \p Bundles.
4043 static CallBrInst *Create(CallBrInst *CBI,
4044 ArrayRef<OperandBundleDef> Bundles,
4045 Instruction *InsertPt = nullptr);
4046
4047 /// Return the number of callbr indirect dest labels.
4048 ///
4049 unsigned getNumIndirectDests() const { return NumIndirectDests; }
4050
4051 /// getIndirectDestLabel - Return the i-th indirect dest label.
4052 ///
4053 Value *getIndirectDestLabel(unsigned i) const {
4054 assert(i < getNumIndirectDests() && "Out of bounds!")((i < getNumIndirectDests() && "Out of bounds!") ?
static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4054, __PRETTY_FUNCTION__))
;
4055 return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4056 1);
4057 }
4058
4059 Value *getIndirectDestLabelUse(unsigned i) const {
4060 assert(i < getNumIndirectDests() && "Out of bounds!")((i < getNumIndirectDests() && "Out of bounds!") ?
static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4060, __PRETTY_FUNCTION__))
;
4061 return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4062 1);
4063 }
4064
4065 // Return the destination basic blocks...
4066 BasicBlock *getDefaultDest() const {
4067 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4068 }
4069 BasicBlock *getIndirectDest(unsigned i) const {
4070 return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4071 }
4072 SmallVector<BasicBlock *, 16> getIndirectDests() const {
4073 SmallVector<BasicBlock *, 16> IndirectDests;
4074 for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4075 IndirectDests.push_back(getIndirectDest(i));
4076 return IndirectDests;
4077 }
4078 void setDefaultDest(BasicBlock *B) {
4079 *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4080 }
4081 void setIndirectDest(unsigned i, BasicBlock *B) {
4082 updateArgBlockAddresses(i, B);
4083 *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4084 }
4085
4086 BasicBlock *getSuccessor(unsigned i) const {
4087 assert(i < getNumSuccessors() + 1 &&((i < getNumSuccessors() + 1 && "Successor # out of range for callbr!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4088, __PRETTY_FUNCTION__))
4088 "Successor # out of range for callbr!")((i < getNumSuccessors() + 1 && "Successor # out of range for callbr!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4088, __PRETTY_FUNCTION__))
;
4089 return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4090 }
4091
4092 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4093 assert(i < getNumIndirectDests() + 1 &&((i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4094, __PRETTY_FUNCTION__))
4094 "Successor # out of range for callbr!")((i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4094, __PRETTY_FUNCTION__))
;
4095 return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
4096 }
4097
4098 unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4099
4100 // Methods for support type inquiry through isa, cast, and dyn_cast:
4101 static bool classof(const Instruction *I) {
4102 return (I->getOpcode() == Instruction::CallBr);
4103 }
4104 static bool classof(const Value *V) {
4105 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4106 }
4107
4108private:
4109 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4110 // method so that subclasses cannot accidentally use it.
4111 template <typename Bitfield>
4112 void setSubclassData(typename Bitfield::Type Value) {
4113 Instruction::setSubclassData<Bitfield>(Value);
4114 }
4115};
4116
4117CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4118 ArrayRef<BasicBlock *> IndirectDests,
4119 ArrayRef<Value *> Args,
4120 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4121 const Twine &NameStr, Instruction *InsertBefore)
4122 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4123 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4124 InsertBefore) {
4125 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4126}
4127
4128CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4129 ArrayRef<BasicBlock *> IndirectDests,
4130 ArrayRef<Value *> Args,
4131 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4132 const Twine &NameStr, BasicBlock *InsertAtEnd)
4133 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4134 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4135 InsertAtEnd) {
4136 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4137}
4138
4139//===----------------------------------------------------------------------===//
4140// ResumeInst Class
4141//===----------------------------------------------------------------------===//
4142
4143//===---------------------------------------------------------------------------
4144/// Resume the propagation of an exception.
4145///
4146class ResumeInst : public Instruction {
4147 ResumeInst(const ResumeInst &RI);
4148
4149 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4150 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4151
4152protected:
4153 // Note: Instruction needs to be a friend here to call cloneImpl.
4154 friend class Instruction;
4155
4156 ResumeInst *cloneImpl() const;
4157
4158public:
4159 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4160 return new(1) ResumeInst(Exn, InsertBefore);
4161 }
4162
4163 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4164 return new(1) ResumeInst(Exn, InsertAtEnd);
4165 }
4166
4167 /// Provide fast operand accessors
4168 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
4169
4170 /// Convenience accessor.
4171 Value *getValue() const { return Op<0>(); }
4172
4173 unsigned getNumSuccessors() const { return 0; }
4174
4175 // Methods for support type inquiry through isa, cast, and dyn_cast:
4176 static bool classof(const Instruction *I) {
4177 return I->getOpcode() == Instruction::Resume;
4178 }
4179 static bool classof(const Value *V) {
4180 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4181 }
4182
4183private:
4184 BasicBlock *getSuccessor(unsigned idx) const {
4185 llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4185)
;
4186 }
4187
4188 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4189 llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4189)
;
4190 }
4191};
4192
4193template <>
4194struct OperandTraits<ResumeInst> :
4195 public FixedNumOperandTraits<ResumeInst, 1> {
4196};
4197
4198DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)ResumeInst::op_iterator ResumeInst::op_begin() { return OperandTraits
<ResumeInst>::op_begin(this); } ResumeInst::const_op_iterator
ResumeInst::op_begin() const { return OperandTraits<ResumeInst
>::op_begin(const_cast<ResumeInst*>(this)); } ResumeInst
::op_iterator ResumeInst::op_end() { return OperandTraits<
ResumeInst>::op_end(this); } ResumeInst::const_op_iterator
ResumeInst::op_end() const { return OperandTraits<ResumeInst
>::op_end(const_cast<ResumeInst*>(this)); } Value *ResumeInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<ResumeInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4198, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ResumeInst>::op_begin(const_cast<ResumeInst
*>(this))[i_nocapture].get()); } void ResumeInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<ResumeInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4198, __PRETTY_FUNCTION__)); OperandTraits<ResumeInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ResumeInst
::getNumOperands() const { return OperandTraits<ResumeInst
>::operands(this); } template <int Idx_nocapture> Use
&ResumeInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
ResumeInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
4199
4200//===----------------------------------------------------------------------===//
4201// CatchSwitchInst Class
4202//===----------------------------------------------------------------------===//
4203class CatchSwitchInst : public Instruction {
4204 using UnwindDestField = BoolBitfieldElementT<0>;
4205
4206 /// The number of operands actually allocated. NumOperands is
4207 /// the number actually in use.
4208 unsigned ReservedSpace;
4209
4210 // Operand[0] = Outer scope
4211 // Operand[1] = Unwind block destination
4212 // Operand[n] = BasicBlock to go to on match
4213 CatchSwitchInst(const CatchSwitchInst &CSI);
4214
4215 /// Create a new switch instruction, specifying a
4216 /// default destination. The number of additional handlers can be specified
4217 /// here to make memory allocation more efficient.
4218 /// This constructor can also autoinsert before another instruction.
4219 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4220 unsigned NumHandlers, const Twine &NameStr,
4221 Instruction *InsertBefore);
4222
4223 /// Create a new switch instruction, specifying a
4224 /// default destination. The number of additional handlers can be specified
4225 /// here to make memory allocation more efficient.
4226 /// This constructor also autoinserts at the end of the specified BasicBlock.
4227 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4228 unsigned NumHandlers, const Twine &NameStr,
4229 BasicBlock *InsertAtEnd);
4230
4231 // allocate space for exactly zero operands
4232 void *operator new(size_t s) { return User::operator new(s); }
4233
4234 void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved);
4235 void growOperands(unsigned Size);
4236
4237protected:
4238 // Note: Instruction needs to be a friend here to call cloneImpl.
4239 friend class Instruction;
4240
4241 CatchSwitchInst *cloneImpl() const;
4242
4243public:
4244 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4245 unsigned NumHandlers,
4246 const Twine &NameStr = "",
4247 Instruction *InsertBefore = nullptr) {
4248 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4249 InsertBefore);
4250 }
4251
4252 static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest,
4253 unsigned NumHandlers, const Twine &NameStr,
4254 BasicBlock *InsertAtEnd) {
4255 return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr,
4256 InsertAtEnd);
4257 }
4258
4259 /// Provide fast operand accessors
4260 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
4261
4262 // Accessor Methods for CatchSwitch stmt
4263 Value *getParentPad() const { return getOperand(0); }
4264 void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); }
4265
4266 // Accessor Methods for CatchSwitch stmt
4267 bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); }
4268 bool unwindsToCaller() const { return !hasUnwindDest(); }
4269 BasicBlock *getUnwindDest() const {
4270 if (hasUnwindDest())
4271 return cast<BasicBlock>(getOperand(1));
4272 return nullptr;
4273 }
4274 void setUnwindDest(BasicBlock *UnwindDest) {
4275 assert(UnwindDest)((UnwindDest) ? static_cast<void> (0) : __assert_fail (
"UnwindDest", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4275, __PRETTY_FUNCTION__))
;
4276 assert(hasUnwindDest())((hasUnwindDest()) ? static_cast<void> (0) : __assert_fail
("hasUnwindDest()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4276, __PRETTY_FUNCTION__))
;
4277 setOperand(1, UnwindDest);
4278 }
4279
4280 /// return the number of 'handlers' in this catchswitch
4281 /// instruction, except the default handler
4282 unsigned getNumHandlers() const {
4283 if (hasUnwindDest())
4284 return getNumOperands() - 2;
4285 return getNumOperands() - 1;
4286 }
4287
4288private:
4289 static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); }
4290 static const BasicBlock *handler_helper(const Value *V) {
4291 return cast<BasicBlock>(V);
4292 }
4293
4294public:
4295 using DerefFnTy = BasicBlock *(*)(Value *);
4296 using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>;
4297 using handler_range = iterator_range<handler_iterator>;
4298 using ConstDerefFnTy = const BasicBlock *(*)(const Value *);
4299 using const_handler_iterator =
4300 mapped_iterator<const_op_iterator, ConstDerefFnTy>;
4301 using const_handler_range = iterator_range<const_handler_iterator>;
4302
4303 /// Returns an iterator that points to the first handler in CatchSwitchInst.
4304 handler_iterator handler_begin() {
4305 op_iterator It = op_begin() + 1;
4306 if (hasUnwindDest())
4307 ++It;
4308 return handler_iterator(It, DerefFnTy(handler_helper));
4309 }
4310
4311 /// Returns an iterator that points to the first handler in the
4312 /// CatchSwitchInst.
4313 const_handler_iterator handler_begin() const {
4314 const_op_iterator It = op_begin() + 1;
4315 if (hasUnwindDest())
4316 ++It;
4317 return const_handler_iterator(It, ConstDerefFnTy(handler_helper));
4318 }
4319
4320 /// Returns a read-only iterator that points one past the last
4321 /// handler in the CatchSwitchInst.
4322 handler_iterator handler_end() {
4323 return handler_iterator(op_end(), DerefFnTy(handler_helper));
4324 }
4325
4326 /// Returns an iterator that points one past the last handler in the
4327 /// CatchSwitchInst.
4328 const_handler_iterator handler_end() const {
4329 return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper));
4330 }
4331
4332 /// iteration adapter for range-for loops.
4333 handler_range handlers() {
4334 return make_range(handler_begin(), handler_end());
4335 }
4336
4337 /// iteration adapter for range-for loops.
4338 const_handler_range handlers() const {
4339 return make_range(handler_begin(), handler_end());
4340 }
4341
4342 /// Add an entry to the switch instruction...
4343 /// Note:
4344 /// This action invalidates handler_end(). Old handler_end() iterator will
4345 /// point to the added handler.
4346 void addHandler(BasicBlock *Dest);
4347
4348 void removeHandler(handler_iterator HI);
4349
4350 unsigned getNumSuccessors() const { return getNumOperands() - 1; }
4351 BasicBlock *getSuccessor(unsigned Idx) const {
4352 assert(Idx < getNumSuccessors() &&((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4353, __PRETTY_FUNCTION__))
4353 "Successor # out of range for catchswitch!")((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4353, __PRETTY_FUNCTION__))
;
4354 return cast<BasicBlock>(getOperand(Idx + 1));
4355 }
4356 void setSuccessor(unsigned Idx, BasicBlock *NewSucc) {
4357 assert(Idx < getNumSuccessors() &&((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4358, __PRETTY_FUNCTION__))
4358 "Successor # out of range for catchswitch!")((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4358, __PRETTY_FUNCTION__))
;
4359 setOperand(Idx + 1, NewSucc);
4360 }
4361
4362 // Methods for support type inquiry through isa, cast, and dyn_cast:
4363 static bool classof(const Instruction *I) {
4364 return I->getOpcode() == Instruction::CatchSwitch;
4365 }
4366 static bool classof(const Value *V) {
4367 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4368 }
4369};
4370
4371template <>
4372struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {};
4373
4374DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)CatchSwitchInst::op_iterator CatchSwitchInst::op_begin() { return
OperandTraits<CatchSwitchInst>::op_begin(this); } CatchSwitchInst
::const_op_iterator CatchSwitchInst::op_begin() const { return
OperandTraits<CatchSwitchInst>::op_begin(const_cast<
CatchSwitchInst*>(this)); } CatchSwitchInst::op_iterator CatchSwitchInst
::op_end() { return OperandTraits<CatchSwitchInst>::op_end
(this); } CatchSwitchInst::const_op_iterator CatchSwitchInst::
op_end() const { return OperandTraits<CatchSwitchInst>::
op_end(const_cast<CatchSwitchInst*>(this)); } Value *CatchSwitchInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<CatchSwitchInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4374, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<CatchSwitchInst>::op_begin(const_cast<
CatchSwitchInst*>(this))[i_nocapture].get()); } void CatchSwitchInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<CatchSwitchInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4374, __PRETTY_FUNCTION__)); OperandTraits<CatchSwitchInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
CatchSwitchInst::getNumOperands() const { return OperandTraits
<CatchSwitchInst>::operands(this); } template <int Idx_nocapture
> Use &CatchSwitchInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &CatchSwitchInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
4375
4376//===----------------------------------------------------------------------===//
4377// CleanupPadInst Class
4378//===----------------------------------------------------------------------===//
4379class CleanupPadInst : public FuncletPadInst {
4380private:
4381 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4382 unsigned Values, const Twine &NameStr,
4383 Instruction *InsertBefore)
4384 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4385 NameStr, InsertBefore) {}
4386 explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args,
4387 unsigned Values, const Twine &NameStr,
4388 BasicBlock *InsertAtEnd)
4389 : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values,
4390 NameStr, InsertAtEnd) {}
4391
4392public:
4393 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None,
4394 const Twine &NameStr = "",
4395 Instruction *InsertBefore = nullptr) {
4396 unsigned Values = 1 + Args.size();
4397 return new (Values)
4398 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore);
4399 }
4400
4401 static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args,
4402 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4403 unsigned Values = 1 + Args.size();
4404 return new (Values)
4405 CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd);
4406 }
4407
4408 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4409 static bool classof(const Instruction *I) {
4410 return I->getOpcode() == Instruction::CleanupPad;
4411 }
4412 static bool classof(const Value *V) {
4413 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4414 }
4415};
4416
4417//===----------------------------------------------------------------------===//
4418// CatchPadInst Class
4419//===----------------------------------------------------------------------===//
4420class CatchPadInst : public FuncletPadInst {
4421private:
4422 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4423 unsigned Values, const Twine &NameStr,
4424 Instruction *InsertBefore)
4425 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4426 NameStr, InsertBefore) {}
4427 explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args,
4428 unsigned Values, const Twine &NameStr,
4429 BasicBlock *InsertAtEnd)
4430 : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values,
4431 NameStr, InsertAtEnd) {}
4432
4433public:
4434 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4435 const Twine &NameStr = "",
4436 Instruction *InsertBefore = nullptr) {
4437 unsigned Values = 1 + Args.size();
4438 return new (Values)
4439 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore);
4440 }
4441
4442 static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args,
4443 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4444 unsigned Values = 1 + Args.size();
4445 return new (Values)
4446 CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd);
4447 }
4448
4449 /// Convenience accessors
4450 CatchSwitchInst *getCatchSwitch() const {
4451 return cast<CatchSwitchInst>(Op<-1>());
4452 }
4453 void setCatchSwitch(Value *CatchSwitch) {
4454 assert(CatchSwitch)((CatchSwitch) ? static_cast<void> (0) : __assert_fail (
"CatchSwitch", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4454, __PRETTY_FUNCTION__))
;
4455 Op<-1>() = CatchSwitch;
4456 }
4457
4458 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4459 static bool classof(const Instruction *I) {
4460 return I->getOpcode() == Instruction::CatchPad;
4461 }
4462 static bool classof(const Value *V) {
4463 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4464 }
4465};
4466
4467//===----------------------------------------------------------------------===//
4468// CatchReturnInst Class
4469//===----------------------------------------------------------------------===//
4470
4471class CatchReturnInst : public Instruction {
4472 CatchReturnInst(const CatchReturnInst &RI);
4473 CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore);
4474 CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd);
4475
4476 void init(Value *CatchPad, BasicBlock *BB);
4477
4478protected:
4479 // Note: Instruction needs to be a friend here to call cloneImpl.
4480 friend class Instruction;
4481
4482 CatchReturnInst *cloneImpl() const;
4483
4484public:
4485 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4486 Instruction *InsertBefore = nullptr) {
4487 assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4487, __PRETTY_FUNCTION__))
;
4488 assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4488, __PRETTY_FUNCTION__))
;
4489 return new (2) CatchReturnInst(CatchPad, BB, InsertBefore);
4490 }
4491
4492 static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB,
4493 BasicBlock *InsertAtEnd) {
4494 assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4494, __PRETTY_FUNCTION__))
;
4495 assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4495, __PRETTY_FUNCTION__))
;
4496 return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd);
4497 }
4498
4499 /// Provide fast operand accessors
4500 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
4501
4502 /// Convenience accessors.
4503 CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); }
4504 void setCatchPad(CatchPadInst *CatchPad) {
4505 assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4505, __PRETTY_FUNCTION__))
;
4506 Op<0>() = CatchPad;
4507 }
4508
4509 BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); }
4510 void setSuccessor(BasicBlock *NewSucc) {
4511 assert(NewSucc)((NewSucc) ? static_cast<void> (0) : __assert_fail ("NewSucc"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4511, __PRETTY_FUNCTION__))
;
4512 Op<1>() = NewSucc;
4513 }
4514 unsigned getNumSuccessors() const { return 1; }
4515
4516 /// Get the parentPad of this catchret's catchpad's catchswitch.
4517 /// The successor block is implicitly a member of this funclet.
4518 Value *getCatchSwitchParentPad() const {
4519 return getCatchPad()->getCatchSwitch()->getParentPad();
4520 }
4521
4522 // Methods for support type inquiry through isa, cast, and dyn_cast:
4523 static bool classof(const Instruction *I) {
4524 return (I->getOpcode() == Instruction::CatchRet);
4525 }
4526 static bool classof(const Value *V) {
4527 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4528 }
4529
4530private:
4531 BasicBlock *getSuccessor(unsigned Idx) const {
4532 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")((Idx < getNumSuccessors() && "Successor # out of range for catchret!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4532, __PRETTY_FUNCTION__))
;
4533 return getSuccessor();
4534 }
4535
4536 void setSuccessor(unsigned Idx, BasicBlock *B) {
4537 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")((Idx < getNumSuccessors() && "Successor # out of range for catchret!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4537, __PRETTY_FUNCTION__))
;
4538 setSuccessor(B);
4539 }
4540};
4541
4542template <>
4543struct OperandTraits<CatchReturnInst>
4544 : public FixedNumOperandTraits<CatchReturnInst, 2> {};
4545
4546DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)CatchReturnInst::op_iterator CatchReturnInst::op_begin() { return
OperandTraits<CatchReturnInst>::op_begin(this); } CatchReturnInst
::const_op_iterator CatchReturnInst::op_begin() const { return
OperandTraits<CatchReturnInst>::op_begin(const_cast<
CatchReturnInst*>(this)); } CatchReturnInst::op_iterator CatchReturnInst
::op_end() { return OperandTraits<CatchReturnInst>::op_end
(this); } CatchReturnInst::const_op_iterator CatchReturnInst::
op_end() const { return OperandTraits<CatchReturnInst>::
op_end(const_cast<CatchReturnInst*>(this)); } Value *CatchReturnInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<CatchReturnInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4546, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<CatchReturnInst>::op_begin(const_cast<
CatchReturnInst*>(this))[i_nocapture].get()); } void CatchReturnInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<CatchReturnInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4546, __PRETTY_FUNCTION__)); OperandTraits<CatchReturnInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
CatchReturnInst::getNumOperands() const { return OperandTraits
<CatchReturnInst>::operands(this); } template <int Idx_nocapture
> Use &CatchReturnInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &CatchReturnInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
4547
4548//===----------------------------------------------------------------------===//
4549// CleanupReturnInst Class
4550//===----------------------------------------------------------------------===//
4551
4552class CleanupReturnInst : public Instruction {
4553 using UnwindDestField = BoolBitfieldElementT<0>;
4554
4555private:
4556 CleanupReturnInst(const CleanupReturnInst &RI);
4557 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4558 Instruction *InsertBefore = nullptr);
4559 CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values,
4560 BasicBlock *InsertAtEnd);
4561
4562 void init(Value *CleanupPad, BasicBlock *UnwindBB);
4563
4564protected:
4565 // Note: Instruction needs to be a friend here to call cloneImpl.
4566 friend class Instruction;
4567
4568 CleanupReturnInst *cloneImpl() const;
4569
4570public:
4571 static CleanupReturnInst *Create(Value *CleanupPad,
4572 BasicBlock *UnwindBB = nullptr,
4573 Instruction *InsertBefore = nullptr) {
4574 assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail (
"CleanupPad", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4574, __PRETTY_FUNCTION__))
;
4575 unsigned Values = 1;
4576 if (UnwindBB)
4577 ++Values;
4578 return new (Values)
4579 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore);
4580 }
4581
4582 static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB,
4583 BasicBlock *InsertAtEnd) {
4584 assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail (
"CleanupPad", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4584, __PRETTY_FUNCTION__))
;
4585 unsigned Values = 1;
4586 if (UnwindBB)
4587 ++Values;
4588 return new (Values)
4589 CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd);
4590 }
4591
4592 /// Provide fast operand accessors
4593 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
4594
4595 bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); }
4596 bool unwindsToCaller() const { return !hasUnwindDest(); }
4597
4598 /// Convenience accessor.
4599 CleanupPadInst *getCleanupPad() const {
4600 return cast<CleanupPadInst>(Op<0>());
4601 }
4602 void setCleanupPad(CleanupPadInst *CleanupPad) {
4603 assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail (
"CleanupPad", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4603, __PRETTY_FUNCTION__))
;
4604 Op<0>() = CleanupPad;
4605 }
4606
4607 unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; }
4608
4609 BasicBlock *getUnwindDest() const {
4610 return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr;
4611 }
4612 void setUnwindDest(BasicBlock *NewDest) {
4613 assert(NewDest)((NewDest) ? static_cast<void> (0) : __assert_fail ("NewDest"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4613, __PRETTY_FUNCTION__))
;
4614 assert(hasUnwindDest())((hasUnwindDest()) ? static_cast<void> (0) : __assert_fail
("hasUnwindDest()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4614, __PRETTY_FUNCTION__))
;
4615 Op<1>() = NewDest;
4616 }
4617
4618 // Methods for support type inquiry through isa, cast, and dyn_cast:
4619 static bool classof(const Instruction *I) {
4620 return (I->getOpcode() == Instruction::CleanupRet);
4621 }
4622 static bool classof(const Value *V) {
4623 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4624 }
4625
4626private:
4627 BasicBlock *getSuccessor(unsigned Idx) const {
4628 assert(Idx == 0)((Idx == 0) ? static_cast<void> (0) : __assert_fail ("Idx == 0"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4628, __PRETTY_FUNCTION__))
;
4629 return getUnwindDest();
4630 }
4631
4632 void setSuccessor(unsigned Idx, BasicBlock *B) {
4633 assert(Idx == 0)((Idx == 0) ? static_cast<void> (0) : __assert_fail ("Idx == 0"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4633, __PRETTY_FUNCTION__))
;
4634 setUnwindDest(B);
4635 }
4636
4637 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4638 // method so that subclasses cannot accidentally use it.
4639 template <typename Bitfield>
4640 void setSubclassData(typename Bitfield::Type Value) {
4641 Instruction::setSubclassData<Bitfield>(Value);
4642 }
4643};
4644
4645template <>
4646struct OperandTraits<CleanupReturnInst>
4647 : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {};
4648
4649DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)CleanupReturnInst::op_iterator CleanupReturnInst::op_begin() {
return OperandTraits<CleanupReturnInst>::op_begin(this
); } CleanupReturnInst::const_op_iterator CleanupReturnInst::
op_begin() const { return OperandTraits<CleanupReturnInst>
::op_begin(const_cast<CleanupReturnInst*>(this)); } CleanupReturnInst
::op_iterator CleanupReturnInst::op_end() { return OperandTraits
<CleanupReturnInst>::op_end(this); } CleanupReturnInst::
const_op_iterator CleanupReturnInst::op_end() const { return OperandTraits
<CleanupReturnInst>::op_end(const_cast<CleanupReturnInst
*>(this)); } Value *CleanupReturnInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<CleanupReturnInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4649, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<CleanupReturnInst>::op_begin(const_cast
<CleanupReturnInst*>(this))[i_nocapture].get()); } void
CleanupReturnInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<CleanupReturnInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4649, __PRETTY_FUNCTION__)); OperandTraits<CleanupReturnInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
CleanupReturnInst::getNumOperands() const { return OperandTraits
<CleanupReturnInst>::operands(this); } template <int
Idx_nocapture> Use &CleanupReturnInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &CleanupReturnInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
4650
4651//===----------------------------------------------------------------------===//
4652// UnreachableInst Class
4653//===----------------------------------------------------------------------===//
4654
4655//===---------------------------------------------------------------------------
4656/// This function has undefined behavior. In particular, the
4657/// presence of this instruction indicates some higher level knowledge that the
4658/// end of the block cannot be reached.
4659///
4660class UnreachableInst : public Instruction {
4661protected:
4662 // Note: Instruction needs to be a friend here to call cloneImpl.
4663 friend class Instruction;
4664
4665 UnreachableInst *cloneImpl() const;
4666
4667public:
4668 explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr);
4669 explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
4670
4671 // allocate space for exactly zero operands
4672 void *operator new(size_t s) {
4673 return User::operator new(s, 0);
4674 }
4675
4676 unsigned getNumSuccessors() const { return 0; }
4677
4678 // Methods for support type inquiry through isa, cast, and dyn_cast:
4679 static bool classof(const Instruction *I) {
4680 return I->getOpcode() == Instruction::Unreachable;
4681 }
4682 static bool classof(const Value *V) {
4683 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4684 }
4685
4686private:
4687 BasicBlock *getSuccessor(unsigned idx) const {
4688 llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4688)
;
4689 }
4690
4691 void setSuccessor(unsigned idx, BasicBlock *B) {
4692 llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 4692)
;
4693 }
4694};
4695
4696//===----------------------------------------------------------------------===//
4697// TruncInst Class
4698//===----------------------------------------------------------------------===//
4699
4700/// This class represents a truncation of integer types.
4701class TruncInst : public CastInst {
4702protected:
4703 // Note: Instruction needs to be a friend here to call cloneImpl.
4704 friend class Instruction;
4705
4706 /// Clone an identical TruncInst
4707 TruncInst *cloneImpl() const;
4708
4709public:
4710 /// Constructor with insert-before-instruction semantics
4711 TruncInst(
4712 Value *S, ///< The value to be truncated
4713 Type *Ty, ///< The (smaller) type to truncate to
4714 const Twine &NameStr = "", ///< A name for the new instruction
4715 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4716 );
4717
4718 /// Constructor with insert-at-end-of-block semantics
4719 TruncInst(
4720 Value *S, ///< The value to be truncated
4721 Type *Ty, ///< The (smaller) type to truncate to
4722 const Twine &NameStr, ///< A name for the new instruction
4723 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4724 );
4725
4726 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4727 static bool classof(const Instruction *I) {
4728 return I->getOpcode() == Trunc;
4729 }
4730 static bool classof(const Value *V) {
4731 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4732 }
4733};
4734
4735//===----------------------------------------------------------------------===//
4736// ZExtInst Class
4737//===----------------------------------------------------------------------===//
4738
4739/// This class represents zero extension of integer types.
4740class ZExtInst : public CastInst {
4741protected:
4742 // Note: Instruction needs to be a friend here to call cloneImpl.
4743 friend class Instruction;
4744
4745 /// Clone an identical ZExtInst
4746 ZExtInst *cloneImpl() const;
4747
4748public:
4749 /// Constructor with insert-before-instruction semantics
4750 ZExtInst(
4751 Value *S, ///< The value to be zero extended
4752 Type *Ty, ///< The type to zero extend to
4753 const Twine &NameStr = "", ///< A name for the new instruction
4754 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4755 );
4756
4757 /// Constructor with insert-at-end semantics.
4758 ZExtInst(
4759 Value *S, ///< The value to be zero extended
4760 Type *Ty, ///< The type to zero extend to
4761 const Twine &NameStr, ///< A name for the new instruction
4762 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4763 );
4764
4765 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4766 static bool classof(const Instruction *I) {
4767 return I->getOpcode() == ZExt;
4768 }
4769 static bool classof(const Value *V) {
4770 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4771 }
4772};
4773
4774//===----------------------------------------------------------------------===//
4775// SExtInst Class
4776//===----------------------------------------------------------------------===//
4777
4778/// This class represents a sign extension of integer types.
4779class SExtInst : public CastInst {
4780protected:
4781 // Note: Instruction needs to be a friend here to call cloneImpl.
4782 friend class Instruction;
4783
4784 /// Clone an identical SExtInst
4785 SExtInst *cloneImpl() const;
4786
4787public:
4788 /// Constructor with insert-before-instruction semantics
4789 SExtInst(
4790 Value *S, ///< The value to be sign extended
4791 Type *Ty, ///< The type to sign extend to
4792 const Twine &NameStr = "", ///< A name for the new instruction
4793 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4794 );
4795
4796 /// Constructor with insert-at-end-of-block semantics
4797 SExtInst(
4798 Value *S, ///< The value to be sign extended
4799 Type *Ty, ///< The type to sign extend to
4800 const Twine &NameStr, ///< A name for the new instruction
4801 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4802 );
4803
4804 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4805 static bool classof(const Instruction *I) {
4806 return I->getOpcode() == SExt;
4807 }
4808 static bool classof(const Value *V) {
4809 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4810 }
4811};
4812
4813//===----------------------------------------------------------------------===//
4814// FPTruncInst Class
4815//===----------------------------------------------------------------------===//
4816
4817/// This class represents a truncation of floating point types.
4818class FPTruncInst : public CastInst {
4819protected:
4820 // Note: Instruction needs to be a friend here to call cloneImpl.
4821 friend class Instruction;
4822
4823 /// Clone an identical FPTruncInst
4824 FPTruncInst *cloneImpl() const;
4825
4826public:
4827 /// Constructor with insert-before-instruction semantics
4828 FPTruncInst(
4829 Value *S, ///< The value to be truncated
4830 Type *Ty, ///< The type to truncate to
4831 const Twine &NameStr = "", ///< A name for the new instruction
4832 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4833 );
4834
4835 /// Constructor with insert-before-instruction semantics
4836 FPTruncInst(
4837 Value *S, ///< The value to be truncated
4838 Type *Ty, ///< The type to truncate to
4839 const Twine &NameStr, ///< A name for the new instruction
4840 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4841 );
4842
4843 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4844 static bool classof(const Instruction *I) {
4845 return I->getOpcode() == FPTrunc;
4846 }
4847 static bool classof(const Value *V) {
4848 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4849 }
4850};
4851
4852//===----------------------------------------------------------------------===//
4853// FPExtInst Class
4854//===----------------------------------------------------------------------===//
4855
4856/// This class represents an extension of floating point types.
4857class FPExtInst : public CastInst {
4858protected:
4859 // Note: Instruction needs to be a friend here to call cloneImpl.
4860 friend class Instruction;
4861
4862 /// Clone an identical FPExtInst
4863 FPExtInst *cloneImpl() const;
4864
4865public:
4866 /// Constructor with insert-before-instruction semantics
4867 FPExtInst(
4868 Value *S, ///< The value to be extended
4869 Type *Ty, ///< The type to extend to
4870 const Twine &NameStr = "", ///< A name for the new instruction
4871 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4872 );
4873
4874 /// Constructor with insert-at-end-of-block semantics
4875 FPExtInst(
4876 Value *S, ///< The value to be extended
4877 Type *Ty, ///< The type to extend to
4878 const Twine &NameStr, ///< A name for the new instruction
4879 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4880 );
4881
4882 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4883 static bool classof(const Instruction *I) {
4884 return I->getOpcode() == FPExt;
4885 }
4886 static bool classof(const Value *V) {
4887 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4888 }
4889};
4890
4891//===----------------------------------------------------------------------===//
4892// UIToFPInst Class
4893//===----------------------------------------------------------------------===//
4894
4895/// This class represents a cast unsigned integer to floating point.
4896class UIToFPInst : public CastInst {
4897protected:
4898 // Note: Instruction needs to be a friend here to call cloneImpl.
4899 friend class Instruction;
4900
4901 /// Clone an identical UIToFPInst
4902 UIToFPInst *cloneImpl() const;
4903
4904public:
4905 /// Constructor with insert-before-instruction semantics
4906 UIToFPInst(
4907 Value *S, ///< The value to be converted
4908 Type *Ty, ///< The type to convert to
4909 const Twine &NameStr = "", ///< A name for the new instruction
4910 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4911 );
4912
4913 /// Constructor with insert-at-end-of-block semantics
4914 UIToFPInst(
4915 Value *S, ///< The value to be converted
4916 Type *Ty, ///< The type to convert to
4917 const Twine &NameStr, ///< A name for the new instruction
4918 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4919 );
4920
4921 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4922 static bool classof(const Instruction *I) {
4923 return I->getOpcode() == UIToFP;
4924 }
4925 static bool classof(const Value *V) {
4926 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4927 }
4928};
4929
4930//===----------------------------------------------------------------------===//
4931// SIToFPInst Class
4932//===----------------------------------------------------------------------===//
4933
4934/// This class represents a cast from signed integer to floating point.
4935class SIToFPInst : public CastInst {
4936protected:
4937 // Note: Instruction needs to be a friend here to call cloneImpl.
4938 friend class Instruction;
4939
4940 /// Clone an identical SIToFPInst
4941 SIToFPInst *cloneImpl() const;
4942
4943public:
4944 /// Constructor with insert-before-instruction semantics
4945 SIToFPInst(
4946 Value *S, ///< The value to be converted
4947 Type *Ty, ///< The type to convert to
4948 const Twine &NameStr = "", ///< A name for the new instruction
4949 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4950 );
4951
4952 /// Constructor with insert-at-end-of-block semantics
4953 SIToFPInst(
4954 Value *S, ///< The value to be converted
4955 Type *Ty, ///< The type to convert to
4956 const Twine &NameStr, ///< A name for the new instruction
4957 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
4958 );
4959
4960 /// Methods for support type inquiry through isa, cast, and dyn_cast:
4961 static bool classof(const Instruction *I) {
4962 return I->getOpcode() == SIToFP;
4963 }
4964 static bool classof(const Value *V) {
4965 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4966 }
4967};
4968
4969//===----------------------------------------------------------------------===//
4970// FPToUIInst Class
4971//===----------------------------------------------------------------------===//
4972
4973/// This class represents a cast from floating point to unsigned integer
4974class FPToUIInst : public CastInst {
4975protected:
4976 // Note: Instruction needs to be a friend here to call cloneImpl.
4977 friend class Instruction;
4978
4979 /// Clone an identical FPToUIInst
4980 FPToUIInst *cloneImpl() const;
4981
4982public:
4983 /// Constructor with insert-before-instruction semantics
4984 FPToUIInst(
4985 Value *S, ///< The value to be converted
4986 Type *Ty, ///< The type to convert to
4987 const Twine &NameStr = "", ///< A name for the new instruction
4988 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
4989 );
4990
4991 /// Constructor with insert-at-end-of-block semantics
4992 FPToUIInst(
4993 Value *S, ///< The value to be converted
4994 Type *Ty, ///< The type to convert to
4995 const Twine &NameStr, ///< A name for the new instruction
4996 BasicBlock *InsertAtEnd ///< Where to insert the new instruction
4997 );
4998
4999 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5000 static bool classof(const Instruction *I) {
5001 return I->getOpcode() == FPToUI;
5002 }
5003 static bool classof(const Value *V) {
5004 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5005 }
5006};
5007
5008//===----------------------------------------------------------------------===//
5009// FPToSIInst Class
5010//===----------------------------------------------------------------------===//
5011
5012/// This class represents a cast from floating point to signed integer.
5013class FPToSIInst : public CastInst {
5014protected:
5015 // Note: Instruction needs to be a friend here to call cloneImpl.
5016 friend class Instruction;
5017
5018 /// Clone an identical FPToSIInst
5019 FPToSIInst *cloneImpl() const;
5020
5021public:
5022 /// Constructor with insert-before-instruction semantics
5023 FPToSIInst(
5024 Value *S, ///< The value to be converted
5025 Type *Ty, ///< The type to convert to
5026 const Twine &NameStr = "", ///< A name for the new instruction
5027 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5028 );
5029
5030 /// Constructor with insert-at-end-of-block semantics
5031 FPToSIInst(
5032 Value *S, ///< The value to be converted
5033 Type *Ty, ///< The type to convert to
5034 const Twine &NameStr, ///< A name for the new instruction
5035 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5036 );
5037
5038 /// Methods for support type inquiry through isa, cast, and dyn_cast:
5039 static bool classof(const Instruction *I) {
5040 return I->getOpcode() == FPToSI;
5041 }
5042 static bool classof(const Value *V) {
5043 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5044 }
5045};
5046
5047//===----------------------------------------------------------------------===//
5048// IntToPtrInst Class
5049//===----------------------------------------------------------------------===//
5050
5051/// This class represents a cast from an integer to a pointer.
5052class IntToPtrInst : public CastInst {
5053public:
5054 // Note: Instruction needs to be a friend here to call cloneImpl.
5055 friend class Instruction;
5056
5057 /// Constructor with insert-before-instruction semantics
5058 IntToPtrInst(
5059 Value *S, ///< The value to be converted
5060 Type *Ty, ///< The type to convert to
5061 const Twine &NameStr = "", ///< A name for the new instruction
5062 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5063 );
5064
5065 /// Constructor with insert-at-end-of-block semantics
5066 IntToPtrInst(
5067 Value *S, ///< The value to be converted
5068 Type *Ty, ///< The type to convert to
5069 const Twine &NameStr, ///< A name for the new instruction
5070 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5071 );
5072
5073 /// Clone an identical IntToPtrInst.
5074 IntToPtrInst *cloneImpl() const;
5075
5076 /// Returns the address space of this instruction's pointer type.
5077 unsigned getAddressSpace() const {
5078 return getType()->getPointerAddressSpace();
5079 }
5080
5081 // Methods for support type inquiry through isa, cast, and dyn_cast:
5082 static bool classof(const Instruction *I) {
5083 return I->getOpcode() == IntToPtr;
5084 }
5085 static bool classof(const Value *V) {
5086 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5087 }
5088};
5089
5090//===----------------------------------------------------------------------===//
5091// PtrToIntInst Class
5092//===----------------------------------------------------------------------===//
5093
5094/// This class represents a cast from a pointer to an integer.
5095class PtrToIntInst : public CastInst {
5096protected:
5097 // Note: Instruction needs to be a friend here to call cloneImpl.
5098 friend class Instruction;
5099
5100 /// Clone an identical PtrToIntInst.
5101 PtrToIntInst *cloneImpl() const;
5102
5103public:
5104 /// Constructor with insert-before-instruction semantics
5105 PtrToIntInst(
5106 Value *S, ///< The value to be converted
5107 Type *Ty, ///< The type to convert to
5108 const Twine &NameStr = "", ///< A name for the new instruction
5109 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5110 );
5111
5112 /// Constructor with insert-at-end-of-block semantics
5113 PtrToIntInst(
5114 Value *S, ///< The value to be converted
5115 Type *Ty, ///< The type to convert to
5116 const Twine &NameStr, ///< A name for the new instruction
5117 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5118 );
5119
5120 /// Gets the pointer operand.
5121 Value *getPointerOperand() { return getOperand(0); }
5122 /// Gets the pointer operand.
5123 const Value *getPointerOperand() const { return getOperand(0); }
5124 /// Gets the operand index of the pointer operand.
5125 static unsigned getPointerOperandIndex() { return 0U; }
5126
5127 /// Returns the address space of the pointer operand.
5128 unsigned getPointerAddressSpace() const {
5129 return getPointerOperand()->getType()->getPointerAddressSpace();
5130 }
5131
5132 // Methods for support type inquiry through isa, cast, and dyn_cast:
5133 static bool classof(const Instruction *I) {
5134 return I->getOpcode() == PtrToInt;
5135 }
5136 static bool classof(const Value *V) {
5137 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5138 }
5139};
5140
5141//===----------------------------------------------------------------------===//
5142// BitCastInst Class
5143//===----------------------------------------------------------------------===//
5144
5145/// This class represents a no-op cast from one type to another.
5146class BitCastInst : public CastInst {
5147protected:
5148 // Note: Instruction needs to be a friend here to call cloneImpl.
5149 friend class Instruction;
5150
5151 /// Clone an identical BitCastInst.
5152 BitCastInst *cloneImpl() const;
5153
5154public:
5155 /// Constructor with insert-before-instruction semantics
5156 BitCastInst(
5157 Value *S, ///< The value to be casted
5158 Type *Ty, ///< The type to casted to
5159 const Twine &NameStr = "", ///< A name for the new instruction
5160 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5161 );
5162
5163 /// Constructor with insert-at-end-of-block semantics
5164 BitCastInst(
5165 Value *S, ///< The value to be casted
5166 Type *Ty, ///< The type to casted to
5167 const Twine &NameStr, ///< A name for the new instruction
5168 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5169 );
5170
5171 // Methods for support type inquiry through isa, cast, and dyn_cast:
5172 static bool classof(const Instruction *I) {
5173 return I->getOpcode() == BitCast;
5174 }
5175 static bool classof(const Value *V) {
5176 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5177 }
5178};
5179
5180//===----------------------------------------------------------------------===//
5181// AddrSpaceCastInst Class
5182//===----------------------------------------------------------------------===//
5183
5184/// This class represents a conversion between pointers from one address space
5185/// to another.
5186class AddrSpaceCastInst : public CastInst {
5187protected:
5188 // Note: Instruction needs to be a friend here to call cloneImpl.
5189 friend class Instruction;
5190
5191 /// Clone an identical AddrSpaceCastInst.
5192 AddrSpaceCastInst *cloneImpl() const;
5193
5194public:
5195 /// Constructor with insert-before-instruction semantics
5196 AddrSpaceCastInst(
5197 Value *S, ///< The value to be casted
5198 Type *Ty, ///< The type to casted to
5199 const Twine &NameStr = "", ///< A name for the new instruction
5200 Instruction *InsertBefore = nullptr ///< Where to insert the new instruction
5201 );
5202
5203 /// Constructor with insert-at-end-of-block semantics
5204 AddrSpaceCastInst(
5205 Value *S, ///< The value to be casted
5206 Type *Ty, ///< The type to casted to
5207 const Twine &NameStr, ///< A name for the new instruction
5208 BasicBlock *InsertAtEnd ///< The block to insert the instruction into
5209 );
5210
5211 // Methods for support type inquiry through isa, cast, and dyn_cast:
5212 static bool classof(const Instruction *I) {
5213 return I->getOpcode() == AddrSpaceCast;
5214 }
5215 static bool classof(const Value *V) {
5216 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5217 }
5218
5219 /// Gets the pointer operand.
5220 Value *getPointerOperand() {
5221 return getOperand(0);
5222 }
5223
5224 /// Gets the pointer operand.
5225 const Value *getPointerOperand() const {
5226 return getOperand(0);
5227 }
5228
5229 /// Gets the operand index of the pointer operand.
5230 static unsigned getPointerOperandIndex() {
5231 return 0U;
5232 }
5233
5234 /// Returns the address space of the pointer operand.
5235 unsigned getSrcAddressSpace() const {
5236 return getPointerOperand()->getType()->getPointerAddressSpace();
5237 }
5238
5239 /// Returns the address space of the result.
5240 unsigned getDestAddressSpace() const {
5241 return getType()->getPointerAddressSpace();
5242 }
5243};
5244
5245/// A helper function that returns the pointer operand of a load or store
5246/// instruction. Returns nullptr if not load or store.
5247inline const Value *getLoadStorePointerOperand(const Value *V) {
5248 if (auto *Load = dyn_cast<LoadInst>(V))
5249 return Load->getPointerOperand();
5250 if (auto *Store = dyn_cast<StoreInst>(V))
5251 return Store->getPointerOperand();
5252 return nullptr;
5253}
5254inline Value *getLoadStorePointerOperand(Value *V) {
5255 return const_cast<Value *>(
5256 getLoadStorePointerOperand(static_cast<const Value *>(V)));
5257}
5258
5259/// A helper function that returns the pointer operand of a load, store
5260/// or GEP instruction. Returns nullptr if not load, store, or GEP.
5261inline const Value *getPointerOperand(const Value *V) {
5262 if (auto *Ptr = getLoadStorePointerOperand(V))
5263 return Ptr;
5264 if (auto *Gep = dyn_cast<GetElementPtrInst>(V))
5265 return Gep->getPointerOperand();
5266 return nullptr;
5267}
5268inline Value *getPointerOperand(Value *V) {
5269 return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V)));
5270}
5271
5272/// A helper function that returns the alignment of load or store instruction.
5273inline Align getLoadStoreAlignment(Value *I) {
5274 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
"Expected Load or Store instruction") ? static_cast<void>
(0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 5275, __PRETTY_FUNCTION__))
5275 "Expected Load or Store instruction")(((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
"Expected Load or Store instruction") ? static_cast<void>
(0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 5275, __PRETTY_FUNCTION__))
;
5276 if (auto *LI = dyn_cast<LoadInst>(I))
5277 return LI->getAlign();
5278 return cast<StoreInst>(I)->getAlign();
5279}
5280
5281/// A helper function that returns the address space of the pointer operand of
5282/// load or store instruction.
5283inline unsigned getLoadStoreAddressSpace(Value *I) {
5284 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
"Expected Load or Store instruction") ? static_cast<void>
(0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 5285, __PRETTY_FUNCTION__))
5285 "Expected Load or Store instruction")(((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
"Expected Load or Store instruction") ? static_cast<void>
(0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/IR/Instructions.h"
, 5285, __PRETTY_FUNCTION__))
;
5286 if (auto *LI = dyn_cast<LoadInst>(I))
5287 return LI->getPointerAddressSpace();
5288 return cast<StoreInst>(I)->getPointerAddressSpace();
5289}
5290
5291//===----------------------------------------------------------------------===//
5292// FreezeInst Class
5293//===----------------------------------------------------------------------===//
5294
5295/// This class represents a freeze function that returns random concrete
5296/// value if an operand is either a poison value or an undef value
5297class FreezeInst : public UnaryInstruction {
5298protected:
5299 // Note: Instruction needs to be a friend here to call cloneImpl.
5300 friend class Instruction;
5301
5302 /// Clone an identical FreezeInst
5303 FreezeInst *cloneImpl() const;
5304
5305public:
5306 explicit FreezeInst(Value *S,
5307 const Twine &NameStr = "",
5308 Instruction *InsertBefore = nullptr);
5309 FreezeInst(Value *S, const Twine &NameStr, BasicBlock *InsertAtEnd);
5310
5311 // Methods for support type inquiry through isa, cast, and dyn_cast:
5312 static inline bool classof(const Instruction *I) {
5313 return I->getOpcode() == Freeze;
5314 }
5315 static inline bool classof(const Value *V) {
5316 return isa<Instruction>(V) && classof(cast<Instruction>(V));
5317 }
5318};
5319
5320} // end namespace llvm
5321
5322#endif // LLVM_IR_INSTRUCTIONS_H

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/ilist_iterator.h

1//===- llvm/ADT/ilist_iterator.h - Intrusive List Iterator ------*- 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#ifndef LLVM_ADT_ILIST_ITERATOR_H
10#define LLVM_ADT_ILIST_ITERATOR_H
11
12#include "llvm/ADT/ilist_node.h"
13#include <cassert>
14#include <cstddef>
15#include <iterator>
16#include <type_traits>
17
18namespace llvm {
19
20namespace ilist_detail {
21
22/// Find const-correct node types.
23template <class OptionsT, bool IsConst> struct IteratorTraits;
24template <class OptionsT> struct IteratorTraits<OptionsT, false> {
25 using value_type = typename OptionsT::value_type;
26 using pointer = typename OptionsT::pointer;
27 using reference = typename OptionsT::reference;
28 using node_pointer = ilist_node_impl<OptionsT> *;
29 using node_reference = ilist_node_impl<OptionsT> &;
30};
31template <class OptionsT> struct IteratorTraits<OptionsT, true> {
32 using value_type = const typename OptionsT::value_type;
33 using pointer = typename OptionsT::const_pointer;
34 using reference = typename OptionsT::const_reference;
35 using node_pointer = const ilist_node_impl<OptionsT> *;
36 using node_reference = const ilist_node_impl<OptionsT> &;
37};
38
39template <bool IsReverse> struct IteratorHelper;
40template <> struct IteratorHelper<false> : ilist_detail::NodeAccess {
41 using Access = ilist_detail::NodeAccess;
42
43 template <class T> static void increment(T *&I) { I = Access::getNext(*I); }
44 template <class T> static void decrement(T *&I) { I = Access::getPrev(*I); }
45};
46template <> struct IteratorHelper<true> : ilist_detail::NodeAccess {
47 using Access = ilist_detail::NodeAccess;
48
49 template <class T> static void increment(T *&I) { I = Access::getPrev(*I); }
50 template <class T> static void decrement(T *&I) { I = Access::getNext(*I); }
51};
52
53} // end namespace ilist_detail
54
55/// Iterator for intrusive lists based on ilist_node.
56template <class OptionsT, bool IsReverse, bool IsConst>
57class ilist_iterator : ilist_detail::SpecificNodeAccess<OptionsT> {
58 friend ilist_iterator<OptionsT, IsReverse, !IsConst>;
59 friend ilist_iterator<OptionsT, !IsReverse, IsConst>;
60 friend ilist_iterator<OptionsT, !IsReverse, !IsConst>;
61
62 using Traits = ilist_detail::IteratorTraits<OptionsT, IsConst>;
63 using Access = ilist_detail::SpecificNodeAccess<OptionsT>;
64
65public:
66 using value_type = typename Traits::value_type;
67 using pointer = typename Traits::pointer;
68 using reference = typename Traits::reference;
69 using difference_type = ptrdiff_t;
70 using iterator_category = std::bidirectional_iterator_tag;
71 using const_pointer = typename OptionsT::const_pointer;
72 using const_reference = typename OptionsT::const_reference;
73
74private:
75 using node_pointer = typename Traits::node_pointer;
76 using node_reference = typename Traits::node_reference;
77
78 node_pointer NodePtr = nullptr;
79
80public:
81 /// Create from an ilist_node.
82 explicit ilist_iterator(node_reference N) : NodePtr(&N) {}
83
84 explicit ilist_iterator(pointer NP) : NodePtr(Access::getNodePtr(NP)) {}
85 explicit ilist_iterator(reference NR) : NodePtr(Access::getNodePtr(&NR)) {}
86 ilist_iterator() = default;
87
88 // This is templated so that we can allow constructing a const iterator from
89 // a nonconst iterator...
90 template <bool RHSIsConst>
91 ilist_iterator(const ilist_iterator<OptionsT, IsReverse, RHSIsConst> &RHS,
92 std::enable_if_t<IsConst || !RHSIsConst, void *> = nullptr)
93 : NodePtr(RHS.NodePtr) {}
94
95 // This is templated so that we can allow assigning to a const iterator from
96 // a nonconst iterator...
97 template <bool RHSIsConst>
98 std::enable_if_t<IsConst || !RHSIsConst, ilist_iterator &>
99 operator=(const ilist_iterator<OptionsT, IsReverse, RHSIsConst> &RHS) {
100 NodePtr = RHS.NodePtr;
101 return *this;
102 }
103
104 /// Explicit conversion between forward/reverse iterators.
105 ///
106 /// Translate between forward and reverse iterators without changing range
107 /// boundaries. The resulting iterator will dereference (and have a handle)
108 /// to the previous node, which is somewhat unexpected; but converting the
109 /// two endpoints in a range will give the same range in reverse.
110 ///
111 /// This matches std::reverse_iterator conversions.
112 explicit ilist_iterator(
113 const ilist_iterator<OptionsT, !IsReverse, IsConst> &RHS)
114 : ilist_iterator(++RHS.getReverse()) {}
115
116 /// Get a reverse iterator to the same node.
117 ///
118 /// Gives a reverse iterator that will dereference (and have a handle) to the
119 /// same node. Converting the endpoint iterators in a range will give a
120 /// different range; for range operations, use the explicit conversions.
121 ilist_iterator<OptionsT, !IsReverse, IsConst> getReverse() const {
122 if (NodePtr)
123 return ilist_iterator<OptionsT, !IsReverse, IsConst>(*NodePtr);
124 return ilist_iterator<OptionsT, !IsReverse, IsConst>();
125 }
126
127 /// Const-cast.
128 ilist_iterator<OptionsT, IsReverse, false> getNonConst() const {
129 if (NodePtr)
130 return ilist_iterator<OptionsT, IsReverse, false>(
131 const_cast<typename ilist_iterator<OptionsT, IsReverse,
132 false>::node_reference>(*NodePtr));
133 return ilist_iterator<OptionsT, IsReverse, false>();
134 }
135
136 // Accessors...
137 reference operator*() const {
138 assert(!NodePtr->isKnownSentinel())((!NodePtr->isKnownSentinel()) ? static_cast<void> (
0) : __assert_fail ("!NodePtr->isKnownSentinel()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/ilist_iterator.h"
, 138, __PRETTY_FUNCTION__))
;
139 return *Access::getValuePtr(NodePtr);
140 }
141 pointer operator->() const { return &operator*(); }
142
143 // Comparison operators
144 friend bool operator==(const ilist_iterator &LHS, const ilist_iterator &RHS) {
145 return LHS.NodePtr == RHS.NodePtr;
146 }
147 friend bool operator!=(const ilist_iterator &LHS, const ilist_iterator &RHS) {
148 return LHS.NodePtr != RHS.NodePtr;
19
Assuming 'LHS.NodePtr' is equal to 'RHS.NodePtr'
20
Returning zero, which participates in a condition later
149 }
150
151 // Increment and decrement operators...
152 ilist_iterator &operator--() {
153 NodePtr = IsReverse ? NodePtr->getNext() : NodePtr->getPrev();
154 return *this;
155 }
156 ilist_iterator &operator++() {
157 NodePtr = IsReverse ? NodePtr->getPrev() : NodePtr->getNext();
158 return *this;
159 }
160 ilist_iterator operator--(int) {
161 ilist_iterator tmp = *this;
162 --*this;
163 return tmp;
164 }
165 ilist_iterator operator++(int) {
166 ilist_iterator tmp = *this;
167 ++*this;
168 return tmp;
169 }
170
171 /// Get the underlying ilist_node.
172 node_pointer getNodePtr() const { return static_cast<node_pointer>(NodePtr); }
173
174 /// Check for end. Only valid if ilist_sentinel_tracking<true>.
175 bool isEnd() const { return NodePtr ? NodePtr->isSentinel() : false; }
176};
177
178template <typename From> struct simplify_type;
179
180/// Allow ilist_iterators to convert into pointers to a node automatically when
181/// used by the dyn_cast, cast, isa mechanisms...
182///
183/// FIXME: remove this, since there is no implicit conversion to NodeTy.
184template <class OptionsT, bool IsConst>
185struct simplify_type<ilist_iterator<OptionsT, false, IsConst>> {
186 using iterator = ilist_iterator<OptionsT, false, IsConst>;
187 using SimpleType = typename iterator::pointer;
188
189 static SimpleType getSimplifiedValue(const iterator &Node) { return &*Node; }
190};
191template <class OptionsT, bool IsConst>
192struct simplify_type<const ilist_iterator<OptionsT, false, IsConst>>
193 : simplify_type<ilist_iterator<OptionsT, false, IsConst>> {};
194
195} // end namespace llvm
196
197#endif // LLVM_ADT_ILIST_ITERATOR_H

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h

1//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the SmallVector class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_SMALLVECTOR_H
14#define LLVM_ADT_SMALLVECTOR_H
15
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/ErrorHandling.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Support/MemAlloc.h"
21#include "llvm/Support/type_traits.h"
22#include <algorithm>
23#include <cassert>
24#include <cstddef>
25#include <cstdlib>
26#include <cstring>
27#include <initializer_list>
28#include <iterator>
29#include <limits>
30#include <memory>
31#include <new>
32#include <type_traits>
33#include <utility>
34
35namespace llvm {
36
37/// This is all the stuff common to all SmallVectors.
38///
39/// The template parameter specifies the type which should be used to hold the
40/// Size and Capacity of the SmallVector, so it can be adjusted.
41/// Using 32 bit size is desirable to shrink the size of the SmallVector.
42/// Using 64 bit size is desirable for cases like SmallVector<char>, where a
43/// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
44/// buffering bitcode output - which can exceed 4GB.
45template <class Size_T> class SmallVectorBase {
46protected:
47 void *BeginX;
48 Size_T Size = 0, Capacity;
49
50 /// The maximum value of the Size_T used.
51 static constexpr size_t SizeTypeMax() {
52 return std::numeric_limits<Size_T>::max();
53 }
54
55 SmallVectorBase() = delete;
56 SmallVectorBase(void *FirstEl, size_t TotalCapacity)
57 : BeginX(FirstEl), Capacity(TotalCapacity) {}
58
59 /// This is an implementation of the grow() method which only works
60 /// on POD-like data types and is out of line to reduce code duplication.
61 /// This function will report a fatal error if it cannot increase capacity.
62 void grow_pod(void *FirstEl, size_t MinSize, size_t TSize);
63
64 /// Report that MinSize doesn't fit into this vector's size type. Throws
65 /// std::length_error or calls report_fatal_error.
66 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) static void report_size_overflow(size_t MinSize);
67 /// Report that this vector is already at maximum capacity. Throws
68 /// std::length_error or calls report_fatal_error.
69 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) static void report_at_maximum_capacity();
70
71public:
72 size_t size() const { return Size; }
73 size_t capacity() const { return Capacity; }
74
75 LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { return !Size; }
25
Assuming field 'Size' is not equal to 0, which participates in a condition later
26
Returning zero, which participates in a condition later
76
77 /// Set the array size to \p N, which the current array must have enough
78 /// capacity for.
79 ///
80 /// This does not construct or destroy any elements in the vector.
81 ///
82 /// Clients can use this in conjunction with capacity() to write past the end
83 /// of the buffer when they know that more elements are available, and only
84 /// update the size later. This avoids the cost of value initializing elements
85 /// which will only be overwritten.
86 void set_size(size_t N) {
87 assert(N <= capacity())((N <= capacity()) ? static_cast<void> (0) : __assert_fail
("N <= capacity()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 87, __PRETTY_FUNCTION__))
;
88 Size = N;
89 }
90};
91
92template <class T>
93using SmallVectorSizeType =
94 typename std::conditional<sizeof(T) < 4 && sizeof(void *) >= 8, uint64_t,
95 uint32_t>::type;
96
97/// Figure out the offset of the first element.
98template <class T, typename = void> struct SmallVectorAlignmentAndSize {
99 alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof(
100 SmallVectorBase<SmallVectorSizeType<T>>)];
101 alignas(T) char FirstEl[sizeof(T)];
102};
103
104/// This is the part of SmallVectorTemplateBase which does not depend on whether
105/// the type T is a POD. The extra dummy template argument is used by ArrayRef
106/// to avoid unnecessarily requiring T to be complete.
107template <typename T, typename = void>
108class SmallVectorTemplateCommon
109 : public SmallVectorBase<SmallVectorSizeType<T>> {
110 using Base = SmallVectorBase<SmallVectorSizeType<T>>;
111
112 /// Find the address of the first element. For this pointer math to be valid
113 /// with small-size of 0 for T with lots of alignment, it's important that
114 /// SmallVectorStorage is properly-aligned even for small-size of 0.
115 void *getFirstEl() const {
116 return const_cast<void *>(reinterpret_cast<const void *>(
117 reinterpret_cast<const char *>(this) +
118 offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)__builtin_offsetof(SmallVectorAlignmentAndSize<T>, FirstEl
)
));
119 }
120 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
121
122protected:
123 SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {}
124
125 void grow_pod(size_t MinSize, size_t TSize) {
126 Base::grow_pod(getFirstEl(), MinSize, TSize);
127 }
128
129 /// Return true if this is a smallvector which has not had dynamic
130 /// memory allocated for it.
131 bool isSmall() const { return this->BeginX == getFirstEl(); }
132
133 /// Put this vector in a state of being small.
134 void resetToSmall() {
135 this->BeginX = getFirstEl();
136 this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
137 }
138
139public:
140 using size_type = size_t;
141 using difference_type = ptrdiff_t;
142 using value_type = T;
143 using iterator = T *;
144 using const_iterator = const T *;
145
146 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
147 using reverse_iterator = std::reverse_iterator<iterator>;
148
149 using reference = T &;
150 using const_reference = const T &;
151 using pointer = T *;
152 using const_pointer = const T *;
153
154 using Base::capacity;
155 using Base::empty;
156 using Base::size;
157
158 // forward iterator creation methods.
159 iterator begin() { return (iterator)this->BeginX; }
160 const_iterator begin() const { return (const_iterator)this->BeginX; }
161 iterator end() { return begin() + size(); }
162 const_iterator end() const { return begin() + size(); }
163
164 // reverse iterator creation methods.
165 reverse_iterator rbegin() { return reverse_iterator(end()); }
166 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
167 reverse_iterator rend() { return reverse_iterator(begin()); }
168 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
169
170 size_type size_in_bytes() const { return size() * sizeof(T); }
171 size_type max_size() const {
172 return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T));
173 }
174
175 size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
176
177 /// Return a pointer to the vector's buffer, even if empty().
178 pointer data() { return pointer(begin()); }
179 /// Return a pointer to the vector's buffer, even if empty().
180 const_pointer data() const { return const_pointer(begin()); }
181
182 reference operator[](size_type idx) {
183 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 183, __PRETTY_FUNCTION__))
;
184 return begin()[idx];
185 }
186 const_reference operator[](size_type idx) const {
187 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 187, __PRETTY_FUNCTION__))
;
188 return begin()[idx];
189 }
190
191 reference front() {
192 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 192, __PRETTY_FUNCTION__))
;
193 return begin()[0];
194 }
195 const_reference front() const {
196 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 196, __PRETTY_FUNCTION__))
;
197 return begin()[0];
198 }
199
200 reference back() {
201 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 201, __PRETTY_FUNCTION__))
;
202 return end()[-1];
203 }
204 const_reference back() const {
205 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 205, __PRETTY_FUNCTION__))
;
206 return end()[-1];
207 }
208};
209
210/// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put
211/// method implementations that are designed to work with non-trivial T's.
212///
213/// We approximate is_trivially_copyable with trivial move/copy construction and
214/// trivial destruction. While the standard doesn't specify that you're allowed
215/// copy these types with memcpy, there is no way for the type to observe this.
216/// This catches the important case of std::pair<POD, POD>, which is not
217/// trivially assignable.
218template <typename T, bool = (is_trivially_copy_constructible<T>::value) &&
219 (is_trivially_move_constructible<T>::value) &&
220 std::is_trivially_destructible<T>::value>
221class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
222protected:
223 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
224
225 static void destroy_range(T *S, T *E) {
226 while (S != E) {
227 --E;
228 E->~T();
229 }
230 }
231
232 /// Move the range [I, E) into the uninitialized memory starting with "Dest",
233 /// constructing elements as needed.
234 template<typename It1, typename It2>
235 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
236 std::uninitialized_copy(std::make_move_iterator(I),
237 std::make_move_iterator(E), Dest);
238 }
239
240 /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
241 /// constructing elements as needed.
242 template<typename It1, typename It2>
243 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
244 std::uninitialized_copy(I, E, Dest);
245 }
246
247 /// Grow the allocated memory (without initializing new elements), doubling
248 /// the size of the allocated memory. Guarantees space for at least one more
249 /// element, or MinSize more elements if specified.
250 void grow(size_t MinSize = 0);
251
252public:
253 void push_back(const T &Elt) {
254 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
255 this->grow();
256 ::new ((void*) this->end()) T(Elt);
257 this->set_size(this->size() + 1);
258 }
259
260 void push_back(T &&Elt) {
261 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
262 this->grow();
263 ::new ((void*) this->end()) T(::std::move(Elt));
264 this->set_size(this->size() + 1);
265 }
266
267 void pop_back() {
268 this->set_size(this->size() - 1);
269 this->end()->~T();
270 }
271};
272
273// Define this out-of-line to dissuade the C++ compiler from inlining it.
274template <typename T, bool TriviallyCopyable>
275void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
276 // Ensure we can fit the new capacity.
277 // This is only going to be applicable when the capacity is 32 bit.
278 if (MinSize > this->SizeTypeMax())
279 this->report_size_overflow(MinSize);
280
281 // Ensure we can meet the guarantee of space for at least one more element.
282 // The above check alone will not catch the case where grow is called with a
283 // default MinSize of 0, but the current capacity cannot be increased.
284 // This is only going to be applicable when the capacity is 32 bit.
285 if (this->capacity() == this->SizeTypeMax())
286 this->report_at_maximum_capacity();
287
288 // Always grow, even from zero.
289 size_t NewCapacity = size_t(NextPowerOf2(this->capacity() + 2));
290 NewCapacity = std::min(std::max(NewCapacity, MinSize), this->SizeTypeMax());
291 T *NewElts = static_cast<T*>(llvm::safe_malloc(NewCapacity*sizeof(T)));
292
293 // Move the elements over.
294 this->uninitialized_move(this->begin(), this->end(), NewElts);
295
296 // Destroy the original elements.
297 destroy_range(this->begin(), this->end());
298
299 // If this wasn't grown from the inline copy, deallocate the old space.
300 if (!this->isSmall())
301 free(this->begin());
302
303 this->BeginX = NewElts;
304 this->Capacity = NewCapacity;
305}
306
307/// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
308/// method implementations that are designed to work with trivially copyable
309/// T's. This allows using memcpy in place of copy/move construction and
310/// skipping destruction.
311template <typename T>
312class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
313protected:
314 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
315
316 // No need to do a destroy loop for POD's.
317 static void destroy_range(T *, T *) {}
318
319 /// Move the range [I, E) onto the uninitialized memory
320 /// starting with "Dest", constructing elements into it as needed.
321 template<typename It1, typename It2>
322 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
323 // Just do a copy.
324 uninitialized_copy(I, E, Dest);
325 }
326
327 /// Copy the range [I, E) onto the uninitialized memory
328 /// starting with "Dest", constructing elements into it as needed.
329 template<typename It1, typename It2>
330 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
331 // Arbitrary iterator types; just use the basic implementation.
332 std::uninitialized_copy(I, E, Dest);
333 }
334
335 /// Copy the range [I, E) onto the uninitialized memory
336 /// starting with "Dest", constructing elements into it as needed.
337 template <typename T1, typename T2>
338 static void uninitialized_copy(
339 T1 *I, T1 *E, T2 *Dest,
340 std::enable_if_t<std::is_same<typename std::remove_const<T1>::type,
341 T2>::value> * = nullptr) {
342 // Use memcpy for PODs iterated by pointers (which includes SmallVector
343 // iterators): std::uninitialized_copy optimizes to memmove, but we can
344 // use memcpy here. Note that I and E are iterators and thus might be
345 // invalid for memcpy if they are equal.
346 if (I != E)
347 memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T));
348 }
349
350 /// Double the size of the allocated memory, guaranteeing space for at
351 /// least one more element or MinSize if specified.
352 void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
353
354public:
355 void push_back(const T &Elt) {
356 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
357 this->grow();
358 memcpy(reinterpret_cast<void *>(this->end()), &Elt, sizeof(T));
359 this->set_size(this->size() + 1);
360 }
361
362 void pop_back() { this->set_size(this->size() - 1); }
363};
364
365/// This class consists of common code factored out of the SmallVector class to
366/// reduce code duplication based on the SmallVector 'N' template parameter.
367template <typename T>
368class SmallVectorImpl : public SmallVectorTemplateBase<T> {
369 using SuperClass = SmallVectorTemplateBase<T>;
370
371public:
372 using iterator = typename SuperClass::iterator;
373 using const_iterator = typename SuperClass::const_iterator;
374 using reference = typename SuperClass::reference;
375 using size_type = typename SuperClass::size_type;
376
377protected:
378 // Default ctor - Initialize to empty.
379 explicit SmallVectorImpl(unsigned N)
380 : SmallVectorTemplateBase<T>(N) {}
381
382public:
383 SmallVectorImpl(const SmallVectorImpl &) = delete;
384
385 ~SmallVectorImpl() {
386 // Subclass has already destructed this vector's elements.
387 // If this wasn't grown from the inline copy, deallocate the old space.
388 if (!this->isSmall())
389 free(this->begin());
390 }
391
392 void clear() {
393 this->destroy_range(this->begin(), this->end());
394 this->Size = 0;
395 }
396
397 void resize(size_type N) {
398 if (N < this->size()) {
399 this->destroy_range(this->begin()+N, this->end());
400 this->set_size(N);
401 } else if (N > this->size()) {
402 if (this->capacity() < N)
403 this->grow(N);
404 for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
405 new (&*I) T();
406 this->set_size(N);
407 }
408 }
409
410 void resize(size_type N, const T &NV) {
411 if (N < this->size()) {
412 this->destroy_range(this->begin()+N, this->end());
413 this->set_size(N);
414 } else if (N > this->size()) {
415 if (this->capacity() < N)
416 this->grow(N);
417 std::uninitialized_fill(this->end(), this->begin()+N, NV);
418 this->set_size(N);
419 }
420 }
421
422 void reserve(size_type N) {
423 if (this->capacity() < N)
424 this->grow(N);
425 }
426
427 LLVM_NODISCARD[[clang::warn_unused_result]] T pop_back_val() {
428 T Result = ::std::move(this->back());
429 this->pop_back();
430 return Result;
431 }
432
433 void swap(SmallVectorImpl &RHS);
434
435 /// Add the specified range to the end of the SmallVector.
436 template <typename in_iter,
437 typename = std::enable_if_t<std::is_convertible<
438 typename std::iterator_traits<in_iter>::iterator_category,
439 std::input_iterator_tag>::value>>
440 void append(in_iter in_start, in_iter in_end) {
441 size_type NumInputs = std::distance(in_start, in_end);
442 if (NumInputs > this->capacity() - this->size())
443 this->grow(this->size()+NumInputs);
444
445 this->uninitialized_copy(in_start, in_end, this->end());
446 this->set_size(this->size() + NumInputs);
447 }
448
449 /// Append \p NumInputs copies of \p Elt to the end.
450 void append(size_type NumInputs, const T &Elt) {
451 if (NumInputs > this->capacity() - this->size())
452 this->grow(this->size()+NumInputs);
453
454 std::uninitialized_fill_n(this->end(), NumInputs, Elt);
455 this->set_size(this->size() + NumInputs);
456 }
457
458 void append(std::initializer_list<T> IL) {
459 append(IL.begin(), IL.end());
460 }
461
462 // FIXME: Consider assigning over existing elements, rather than clearing &
463 // re-initializing them - for all assign(...) variants.
464
465 void assign(size_type NumElts, const T &Elt) {
466 clear();
467 if (this->capacity() < NumElts)
468 this->grow(NumElts);
469 this->set_size(NumElts);
470 std::uninitialized_fill(this->begin(), this->end(), Elt);
471 }
472
473 template <typename in_iter,
474 typename = std::enable_if_t<std::is_convertible<
475 typename std::iterator_traits<in_iter>::iterator_category,
476 std::input_iterator_tag>::value>>
477 void assign(in_iter in_start, in_iter in_end) {
478 clear();
479 append(in_start, in_end);
480 }
481
482 void assign(std::initializer_list<T> IL) {
483 clear();
484 append(IL);
485 }
486
487 iterator erase(const_iterator CI) {
488 // Just cast away constness because this is a non-const member function.
489 iterator I = const_cast<iterator>(CI);
490
491 assert(I >= this->begin() && "Iterator to erase is out of bounds.")((I >= this->begin() && "Iterator to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Iterator to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 491, __PRETTY_FUNCTION__))
;
492 assert(I < this->end() && "Erasing at past-the-end iterator.")((I < this->end() && "Erasing at past-the-end iterator."
) ? static_cast<void> (0) : __assert_fail ("I < this->end() && \"Erasing at past-the-end iterator.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 492, __PRETTY_FUNCTION__))
;
493
494 iterator N = I;
495 // Shift all elts down one.
496 std::move(I+1, this->end(), I);
497 // Drop the last elt.
498 this->pop_back();
499 return(N);
500 }
501
502 iterator erase(const_iterator CS, const_iterator CE) {
503 // Just cast away constness because this is a non-const member function.
504 iterator S = const_cast<iterator>(CS);
505 iterator E = const_cast<iterator>(CE);
506
507 assert(S >= this->begin() && "Range to erase is out of bounds.")((S >= this->begin() && "Range to erase is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("S >= this->begin() && \"Range to erase is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 507, __PRETTY_FUNCTION__))
;
508 assert(S <= E && "Trying to erase invalid range.")((S <= E && "Trying to erase invalid range.") ? static_cast
<void> (0) : __assert_fail ("S <= E && \"Trying to erase invalid range.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 508, __PRETTY_FUNCTION__))
;
509 assert(E <= this->end() && "Trying to erase past the end.")((E <= this->end() && "Trying to erase past the end."
) ? static_cast<void> (0) : __assert_fail ("E <= this->end() && \"Trying to erase past the end.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 509, __PRETTY_FUNCTION__))
;
510
511 iterator N = S;
512 // Shift all elts down.
513 iterator I = std::move(E, this->end(), S);
514 // Drop the last elts.
515 this->destroy_range(I, this->end());
516 this->set_size(I - this->begin());
517 return(N);
518 }
519
520 iterator insert(iterator I, T &&Elt) {
521 if (I == this->end()) { // Important special case for empty vector.
522 this->push_back(::std::move(Elt));
523 return this->end()-1;
524 }
525
526 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 526, __PRETTY_FUNCTION__))
;
527 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 527, __PRETTY_FUNCTION__))
;
528
529 if (this->size() >= this->capacity()) {
530 size_t EltNo = I-this->begin();
531 this->grow();
532 I = this->begin()+EltNo;
533 }
534
535 ::new ((void*) this->end()) T(::std::move(this->back()));
536 // Push everything else over.
537 std::move_backward(I, this->end()-1, this->end());
538 this->set_size(this->size() + 1);
539
540 // If we just moved the element we're inserting, be sure to update
541 // the reference.
542 T *EltPtr = &Elt;
543 if (I <= EltPtr && EltPtr < this->end())
544 ++EltPtr;
545
546 *I = ::std::move(*EltPtr);
547 return I;
548 }
549
550 iterator insert(iterator I, const T &Elt) {
551 if (I == this->end()) { // Important special case for empty vector.
552 this->push_back(Elt);
553 return this->end()-1;
554 }
555
556 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 556, __PRETTY_FUNCTION__))
;
557 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 557, __PRETTY_FUNCTION__))
;
558
559 if (this->size() >= this->capacity()) {
560 size_t EltNo = I-this->begin();
561 this->grow();
562 I = this->begin()+EltNo;
563 }
564 ::new ((void*) this->end()) T(std::move(this->back()));
565 // Push everything else over.
566 std::move_backward(I, this->end()-1, this->end());
567 this->set_size(this->size() + 1);
568
569 // If we just moved the element we're inserting, be sure to update
570 // the reference.
571 const T *EltPtr = &Elt;
572 if (I <= EltPtr && EltPtr < this->end())
573 ++EltPtr;
574
575 *I = *EltPtr;
576 return I;
577 }
578
579 iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
580 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
581 size_t InsertElt = I - this->begin();
582
583 if (I == this->end()) { // Important special case for empty vector.
584 append(NumToInsert, Elt);
585 return this->begin()+InsertElt;
586 }
587
588 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 588, __PRETTY_FUNCTION__))
;
589 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 589, __PRETTY_FUNCTION__))
;
590
591 // Ensure there is enough space.
592 reserve(this->size() + NumToInsert);
593
594 // Uninvalidate the iterator.
595 I = this->begin()+InsertElt;
596
597 // If there are more elements between the insertion point and the end of the
598 // range than there are being inserted, we can use a simple approach to
599 // insertion. Since we already reserved space, we know that this won't
600 // reallocate the vector.
601 if (size_t(this->end()-I) >= NumToInsert) {
602 T *OldEnd = this->end();
603 append(std::move_iterator<iterator>(this->end() - NumToInsert),
604 std::move_iterator<iterator>(this->end()));
605
606 // Copy the existing elements that get replaced.
607 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
608
609 std::fill_n(I, NumToInsert, Elt);
610 return I;
611 }
612
613 // Otherwise, we're inserting more elements than exist already, and we're
614 // not inserting at the end.
615
616 // Move over the elements that we're about to overwrite.
617 T *OldEnd = this->end();
618 this->set_size(this->size() + NumToInsert);
619 size_t NumOverwritten = OldEnd-I;
620 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
621
622 // Replace the overwritten part.
623 std::fill_n(I, NumOverwritten, Elt);
624
625 // Insert the non-overwritten middle part.
626 std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
627 return I;
628 }
629
630 template <typename ItTy,
631 typename = std::enable_if_t<std::is_convertible<
632 typename std::iterator_traits<ItTy>::iterator_category,
633 std::input_iterator_tag>::value>>
634 iterator insert(iterator I, ItTy From, ItTy To) {
635 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
636 size_t InsertElt = I - this->begin();
637
638 if (I == this->end()) { // Important special case for empty vector.
639 append(From, To);
640 return this->begin()+InsertElt;
641 }
642
643 assert(I >= this->begin() && "Insertion iterator is out of bounds.")((I >= this->begin() && "Insertion iterator is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("I >= this->begin() && \"Insertion iterator is out of bounds.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 643, __PRETTY_FUNCTION__))
;
644 assert(I <= this->end() && "Inserting past the end of the vector.")((I <= this->end() && "Inserting past the end of the vector."
) ? static_cast<void> (0) : __assert_fail ("I <= this->end() && \"Inserting past the end of the vector.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include/llvm/ADT/SmallVector.h"
, 644, __PRETTY_FUNCTION__))
;
645
646 size_t NumToInsert = std::distance(From, To);
647
648 // Ensure there is enough space.
649 reserve(this->size() + NumToInsert);
650
651 // Uninvalidate the iterator.
652 I = this->begin()+InsertElt;
653
654 // If there are more elements between the insertion point and the end of the
655 // range than there are being inserted, we can use a simple approach to
656 // insertion. Since we already reserved space, we know that this won't
657 // reallocate the vector.
658 if (size_t(this->end()-I) >= NumToInsert) {
659 T *OldEnd = this->end();
660 append(std::move_iterator<iterator>(this->end() - NumToInsert),
661 std::move_iterator<iterator>(this->end()));
662
663 // Copy the existing elements that get replaced.
664 std::move_backward(I, OldEnd-NumToInsert, OldEnd);
665
666 std::copy(From, To, I);
667 return I;
668 }
669
670 // Otherwise, we're inserting more elements than exist already, and we're
671 // not inserting at the end.
672
673 // Move over the elements that we're about to overwrite.
674 T *OldEnd = this->end();
675 this->set_size(this->size() + NumToInsert);
676 size_t NumOverwritten = OldEnd-I;
677 this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
678
679 // Replace the overwritten part.
680 for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
681 *J = *From;
682 ++J; ++From;
683 }
684
685 // Insert the non-overwritten middle part.
686 this->uninitialized_copy(From, To, OldEnd);
687 return I;
688 }
689
690 void insert(iterator I, std::initializer_list<T> IL) {
691 insert(I, IL.begin(), IL.end());
692 }
693
694 template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
695 if (LLVM_UNLIKELY(this->size() >= this->capacity())__builtin_expect((bool)(this->size() >= this->capacity
()), false)
)
696 this->grow();
697 ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
698 this->set_size(this->size() + 1);
699 return this->back();
700 }
701
702 SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
703
704 SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
705
706 bool operator==(const SmallVectorImpl &RHS) const {
707 if (this->size() != RHS.size()) return false;
708 return std::equal(this->begin(), this->end(), RHS.begin());
709 }
710 bool operator!=(const SmallVectorImpl &RHS) const {
711 return !(*this == RHS);
712 }
713
714 bool operator<(const SmallVectorImpl &RHS) const {
715 return std::lexicographical_compare(this->begin(), this->end(),
716 RHS.begin(), RHS.end());
717 }
718};
719
720template <typename T>
721void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
722 if (this == &RHS) return;
723
724 // We can only avoid copying elements if neither vector is small.
725 if (!this->isSmall() && !RHS.isSmall()) {
726 std::swap(this->BeginX, RHS.BeginX);
727 std::swap(this->Size, RHS.Size);
728 std::swap(this->Capacity, RHS.Capacity);
729 return;
730 }
731 if (RHS.size() > this->capacity())
732 this->grow(RHS.size());
733 if (this->size() > RHS.capacity())
734 RHS.grow(this->size());
735
736 // Swap the shared elements.
737 size_t NumShared = this->size();
738 if (NumShared > RHS.size()) NumShared = RHS.size();
739 for (size_type i = 0; i != NumShared; ++i)
740 std::swap((*this)[i], RHS[i]);
741
742 // Copy over the extra elts.
743 if (this->size() > RHS.size()) {
744 size_t EltDiff = this->size() - RHS.size();
745 this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
746 RHS.set_size(RHS.size() + EltDiff);
747 this->destroy_range(this->begin()+NumShared, this->end());
748 this->set_size(NumShared);
749 } else if (RHS.size() > this->size()) {
750 size_t EltDiff = RHS.size() - this->size();
751 this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
752 this->set_size(this->size() + EltDiff);
753 this->destroy_range(RHS.begin()+NumShared, RHS.end());
754 RHS.set_size(NumShared);
755 }
756}
757
758template <typename T>
759SmallVectorImpl<T> &SmallVectorImpl<T>::
760 operator=(const SmallVectorImpl<T> &RHS) {
761 // Avoid self-assignment.
762 if (this == &RHS) return *this;
763
764 // If we already have sufficient space, assign the common elements, then
765 // destroy any excess.
766 size_t RHSSize = RHS.size();
767 size_t CurSize = this->size();
768 if (CurSize >= RHSSize) {
769 // Assign common elements.
770 iterator NewEnd;
771 if (RHSSize)
772 NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
773 else
774 NewEnd = this->begin();
775
776 // Destroy excess elements.
777 this->destroy_range(NewEnd, this->end());
778
779 // Trim.
780 this->set_size(RHSSize);
781 return *this;
782 }
783
784 // If we have to grow to have enough elements, destroy the current elements.
785 // This allows us to avoid copying them during the grow.
786 // FIXME: don't do this if they're efficiently moveable.
787 if (this->capacity() < RHSSize) {
788 // Destroy current elements.
789 this->destroy_range(this->begin(), this->end());
790 this->set_size(0);
791 CurSize = 0;
792 this->grow(RHSSize);
793 } else if (CurSize) {
794 // Otherwise, use assignment for the already-constructed elements.
795 std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
796 }
797
798 // Copy construct the new elements in place.
799 this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
800 this->begin()+CurSize);
801
802 // Set end.
803 this->set_size(RHSSize);
804 return *this;
805}
806
807template <typename T>
808SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
809 // Avoid self-assignment.
810 if (this == &RHS) return *this;
811
812 // If the RHS isn't small, clear this vector and then steal its buffer.
813 if (!RHS.isSmall()) {
814 this->destroy_range(this->begin(), this->end());
815 if (!this->isSmall()) free(this->begin());
816 this->BeginX = RHS.BeginX;
817 this->Size = RHS.Size;
818 this->Capacity = RHS.Capacity;
819 RHS.resetToSmall();
820 return *this;
821 }
822
823 // If we already have sufficient space, assign the common elements, then
824 // destroy any excess.
825 size_t RHSSize = RHS.size();
826 size_t CurSize = this->size();
827 if (CurSize >= RHSSize) {
828 // Assign common elements.
829 iterator NewEnd = this->begin();
830 if (RHSSize)
831 NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
832
833 // Destroy excess elements and trim the bounds.
834 this->destroy_range(NewEnd, this->end());
835 this->set_size(RHSSize);
836
837 // Clear the RHS.
838 RHS.clear();
839
840 return *this;
841 }
842
843 // If we have to grow to have enough elements, destroy the current elements.
844 // This allows us to avoid copying them during the grow.
845 // FIXME: this may not actually make any sense if we can efficiently move
846 // elements.
847 if (this->capacity() < RHSSize) {
848 // Destroy current elements.
849 this->destroy_range(this->begin(), this->end());
850 this->set_size(0);
851 CurSize = 0;
852 this->grow(RHSSize);
853 } else if (CurSize) {
854 // Otherwise, use assignment for the already-constructed elements.
855 std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
856 }
857
858 // Move-construct the new elements in place.
859 this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
860 this->begin()+CurSize);
861
862 // Set end.
863 this->set_size(RHSSize);
864
865 RHS.clear();
866 return *this;
867}
868
869/// Storage for the SmallVector elements. This is specialized for the N=0 case
870/// to avoid allocating unnecessary storage.
871template <typename T, unsigned N>
872struct SmallVectorStorage {
873 alignas(T) char InlineElts[N * sizeof(T)];
874};
875
876/// We need the storage to be properly aligned even for small-size of 0 so that
877/// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
878/// well-defined.
879template <typename T> struct alignas(T) SmallVectorStorage<T, 0> {};
880
881/// This is a 'vector' (really, a variable-sized array), optimized
882/// for the case when the array is small. It contains some number of elements
883/// in-place, which allows it to avoid heap allocation when the actual number of
884/// elements is below that threshold. This allows normal "small" cases to be
885/// fast without losing generality for large inputs.
886///
887/// Note that this does not attempt to be exception safe.
888///
889template <typename T, unsigned N>
890class LLVM_GSL_OWNER[[gsl::Owner]] SmallVector : public SmallVectorImpl<T>,
891 SmallVectorStorage<T, N> {
892public:
893 SmallVector() : SmallVectorImpl<T>(N) {}
894
895 ~SmallVector() {
896 // Destroy the constructed elements in the vector.
897 this->destroy_range(this->begin(), this->end());
898 }
899
900 explicit SmallVector(size_t Size, const T &Value = T())
901 : SmallVectorImpl<T>(N) {
902 this->assign(Size, Value);
903 }
904
905 template <typename ItTy,
906 typename = std::enable_if_t<std::is_convertible<
907 typename std::iterator_traits<ItTy>::iterator_category,
908 std::input_iterator_tag>::value>>
909 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
910 this->append(S, E);
911 }
912
913 template <typename RangeTy>
914 explicit SmallVector(const iterator_range<RangeTy> &R)
915 : SmallVectorImpl<T>(N) {
916 this->append(R.begin(), R.end());
917 }
918
919 SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
920 this->assign(IL);
921 }
922
923 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
924 if (!RHS.empty())
925 SmallVectorImpl<T>::operator=(RHS);
926 }
927
928 SmallVector &operator=(const SmallVector &RHS) {
929 SmallVectorImpl<T>::operator=(RHS);
930 return *this;
931 }
932
933 SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
934 if (!RHS.empty())
935 SmallVectorImpl<T>::operator=(::std::move(RHS));
936 }
937
938 SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
939 if (!RHS.empty())
940 SmallVectorImpl<T>::operator=(::std::move(RHS));
941 }
942
943 SmallVector &operator=(SmallVector &&RHS) {
944 SmallVectorImpl<T>::operator=(::std::move(RHS));
945 return *this;
946 }
947
948 SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
949 SmallVectorImpl<T>::operator=(::std::move(RHS));
950 return *this;
951 }
952
953 SmallVector &operator=(std::initializer_list<T> IL) {
954 this->assign(IL);
955 return *this;
956 }
957};
958
959template <typename T, unsigned N>
960inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
961 return X.capacity_in_bytes();
962}
963
964/// Given a range of type R, iterate the entire range and return a
965/// SmallVector with elements of the vector. This is useful, for example,
966/// when you want to iterate a range and then sort the results.
967template <unsigned Size, typename R>
968SmallVector<typename std::remove_const<typename std::remove_reference<
969 decltype(*std::begin(std::declval<R &>()))>::type>::type,
970 Size>
971to_vector(R &&Range) {
972 return {std::begin(Range), std::end(Range)};
973}
974
975} // end namespace llvm
976
977namespace std {
978
979 /// Implement std::swap in terms of SmallVector swap.
980 template<typename T>
981 inline void
982 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
983 LHS.swap(RHS);
984 }
985
986 /// Implement std::swap in terms of SmallVector swap.
987 template<typename T, unsigned N>
988 inline void
989 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
990 LHS.swap(RHS);
991 }
992
993} // end namespace std
994
995#endif // LLVM_ADT_SMALLVECTOR_H