Bug Summary

File:llvm/lib/CodeGen/WinEHPrepare.cpp
Warning:line 209, column 30
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name WinEHPrepare.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 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/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-10/lib/clang/10.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-10~+201911111502510600c19528f1809/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp

1//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
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 pass lowers LLVM IR exception handling into something closer to what the
10// backend wants for functions using a personality function from a runtime
11// provided by MSVC. Functions with other personality functions are left alone
12// and may be prepared by other passes. In particular, all supported MSVC
13// personality functions require cleanup code to be outlined, and the C++
14// personality requires catch handler code to be outlined.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/Analysis/CFG.h"
22#include "llvm/Analysis/EHPersonalities.h"
23#include "llvm/Transforms/Utils/Local.h"
24#include "llvm/CodeGen/MachineBasicBlock.h"
25#include "llvm/CodeGen/Passes.h"
26#include "llvm/CodeGen/WinEHFuncInfo.h"
27#include "llvm/IR/Verifier.h"
28#include "llvm/MC/MCSymbol.h"
29#include "llvm/Pass.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Transforms/Utils/BasicBlockUtils.h"
33#include "llvm/Transforms/Utils/Cloning.h"
34#include "llvm/Transforms/Utils/SSAUpdater.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE"winehprepare" "winehprepare"
39
40static cl::opt<bool> DisableDemotion(
41 "disable-demotion", cl::Hidden,
42 cl::desc(
43 "Clone multicolor basic blocks but do not demote cross scopes"),
44 cl::init(false));
45
46static cl::opt<bool> DisableCleanups(
47 "disable-cleanups", cl::Hidden,
48 cl::desc("Do not remove implausible terminators or other similar cleanups"),
49 cl::init(false));
50
51static cl::opt<bool> DemoteCatchSwitchPHIOnlyOpt(
52 "demote-catchswitch-only", cl::Hidden,
53 cl::desc("Demote catchswitch BBs only (for wasm EH)"), cl::init(false));
54
55namespace {
56
57class WinEHPrepare : public FunctionPass {
58public:
59 static char ID; // Pass identification, replacement for typeid.
60 WinEHPrepare(bool DemoteCatchSwitchPHIOnly = false)
61 : FunctionPass(ID), DemoteCatchSwitchPHIOnly(DemoteCatchSwitchPHIOnly) {}
62
63 bool runOnFunction(Function &Fn) override;
64
65 bool doFinalization(Module &M) override;
66
67 void getAnalysisUsage(AnalysisUsage &AU) const override;
68
69 StringRef getPassName() const override {
70 return "Windows exception handling preparation";
71 }
72
73private:
74 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
75 void
76 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
77 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
78 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
79 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
80 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
81 bool prepareExplicitEH(Function &F);
82 void colorFunclets(Function &F);
83
84 void demotePHIsOnFunclets(Function &F, bool DemoteCatchSwitchPHIOnly);
85 void cloneCommonBlocks(Function &F);
86 void removeImplausibleInstructions(Function &F);
87 void cleanupPreparedFunclets(Function &F);
88 void verifyPreparedFunclets(Function &F);
89
90 bool DemoteCatchSwitchPHIOnly;
91
92 // All fields are reset by runOnFunction.
93 EHPersonality Personality = EHPersonality::Unknown;
94
95 const DataLayout *DL = nullptr;
96 DenseMap<BasicBlock *, ColorVector> BlockColors;
97 MapVector<BasicBlock *, std::vector<BasicBlock *>> FuncletBlocks;
98};
99
100} // end anonymous namespace
101
102char WinEHPrepare::ID = 0;
103INITIALIZE_PASS(WinEHPrepare, DEBUG_TYPE, "Prepare Windows exceptions",static void *initializeWinEHPreparePassOnce(PassRegistry &
Registry) { PassInfo *PI = new PassInfo( "Prepare Windows exceptions"
, "winehprepare", &WinEHPrepare::ID, PassInfo::NormalCtor_t
(callDefaultCtor<WinEHPrepare>), false, false); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeWinEHPreparePassFlag; void llvm::initializeWinEHPreparePass
(PassRegistry &Registry) { llvm::call_once(InitializeWinEHPreparePassFlag
, initializeWinEHPreparePassOnce, std::ref(Registry)); }
104 false, false)static void *initializeWinEHPreparePassOnce(PassRegistry &
Registry) { PassInfo *PI = new PassInfo( "Prepare Windows exceptions"
, "winehprepare", &WinEHPrepare::ID, PassInfo::NormalCtor_t
(callDefaultCtor<WinEHPrepare>), false, false); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeWinEHPreparePassFlag; void llvm::initializeWinEHPreparePass
(PassRegistry &Registry) { llvm::call_once(InitializeWinEHPreparePassFlag
, initializeWinEHPreparePassOnce, std::ref(Registry)); }
105
106FunctionPass *llvm::createWinEHPass(bool DemoteCatchSwitchPHIOnly) {
107 return new WinEHPrepare(DemoteCatchSwitchPHIOnly);
108}
109
110bool WinEHPrepare::runOnFunction(Function &Fn) {
111 if (!Fn.hasPersonalityFn())
112 return false;
113
114 // Classify the personality to see what kind of preparation we need.
115 Personality = classifyEHPersonality(Fn.getPersonalityFn());
116
117 // Do nothing if this is not a scope-based personality.
118 if (!isScopedEHPersonality(Personality))
119 return false;
120
121 DL = &Fn.getParent()->getDataLayout();
122 return prepareExplicitEH(Fn);
123}
124
125bool WinEHPrepare::doFinalization(Module &M) { return false; }
126
127void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
128
129static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
130 const BasicBlock *BB) {
131 CxxUnwindMapEntry UME;
132 UME.ToState = ToState;
133 UME.Cleanup = BB;
134 FuncInfo.CxxUnwindMap.push_back(UME);
135 return FuncInfo.getLastStateNumber();
136}
137
138static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
139 int TryHigh, int CatchHigh,
140 ArrayRef<const CatchPadInst *> Handlers) {
141 WinEHTryBlockMapEntry TBME;
142 TBME.TryLow = TryLow;
143 TBME.TryHigh = TryHigh;
144 TBME.CatchHigh = CatchHigh;
145 assert(TBME.TryLow <= TBME.TryHigh)((TBME.TryLow <= TBME.TryHigh) ? static_cast<void> (
0) : __assert_fail ("TBME.TryLow <= TBME.TryHigh", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 145, __PRETTY_FUNCTION__))
;
146 for (const CatchPadInst *CPI : Handlers) {
147 WinEHHandlerType HT;
148 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
149 if (TypeInfo->isNullValue())
150 HT.TypeDescriptor = nullptr;
151 else
152 HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
153 HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
154 HT.Handler = CPI->getParent();
155 if (auto *AI =
156 dyn_cast<AllocaInst>(CPI->getArgOperand(2)->stripPointerCasts()))
157 HT.CatchObj.Alloca = AI;
158 else
159 HT.CatchObj.Alloca = nullptr;
160 TBME.HandlerArray.push_back(HT);
161 }
162 FuncInfo.TryBlockMap.push_back(TBME);
163}
164
165static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad) {
166 for (const User *U : CleanupPad->users())
167 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
168 return CRI->getUnwindDest();
169 return nullptr;
170}
171
172static void calculateStateNumbersForInvokes(const Function *Fn,
173 WinEHFuncInfo &FuncInfo) {
174 auto *F = const_cast<Function *>(Fn);
175 DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(*F);
176 for (BasicBlock &BB : *F) {
177 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
6
Assuming the object is a 'InvokeInst'
178 if (!II
6.1
'II' is non-null
6.1
'II' is non-null
6.1
'II' is non-null
)
7
Taking false branch
179 continue;
180
181 auto &BBColors = BlockColors[&BB];
182 assert(BBColors.size() == 1 && "multi-color BB not removed by preparation")((BBColors.size() == 1 && "multi-color BB not removed by preparation"
) ? static_cast<void> (0) : __assert_fail ("BBColors.size() == 1 && \"multi-color BB not removed by preparation\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 182, __PRETTY_FUNCTION__))
;
8
Assuming the condition is true
9
'?' condition is true
183 BasicBlock *FuncletEntryBB = BBColors.front();
184
185 BasicBlock *FuncletUnwindDest;
186 auto *FuncletPad =
187 dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI());
10
Assuming the object is not a 'FuncletPadInst'
188 assert
10.1
'FuncletPad' is null
10.1
'FuncletPad' is null
10.1
'FuncletPad' is null
(FuncletPad || FuncletEntryBB == &Fn->getEntryBlock())((FuncletPad || FuncletEntryBB == &Fn->getEntryBlock()
) ? static_cast<void> (0) : __assert_fail ("FuncletPad || FuncletEntryBB == &Fn->getEntryBlock()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 188, __PRETTY_FUNCTION__))
;
11
Assuming the condition is true
12
'?' condition is true
189 if (!FuncletPad
12.1
'FuncletPad' is null
12.1
'FuncletPad' is null
12.1
'FuncletPad' is null
)
13
Taking true branch
190 FuncletUnwindDest = nullptr;
191 else if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
192 FuncletUnwindDest = CatchPad->getCatchSwitch()->getUnwindDest();
193 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(FuncletPad))
194 FuncletUnwindDest = getCleanupRetUnwindDest(CleanupPad);
195 else
196 llvm_unreachable("unexpected funclet pad!")::llvm::llvm_unreachable_internal("unexpected funclet pad!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 196)
;
197
198 BasicBlock *InvokeUnwindDest = II->getUnwindDest();
14
Calling 'InvokeInst::getUnwindDest'
30
Returning from 'InvokeInst::getUnwindDest'
31
'InvokeUnwindDest' initialized here
199 int BaseState = -1;
200 if (FuncletUnwindDest == InvokeUnwindDest) {
32
Assuming 'FuncletUnwindDest' is equal to 'InvokeUnwindDest'
33
Taking true branch
201 auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
202 if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
34
Assuming the condition is false
35
Taking false branch
203 BaseState = BaseStateI->second;
204 }
205
206 if (BaseState != -1) {
36
Taking false branch
207 FuncInfo.InvokeStateMap[II] = BaseState;
208 } else {
209 Instruction *PadInst = InvokeUnwindDest->getFirstNonPHI();
37
Called C++ object pointer is null
210 assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!")((FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.EHPadStateMap.count(PadInst) && \"EH Pad has no state!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 210, __PRETTY_FUNCTION__))
;
211 FuncInfo.InvokeStateMap[II] = FuncInfo.EHPadStateMap[PadInst];
212 }
213 }
214}
215
216// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
217// to. If the unwind edge came from an invoke, return null.
218static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB,
219 Value *ParentPad) {
220 const Instruction *TI = BB->getTerminator();
221 if (isa<InvokeInst>(TI))
222 return nullptr;
223 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
224 if (CatchSwitch->getParentPad() != ParentPad)
225 return nullptr;
226 return BB;
227 }
228 assert(!TI->isEHPad() && "unexpected EHPad!")((!TI->isEHPad() && "unexpected EHPad!") ? static_cast
<void> (0) : __assert_fail ("!TI->isEHPad() && \"unexpected EHPad!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 228, __PRETTY_FUNCTION__))
;
229 auto *CleanupPad = cast<CleanupReturnInst>(TI)->getCleanupPad();
230 if (CleanupPad->getParentPad() != ParentPad)
231 return nullptr;
232 return CleanupPad->getParent();
233}
234
235static void calculateCXXStateNumbers(WinEHFuncInfo &FuncInfo,
236 const Instruction *FirstNonPHI,
237 int ParentState) {
238 const BasicBlock *BB = FirstNonPHI->getParent();
239 assert(BB->isEHPad() && "not a funclet!")((BB->isEHPad() && "not a funclet!") ? static_cast
<void> (0) : __assert_fail ("BB->isEHPad() && \"not a funclet!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 239, __PRETTY_FUNCTION__))
;
240
241 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
242 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&((FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && "shouldn't revist catch funclets!"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && \"shouldn't revist catch funclets!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 243, __PRETTY_FUNCTION__))
243 "shouldn't revist catch funclets!")((FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && "shouldn't revist catch funclets!"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && \"shouldn't revist catch funclets!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 243, __PRETTY_FUNCTION__))
;
244
245 SmallVector<const CatchPadInst *, 2> Handlers;
246 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
247 auto *CatchPad = cast<CatchPadInst>(CatchPadBB->getFirstNonPHI());
248 Handlers.push_back(CatchPad);
249 }
250 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
251 FuncInfo.EHPadStateMap[CatchSwitch] = TryLow;
252 for (const BasicBlock *PredBlock : predecessors(BB))
253 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
254 CatchSwitch->getParentPad())))
255 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
256 TryLow);
257 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
258
259 // catchpads are separate funclets in C++ EH due to the way rethrow works.
260 int TryHigh = CatchLow - 1;
261 for (const auto *CatchPad : Handlers) {
262 FuncInfo.FuncletBaseStateMap[CatchPad] = CatchLow;
263 for (const User *U : CatchPad->users()) {
264 const auto *UserI = cast<Instruction>(U);
265 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
266 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
267 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
268 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
269 }
270 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
271 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
272 // If a nested cleanup pad reports a null unwind destination and the
273 // enclosing catch pad doesn't it must be post-dominated by an
274 // unreachable instruction.
275 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
276 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
277 }
278 }
279 }
280 int CatchHigh = FuncInfo.getLastStateNumber();
281 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
282 LLVM_DEBUG(dbgs() << "TryLow[" << BB->getName() << "]: " << TryLow << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "TryLow[" << BB->
getName() << "]: " << TryLow << '\n'; } } while
(false)
;
283 LLVM_DEBUG(dbgs() << "TryHigh[" << BB->getName() << "]: " << TryHighdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "TryHigh[" << BB->
getName() << "]: " << TryHigh << '\n'; } } while
(false)
284 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "TryHigh[" << BB->
getName() << "]: " << TryHigh << '\n'; } } while
(false)
;
285 LLVM_DEBUG(dbgs() << "CatchHigh[" << BB->getName() << "]: " << CatchHighdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "CatchHigh[" << BB->
getName() << "]: " << CatchHigh << '\n'; } }
while (false)
286 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "CatchHigh[" << BB->
getName() << "]: " << CatchHigh << '\n'; } }
while (false)
;
287 } else {
288 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
289
290 // It's possible for a cleanup to be visited twice: it might have multiple
291 // cleanupret instructions.
292 if (FuncInfo.EHPadStateMap.count(CleanupPad))
293 return;
294
295 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, BB);
296 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
297 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
CleanupState << " to BB " << BB->getName() <<
'\n'; } } while (false)
298 << BB->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
CleanupState << " to BB " << BB->getName() <<
'\n'; } } while (false)
;
299 for (const BasicBlock *PredBlock : predecessors(BB)) {
300 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
301 CleanupPad->getParentPad()))) {
302 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
303 CleanupState);
304 }
305 }
306 for (const User *U : CleanupPad->users()) {
307 const auto *UserI = cast<Instruction>(U);
308 if (UserI->isEHPad())
309 report_fatal_error("Cleanup funclets for the MSVC++ personality cannot "
310 "contain exceptional actions");
311 }
312 }
313}
314
315static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
316 const Function *Filter, const BasicBlock *Handler) {
317 SEHUnwindMapEntry Entry;
318 Entry.ToState = ParentState;
319 Entry.IsFinally = false;
320 Entry.Filter = Filter;
321 Entry.Handler = Handler;
322 FuncInfo.SEHUnwindMap.push_back(Entry);
323 return FuncInfo.SEHUnwindMap.size() - 1;
324}
325
326static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
327 const BasicBlock *Handler) {
328 SEHUnwindMapEntry Entry;
329 Entry.ToState = ParentState;
330 Entry.IsFinally = true;
331 Entry.Filter = nullptr;
332 Entry.Handler = Handler;
333 FuncInfo.SEHUnwindMap.push_back(Entry);
334 return FuncInfo.SEHUnwindMap.size() - 1;
335}
336
337static void calculateSEHStateNumbers(WinEHFuncInfo &FuncInfo,
338 const Instruction *FirstNonPHI,
339 int ParentState) {
340 const BasicBlock *BB = FirstNonPHI->getParent();
341 assert(BB->isEHPad() && "no a funclet!")((BB->isEHPad() && "no a funclet!") ? static_cast<
void> (0) : __assert_fail ("BB->isEHPad() && \"no a funclet!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 341, __PRETTY_FUNCTION__))
;
342
343 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
344 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&((FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && "shouldn't revist catch funclets!"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && \"shouldn't revist catch funclets!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 345, __PRETTY_FUNCTION__))
345 "shouldn't revist catch funclets!")((FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && "shouldn't revist catch funclets!"
) ? static_cast<void> (0) : __assert_fail ("FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && \"shouldn't revist catch funclets!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 345, __PRETTY_FUNCTION__))
;
346
347 // Extract the filter function and the __except basic block and create a
348 // state for them.
349 assert(CatchSwitch->getNumHandlers() == 1 &&((CatchSwitch->getNumHandlers() == 1 && "SEH doesn't have multiple handlers per __try"
) ? static_cast<void> (0) : __assert_fail ("CatchSwitch->getNumHandlers() == 1 && \"SEH doesn't have multiple handlers per __try\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 350, __PRETTY_FUNCTION__))
350 "SEH doesn't have multiple handlers per __try")((CatchSwitch->getNumHandlers() == 1 && "SEH doesn't have multiple handlers per __try"
) ? static_cast<void> (0) : __assert_fail ("CatchSwitch->getNumHandlers() == 1 && \"SEH doesn't have multiple handlers per __try\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 350, __PRETTY_FUNCTION__))
;
351 const auto *CatchPad =
352 cast<CatchPadInst>((*CatchSwitch->handler_begin())->getFirstNonPHI());
353 const BasicBlock *CatchPadBB = CatchPad->getParent();
354 const Constant *FilterOrNull =
355 cast<Constant>(CatchPad->getArgOperand(0)->stripPointerCasts());
356 const Function *Filter = dyn_cast<Function>(FilterOrNull);
357 assert((Filter || FilterOrNull->isNullValue()) &&(((Filter || FilterOrNull->isNullValue()) && "unexpected filter value"
) ? static_cast<void> (0) : __assert_fail ("(Filter || FilterOrNull->isNullValue()) && \"unexpected filter value\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 358, __PRETTY_FUNCTION__))
358 "unexpected filter value")(((Filter || FilterOrNull->isNullValue()) && "unexpected filter value"
) ? static_cast<void> (0) : __assert_fail ("(Filter || FilterOrNull->isNullValue()) && \"unexpected filter value\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 358, __PRETTY_FUNCTION__))
;
359 int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
360
361 // Everything in the __try block uses TryState as its parent state.
362 FuncInfo.EHPadStateMap[CatchSwitch] = TryState;
363 LLVM_DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
TryState << " to BB " << CatchPadBB->getName(
) << '\n'; } } while (false)
364 << CatchPadBB->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
TryState << " to BB " << CatchPadBB->getName(
) << '\n'; } } while (false)
;
365 for (const BasicBlock *PredBlock : predecessors(BB))
366 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
367 CatchSwitch->getParentPad())))
368 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
369 TryState);
370
371 // Everything in the __except block unwinds to ParentState, just like code
372 // outside the __try.
373 for (const User *U : CatchPad->users()) {
374 const auto *UserI = cast<Instruction>(U);
375 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
376 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
377 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
378 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
379 }
380 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
381 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
382 // If a nested cleanup pad reports a null unwind destination and the
383 // enclosing catch pad doesn't it must be post-dominated by an
384 // unreachable instruction.
385 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
386 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
387 }
388 }
389 } else {
390 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
391
392 // It's possible for a cleanup to be visited twice: it might have multiple
393 // cleanupret instructions.
394 if (FuncInfo.EHPadStateMap.count(CleanupPad))
395 return;
396
397 int CleanupState = addSEHFinally(FuncInfo, ParentState, BB);
398 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
399 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
CleanupState << " to BB " << BB->getName() <<
'\n'; } } while (false)
400 << BB->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
CleanupState << " to BB " << BB->getName() <<
'\n'; } } while (false)
;
401 for (const BasicBlock *PredBlock : predecessors(BB))
402 if ((PredBlock =
403 getEHPadFromPredecessor(PredBlock, CleanupPad->getParentPad())))
404 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
405 CleanupState);
406 for (const User *U : CleanupPad->users()) {
407 const auto *UserI = cast<Instruction>(U);
408 if (UserI->isEHPad())
409 report_fatal_error("Cleanup funclets for the SEH personality cannot "
410 "contain exceptional actions");
411 }
412 }
413}
414
415static bool isTopLevelPadForMSVC(const Instruction *EHPad) {
416 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(EHPad))
417 return isa<ConstantTokenNone>(CatchSwitch->getParentPad()) &&
418 CatchSwitch->unwindsToCaller();
419 if (auto *CleanupPad = dyn_cast<CleanupPadInst>(EHPad))
420 return isa<ConstantTokenNone>(CleanupPad->getParentPad()) &&
421 getCleanupRetUnwindDest(CleanupPad) == nullptr;
422 if (isa<CatchPadInst>(EHPad))
423 return false;
424 llvm_unreachable("unexpected EHPad!")::llvm::llvm_unreachable_internal("unexpected EHPad!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 424)
;
425}
426
427void llvm::calculateSEHStateNumbers(const Function *Fn,
428 WinEHFuncInfo &FuncInfo) {
429 // Don't compute state numbers twice.
430 if (!FuncInfo.SEHUnwindMap.empty())
431 return;
432
433 for (const BasicBlock &BB : *Fn) {
434 if (!BB.isEHPad())
435 continue;
436 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
437 if (!isTopLevelPadForMSVC(FirstNonPHI))
438 continue;
439 ::calculateSEHStateNumbers(FuncInfo, FirstNonPHI, -1);
440 }
441
442 calculateStateNumbersForInvokes(Fn, FuncInfo);
443}
444
445void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
446 WinEHFuncInfo &FuncInfo) {
447 // Return if it's already been done.
448 if (!FuncInfo.EHPadStateMap.empty())
449 return;
450
451 for (const BasicBlock &BB : *Fn) {
452 if (!BB.isEHPad())
453 continue;
454 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
455 if (!isTopLevelPadForMSVC(FirstNonPHI))
456 continue;
457 calculateCXXStateNumbers(FuncInfo, FirstNonPHI, -1);
458 }
459
460 calculateStateNumbersForInvokes(Fn, FuncInfo);
461}
462
463static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState,
464 int TryParentState, ClrHandlerType HandlerType,
465 uint32_t TypeToken, const BasicBlock *Handler) {
466 ClrEHUnwindMapEntry Entry;
467 Entry.HandlerParentState = HandlerParentState;
468 Entry.TryParentState = TryParentState;
469 Entry.Handler = Handler;
470 Entry.HandlerType = HandlerType;
471 Entry.TypeToken = TypeToken;
472 FuncInfo.ClrEHUnwindMap.push_back(Entry);
473 return FuncInfo.ClrEHUnwindMap.size() - 1;
474}
475
476void llvm::calculateClrEHStateNumbers(const Function *Fn,
477 WinEHFuncInfo &FuncInfo) {
478 // Return if it's already been done.
479 if (!FuncInfo.EHPadStateMap.empty())
1
Assuming the condition is false
2
Taking false branch
480 return;
481
482 // This numbering assigns one state number to each catchpad and cleanuppad.
483 // It also computes two tree-like relations over states:
484 // 1) Each state has a "HandlerParentState", which is the state of the next
485 // outer handler enclosing this state's handler (same as nearest ancestor
486 // per the ParentPad linkage on EH pads, but skipping over catchswitches).
487 // 2) Each state has a "TryParentState", which:
488 // a) for a catchpad that's not the last handler on its catchswitch, is
489 // the state of the next catchpad on that catchswitch
490 // b) for all other pads, is the state of the pad whose try region is the
491 // next outer try region enclosing this state's try region. The "try
492 // regions are not present as such in the IR, but will be inferred
493 // based on the placement of invokes and pads which reach each other
494 // by exceptional exits
495 // Catchswitches do not get their own states, but each gets mapped to the
496 // state of its first catchpad.
497
498 // Step one: walk down from outermost to innermost funclets, assigning each
499 // catchpad and cleanuppad a state number. Add an entry to the
500 // ClrEHUnwindMap for each state, recording its HandlerParentState and
501 // handler attributes. Record the TryParentState as well for each catchpad
502 // that's not the last on its catchswitch, but initialize all other entries'
503 // TryParentStates to a sentinel -1 value that the next pass will update.
504
505 // Seed a worklist with pads that have no parent.
506 SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
507 for (const BasicBlock &BB : *Fn) {
508 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
509 const Value *ParentPad;
510 if (const auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI))
511 ParentPad = CPI->getParentPad();
512 else if (const auto *CSI = dyn_cast<CatchSwitchInst>(FirstNonPHI))
513 ParentPad = CSI->getParentPad();
514 else
515 continue;
516 if (isa<ConstantTokenNone>(ParentPad))
517 Worklist.emplace_back(FirstNonPHI, -1);
518 }
519
520 // Use the worklist to visit all pads, from outer to inner. Record
521 // HandlerParentState for all pads. Record TryParentState only for catchpads
522 // that aren't the last on their catchswitch (setting all other entries'
523 // TryParentStates to an initial value of -1). This loop is also responsible
524 // for setting the EHPadStateMap entry for all catchpads, cleanuppads, and
525 // catchswitches.
526 while (!Worklist.empty()) {
3
Loop condition is false. Execution continues on line 580
527 const Instruction *Pad;
528 int HandlerParentState;
529 std::tie(Pad, HandlerParentState) = Worklist.pop_back_val();
530
531 if (const auto *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
532 // Create the entry for this cleanup with the appropriate handler
533 // properties. Finally and fault handlers are distinguished by arity.
534 ClrHandlerType HandlerType =
535 (Cleanup->getNumArgOperands() ? ClrHandlerType::Fault
536 : ClrHandlerType::Finally);
537 int CleanupState = addClrEHHandler(FuncInfo, HandlerParentState, -1,
538 HandlerType, 0, Pad->getParent());
539 // Queue any child EH pads on the worklist.
540 for (const User *U : Cleanup->users())
541 if (const auto *I = dyn_cast<Instruction>(U))
542 if (I->isEHPad())
543 Worklist.emplace_back(I, CleanupState);
544 // Remember this pad's state.
545 FuncInfo.EHPadStateMap[Cleanup] = CleanupState;
546 } else {
547 // Walk the handlers of this catchswitch in reverse order since all but
548 // the last need to set the following one as its TryParentState.
549 const auto *CatchSwitch = cast<CatchSwitchInst>(Pad);
550 int CatchState = -1, FollowerState = -1;
551 SmallVector<const BasicBlock *, 4> CatchBlocks(CatchSwitch->handlers());
552 for (auto CBI = CatchBlocks.rbegin(), CBE = CatchBlocks.rend();
553 CBI != CBE; ++CBI, FollowerState = CatchState) {
554 const BasicBlock *CatchBlock = *CBI;
555 // Create the entry for this catch with the appropriate handler
556 // properties.
557 const auto *Catch = cast<CatchPadInst>(CatchBlock->getFirstNonPHI());
558 uint32_t TypeToken = static_cast<uint32_t>(
559 cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
560 CatchState =
561 addClrEHHandler(FuncInfo, HandlerParentState, FollowerState,
562 ClrHandlerType::Catch, TypeToken, CatchBlock);
563 // Queue any child EH pads on the worklist.
564 for (const User *U : Catch->users())
565 if (const auto *I = dyn_cast<Instruction>(U))
566 if (I->isEHPad())
567 Worklist.emplace_back(I, CatchState);
568 // Remember this catch's state.
569 FuncInfo.EHPadStateMap[Catch] = CatchState;
570 }
571 // Associate the catchswitch with the state of its first catch.
572 assert(CatchSwitch->getNumHandlers())((CatchSwitch->getNumHandlers()) ? static_cast<void>
(0) : __assert_fail ("CatchSwitch->getNumHandlers()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 572, __PRETTY_FUNCTION__))
;
573 FuncInfo.EHPadStateMap[CatchSwitch] = CatchState;
574 }
575 }
576
577 // Step two: record the TryParentState of each state. For cleanuppads that
578 // don't have cleanuprets, we may need to infer this from their child pads,
579 // so visit pads in descendant-most to ancestor-most order.
580 for (auto Entry = FuncInfo.ClrEHUnwindMap.rbegin(),
4
Loop condition is false. Execution continues on line 675
581 End = FuncInfo.ClrEHUnwindMap.rend();
582 Entry != End; ++Entry) {
583 const Instruction *Pad =
584 Entry->Handler.get<const BasicBlock *>()->getFirstNonPHI();
585 // For most pads, the TryParentState is the state associated with the
586 // unwind dest of exceptional exits from it.
587 const BasicBlock *UnwindDest;
588 if (const auto *Catch = dyn_cast<CatchPadInst>(Pad)) {
589 // If a catch is not the last in its catchswitch, its TryParentState is
590 // the state associated with the next catch in the switch, even though
591 // that's not the unwind dest of exceptions escaping the catch. Those
592 // cases were already assigned a TryParentState in the first pass, so
593 // skip them.
594 if (Entry->TryParentState != -1)
595 continue;
596 // Otherwise, get the unwind dest from the catchswitch.
597 UnwindDest = Catch->getCatchSwitch()->getUnwindDest();
598 } else {
599 const auto *Cleanup = cast<CleanupPadInst>(Pad);
600 UnwindDest = nullptr;
601 for (const User *U : Cleanup->users()) {
602 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
603 // Common and unambiguous case -- cleanupret indicates cleanup's
604 // unwind dest.
605 UnwindDest = CleanupRet->getUnwindDest();
606 break;
607 }
608
609 // Get an unwind dest for the user
610 const BasicBlock *UserUnwindDest = nullptr;
611 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
612 UserUnwindDest = Invoke->getUnwindDest();
613 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(U)) {
614 UserUnwindDest = CatchSwitch->getUnwindDest();
615 } else if (auto *ChildCleanup = dyn_cast<CleanupPadInst>(U)) {
616 int UserState = FuncInfo.EHPadStateMap[ChildCleanup];
617 int UserUnwindState =
618 FuncInfo.ClrEHUnwindMap[UserState].TryParentState;
619 if (UserUnwindState != -1)
620 UserUnwindDest = FuncInfo.ClrEHUnwindMap[UserUnwindState]
621 .Handler.get<const BasicBlock *>();
622 }
623
624 // Not having an unwind dest for this user might indicate that it
625 // doesn't unwind, so can't be taken as proof that the cleanup itself
626 // may unwind to caller (see e.g. SimplifyUnreachable and
627 // RemoveUnwindEdge).
628 if (!UserUnwindDest)
629 continue;
630
631 // Now we have an unwind dest for the user, but we need to see if it
632 // unwinds all the way out of the cleanup or if it stays within it.
633 const Instruction *UserUnwindPad = UserUnwindDest->getFirstNonPHI();
634 const Value *UserUnwindParent;
635 if (auto *CSI = dyn_cast<CatchSwitchInst>(UserUnwindPad))
636 UserUnwindParent = CSI->getParentPad();
637 else
638 UserUnwindParent =
639 cast<CleanupPadInst>(UserUnwindPad)->getParentPad();
640
641 // The unwind stays within the cleanup iff it targets a child of the
642 // cleanup.
643 if (UserUnwindParent == Cleanup)
644 continue;
645
646 // This unwind exits the cleanup, so its dest is the cleanup's dest.
647 UnwindDest = UserUnwindDest;
648 break;
649 }
650 }
651
652 // Record the state of the unwind dest as the TryParentState.
653 int UnwindDestState;
654
655 // If UnwindDest is null at this point, either the pad in question can
656 // be exited by unwind to caller, or it cannot be exited by unwind. In
657 // either case, reporting such cases as unwinding to caller is correct.
658 // This can lead to EH tables that "look strange" -- if this pad's is in
659 // a parent funclet which has other children that do unwind to an enclosing
660 // pad, the try region for this pad will be missing the "duplicate" EH
661 // clause entries that you'd expect to see covering the whole parent. That
662 // should be benign, since the unwind never actually happens. If it were
663 // an issue, we could add a subsequent pass that pushes unwind dests down
664 // from parents that have them to children that appear to unwind to caller.
665 if (!UnwindDest) {
666 UnwindDestState = -1;
667 } else {
668 UnwindDestState = FuncInfo.EHPadStateMap[UnwindDest->getFirstNonPHI()];
669 }
670
671 Entry->TryParentState = UnwindDestState;
672 }
673
674 // Step three: transfer information from pads to invokes.
675 calculateStateNumbersForInvokes(Fn, FuncInfo);
5
Calling 'calculateStateNumbersForInvokes'
676}
677
678void WinEHPrepare::colorFunclets(Function &F) {
679 BlockColors = colorEHFunclets(F);
680
681 // Invert the map from BB to colors to color to BBs.
682 for (BasicBlock &BB : F) {
683 ColorVector &Colors = BlockColors[&BB];
684 for (BasicBlock *Color : Colors)
685 FuncletBlocks[Color].push_back(&BB);
686 }
687}
688
689void WinEHPrepare::demotePHIsOnFunclets(Function &F,
690 bool DemoteCatchSwitchPHIOnly) {
691 // Strip PHI nodes off of EH pads.
692 SmallVector<PHINode *, 16> PHINodes;
693 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
694 BasicBlock *BB = &*FI++;
695 if (!BB->isEHPad())
696 continue;
697 if (DemoteCatchSwitchPHIOnly && !isa<CatchSwitchInst>(BB->getFirstNonPHI()))
698 continue;
699
700 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
701 Instruction *I = &*BI++;
702 auto *PN = dyn_cast<PHINode>(I);
703 // Stop at the first non-PHI.
704 if (!PN)
705 break;
706
707 AllocaInst *SpillSlot = insertPHILoads(PN, F);
708 if (SpillSlot)
709 insertPHIStores(PN, SpillSlot);
710
711 PHINodes.push_back(PN);
712 }
713 }
714
715 for (auto *PN : PHINodes) {
716 // There may be lingering uses on other EH PHIs being removed
717 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
718 PN->eraseFromParent();
719 }
720}
721
722void WinEHPrepare::cloneCommonBlocks(Function &F) {
723 // We need to clone all blocks which belong to multiple funclets. Values are
724 // remapped throughout the funclet to propagate both the new instructions
725 // *and* the new basic blocks themselves.
726 for (auto &Funclets : FuncletBlocks) {
727 BasicBlock *FuncletPadBB = Funclets.first;
728 std::vector<BasicBlock *> &BlocksInFunclet = Funclets.second;
729 Value *FuncletToken;
730 if (FuncletPadBB == &F.getEntryBlock())
731 FuncletToken = ConstantTokenNone::get(F.getContext());
732 else
733 FuncletToken = FuncletPadBB->getFirstNonPHI();
734
735 std::vector<std::pair<BasicBlock *, BasicBlock *>> Orig2Clone;
736 ValueToValueMapTy VMap;
737 for (BasicBlock *BB : BlocksInFunclet) {
738 ColorVector &ColorsForBB = BlockColors[BB];
739 // We don't need to do anything if the block is monochromatic.
740 size_t NumColorsForBB = ColorsForBB.size();
741 if (NumColorsForBB == 1)
742 continue;
743
744 DEBUG_WITH_TYPE("winehprepare-coloring",do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Cloning block \'"
<< BB->getName() << "\' for funclet \'" <<
FuncletPadBB->getName() << "\'.\n"; } } while (false
)
745 dbgs() << " Cloning block \'" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Cloning block \'"
<< BB->getName() << "\' for funclet \'" <<
FuncletPadBB->getName() << "\'.\n"; } } while (false
)
746 << "\' for funclet \'" << FuncletPadBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Cloning block \'"
<< BB->getName() << "\' for funclet \'" <<
FuncletPadBB->getName() << "\'.\n"; } } while (false
)
747 << "\'.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Cloning block \'"
<< BB->getName() << "\' for funclet \'" <<
FuncletPadBB->getName() << "\'.\n"; } } while (false
)
;
748
749 // Create a new basic block and copy instructions into it!
750 BasicBlock *CBB =
751 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
752 // Insert the clone immediately after the original to ensure determinism
753 // and to keep the same relative ordering of any funclet's blocks.
754 CBB->insertInto(&F, BB->getNextNode());
755
756 // Add basic block mapping.
757 VMap[BB] = CBB;
758
759 // Record delta operations that we need to perform to our color mappings.
760 Orig2Clone.emplace_back(BB, CBB);
761 }
762
763 // If nothing was cloned, we're done cloning in this funclet.
764 if (Orig2Clone.empty())
765 continue;
766
767 // Update our color mappings to reflect that one block has lost a color and
768 // another has gained a color.
769 for (auto &BBMapping : Orig2Clone) {
770 BasicBlock *OldBlock = BBMapping.first;
771 BasicBlock *NewBlock = BBMapping.second;
772
773 BlocksInFunclet.push_back(NewBlock);
774 ColorVector &NewColors = BlockColors[NewBlock];
775 assert(NewColors.empty() && "A new block should only have one color!")((NewColors.empty() && "A new block should only have one color!"
) ? static_cast<void> (0) : __assert_fail ("NewColors.empty() && \"A new block should only have one color!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 775, __PRETTY_FUNCTION__))
;
776 NewColors.push_back(FuncletPadBB);
777
778 DEBUG_WITH_TYPE("winehprepare-coloring",do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Assigned color \'"
<< FuncletPadBB->getName() << "\' to block \'"
<< NewBlock->getName() << "\'.\n"; } } while (
false)
779 dbgs() << " Assigned color \'" << FuncletPadBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Assigned color \'"
<< FuncletPadBB->getName() << "\' to block \'"
<< NewBlock->getName() << "\'.\n"; } } while (
false)
780 << "\' to block \'" << NewBlock->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Assigned color \'"
<< FuncletPadBB->getName() << "\' to block \'"
<< NewBlock->getName() << "\'.\n"; } } while (
false)
781 << "\'.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Assigned color \'"
<< FuncletPadBB->getName() << "\' to block \'"
<< NewBlock->getName() << "\'.\n"; } } while (
false)
;
782
783 BlocksInFunclet.erase(
784 std::remove(BlocksInFunclet.begin(), BlocksInFunclet.end(), OldBlock),
785 BlocksInFunclet.end());
786 ColorVector &OldColors = BlockColors[OldBlock];
787 OldColors.erase(
788 std::remove(OldColors.begin(), OldColors.end(), FuncletPadBB),
789 OldColors.end());
790
791 DEBUG_WITH_TYPE("winehprepare-coloring",do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Removed color \'"
<< FuncletPadBB->getName() << "\' from block \'"
<< OldBlock->getName() << "\'.\n"; } } while (
false)
792 dbgs() << " Removed color \'" << FuncletPadBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Removed color \'"
<< FuncletPadBB->getName() << "\' from block \'"
<< OldBlock->getName() << "\'.\n"; } } while (
false)
793 << "\' from block \'" << OldBlock->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Removed color \'"
<< FuncletPadBB->getName() << "\' from block \'"
<< OldBlock->getName() << "\'.\n"; } } while (
false)
794 << "\'.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Removed color \'"
<< FuncletPadBB->getName() << "\' from block \'"
<< OldBlock->getName() << "\'.\n"; } } while (
false)
;
795 }
796
797 // Loop over all of the instructions in this funclet, fixing up operand
798 // references as we go. This uses VMap to do all the hard work.
799 for (BasicBlock *BB : BlocksInFunclet)
800 // Loop over all instructions, fixing each one as we find it...
801 for (Instruction &I : *BB)
802 RemapInstruction(&I, VMap,
803 RF_IgnoreMissingLocals | RF_NoModuleLevelChanges);
804
805 // Catchrets targeting cloned blocks need to be updated separately from
806 // the loop above because they are not in the current funclet.
807 SmallVector<CatchReturnInst *, 2> FixupCatchrets;
808 for (auto &BBMapping : Orig2Clone) {
809 BasicBlock *OldBlock = BBMapping.first;
810 BasicBlock *NewBlock = BBMapping.second;
811
812 FixupCatchrets.clear();
813 for (BasicBlock *Pred : predecessors(OldBlock))
814 if (auto *CatchRet = dyn_cast<CatchReturnInst>(Pred->getTerminator()))
815 if (CatchRet->getCatchSwitchParentPad() == FuncletToken)
816 FixupCatchrets.push_back(CatchRet);
817
818 for (CatchReturnInst *CatchRet : FixupCatchrets)
819 CatchRet->setSuccessor(NewBlock);
820 }
821
822 auto UpdatePHIOnClonedBlock = [&](PHINode *PN, bool IsForOldBlock) {
823 unsigned NumPreds = PN->getNumIncomingValues();
824 for (unsigned PredIdx = 0, PredEnd = NumPreds; PredIdx != PredEnd;
825 ++PredIdx) {
826 BasicBlock *IncomingBlock = PN->getIncomingBlock(PredIdx);
827 bool EdgeTargetsFunclet;
828 if (auto *CRI =
829 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
830 EdgeTargetsFunclet = (CRI->getCatchSwitchParentPad() == FuncletToken);
831 } else {
832 ColorVector &IncomingColors = BlockColors[IncomingBlock];
833 assert(!IncomingColors.empty() && "Block not colored!")((!IncomingColors.empty() && "Block not colored!") ? static_cast
<void> (0) : __assert_fail ("!IncomingColors.empty() && \"Block not colored!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 833, __PRETTY_FUNCTION__))
;
834 assert((IncomingColors.size() == 1 ||(((IncomingColors.size() == 1 || llvm::all_of(IncomingColors,
[&](BasicBlock *Color) { return Color != FuncletPadBB; }
)) && "Cloning should leave this funclet's blocks monochromatic"
) ? static_cast<void> (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 839, __PRETTY_FUNCTION__))
835 llvm::all_of(IncomingColors,(((IncomingColors.size() == 1 || llvm::all_of(IncomingColors,
[&](BasicBlock *Color) { return Color != FuncletPadBB; }
)) && "Cloning should leave this funclet's blocks monochromatic"
) ? static_cast<void> (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 839, __PRETTY_FUNCTION__))
836 [&](BasicBlock *Color) {(((IncomingColors.size() == 1 || llvm::all_of(IncomingColors,
[&](BasicBlock *Color) { return Color != FuncletPadBB; }
)) && "Cloning should leave this funclet's blocks monochromatic"
) ? static_cast<void> (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 839, __PRETTY_FUNCTION__))
837 return Color != FuncletPadBB;(((IncomingColors.size() == 1 || llvm::all_of(IncomingColors,
[&](BasicBlock *Color) { return Color != FuncletPadBB; }
)) && "Cloning should leave this funclet's blocks monochromatic"
) ? static_cast<void> (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 839, __PRETTY_FUNCTION__))
838 })) &&(((IncomingColors.size() == 1 || llvm::all_of(IncomingColors,
[&](BasicBlock *Color) { return Color != FuncletPadBB; }
)) && "Cloning should leave this funclet's blocks monochromatic"
) ? static_cast<void> (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 839, __PRETTY_FUNCTION__))
839 "Cloning should leave this funclet's blocks monochromatic")(((IncomingColors.size() == 1 || llvm::all_of(IncomingColors,
[&](BasicBlock *Color) { return Color != FuncletPadBB; }
)) && "Cloning should leave this funclet's blocks monochromatic"
) ? static_cast<void> (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 839, __PRETTY_FUNCTION__))
;
840 EdgeTargetsFunclet = (IncomingColors.front() == FuncletPadBB);
841 }
842 if (IsForOldBlock != EdgeTargetsFunclet)
843 continue;
844 PN->removeIncomingValue(IncomingBlock, /*DeletePHIIfEmpty=*/false);
845 // Revisit the next entry.
846 --PredIdx;
847 --PredEnd;
848 }
849 };
850
851 for (auto &BBMapping : Orig2Clone) {
852 BasicBlock *OldBlock = BBMapping.first;
853 BasicBlock *NewBlock = BBMapping.second;
854 for (PHINode &OldPN : OldBlock->phis()) {
855 UpdatePHIOnClonedBlock(&OldPN, /*IsForOldBlock=*/true);
856 }
857 for (PHINode &NewPN : NewBlock->phis()) {
858 UpdatePHIOnClonedBlock(&NewPN, /*IsForOldBlock=*/false);
859 }
860 }
861
862 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
863 // the PHI nodes for NewBB now.
864 for (auto &BBMapping : Orig2Clone) {
865 BasicBlock *OldBlock = BBMapping.first;
866 BasicBlock *NewBlock = BBMapping.second;
867 for (BasicBlock *SuccBB : successors(NewBlock)) {
868 for (PHINode &SuccPN : SuccBB->phis()) {
869 // Ok, we have a PHI node. Figure out what the incoming value was for
870 // the OldBlock.
871 int OldBlockIdx = SuccPN.getBasicBlockIndex(OldBlock);
872 if (OldBlockIdx == -1)
873 break;
874 Value *IV = SuccPN.getIncomingValue(OldBlockIdx);
875
876 // Remap the value if necessary.
877 if (auto *Inst = dyn_cast<Instruction>(IV)) {
878 ValueToValueMapTy::iterator I = VMap.find(Inst);
879 if (I != VMap.end())
880 IV = I->second;
881 }
882
883 SuccPN.addIncoming(IV, NewBlock);
884 }
885 }
886 }
887
888 for (ValueToValueMapTy::value_type VT : VMap) {
889 // If there were values defined in BB that are used outside the funclet,
890 // then we now have to update all uses of the value to use either the
891 // original value, the cloned value, or some PHI derived value. This can
892 // require arbitrary PHI insertion, of which we are prepared to do, clean
893 // these up now.
894 SmallVector<Use *, 16> UsesToRename;
895
896 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
897 if (!OldI)
898 continue;
899 auto *NewI = cast<Instruction>(VT.second);
900 // Scan all uses of this instruction to see if it is used outside of its
901 // funclet, and if so, record them in UsesToRename.
902 for (Use &U : OldI->uses()) {
903 Instruction *UserI = cast<Instruction>(U.getUser());
904 BasicBlock *UserBB = UserI->getParent();
905 ColorVector &ColorsForUserBB = BlockColors[UserBB];
906 assert(!ColorsForUserBB.empty())((!ColorsForUserBB.empty()) ? static_cast<void> (0) : __assert_fail
("!ColorsForUserBB.empty()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 906, __PRETTY_FUNCTION__))
;
907 if (ColorsForUserBB.size() > 1 ||
908 *ColorsForUserBB.begin() != FuncletPadBB)
909 UsesToRename.push_back(&U);
910 }
911
912 // If there are no uses outside the block, we're done with this
913 // instruction.
914 if (UsesToRename.empty())
915 continue;
916
917 // We found a use of OldI outside of the funclet. Rename all uses of OldI
918 // that are outside its funclet to be uses of the appropriate PHI node
919 // etc.
920 SSAUpdater SSAUpdate;
921 SSAUpdate.Initialize(OldI->getType(), OldI->getName());
922 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
923 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
924
925 while (!UsesToRename.empty())
926 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
927 }
928 }
929}
930
931void WinEHPrepare::removeImplausibleInstructions(Function &F) {
932 // Remove implausible terminators and replace them with UnreachableInst.
933 for (auto &Funclet : FuncletBlocks) {
934 BasicBlock *FuncletPadBB = Funclet.first;
935 std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
936 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
937 auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
938 auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
939 auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
940
941 for (BasicBlock *BB : BlocksInFunclet) {
942 for (Instruction &I : *BB) {
943 CallSite CS(&I);
944 if (!CS)
945 continue;
946
947 Value *FuncletBundleOperand = nullptr;
948 if (auto BU = CS.getOperandBundle(LLVMContext::OB_funclet))
949 FuncletBundleOperand = BU->Inputs.front();
950
951 if (FuncletBundleOperand == FuncletPad)
952 continue;
953
954 // Skip call sites which are nounwind intrinsics or inline asm.
955 auto *CalledFn =
956 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
957 if (CalledFn && ((CalledFn->isIntrinsic() && CS.doesNotThrow()) ||
958 CS.isInlineAsm()))
959 continue;
960
961 // This call site was not part of this funclet, remove it.
962 if (CS.isInvoke()) {
963 // Remove the unwind edge if it was an invoke.
964 removeUnwindEdge(BB);
965 // Get a pointer to the new call.
966 BasicBlock::iterator CallI =
967 std::prev(BB->getTerminator()->getIterator());
968 auto *CI = cast<CallInst>(&*CallI);
969 changeToUnreachable(CI, /*UseLLVMTrap=*/false);
970 } else {
971 changeToUnreachable(&I, /*UseLLVMTrap=*/false);
972 }
973
974 // There are no more instructions in the block (except for unreachable),
975 // we are done.
976 break;
977 }
978
979 Instruction *TI = BB->getTerminator();
980 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
981 bool IsUnreachableRet = isa<ReturnInst>(TI) && FuncletPad;
982 // The token consumed by a CatchReturnInst must match the funclet token.
983 bool IsUnreachableCatchret = false;
984 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
985 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
986 // The token consumed by a CleanupReturnInst must match the funclet token.
987 bool IsUnreachableCleanupret = false;
988 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
989 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
990 if (IsUnreachableRet || IsUnreachableCatchret ||
991 IsUnreachableCleanupret) {
992 changeToUnreachable(TI, /*UseLLVMTrap=*/false);
993 } else if (isa<InvokeInst>(TI)) {
994 if (Personality == EHPersonality::MSVC_CXX && CleanupPad) {
995 // Invokes within a cleanuppad for the MSVC++ personality never
996 // transfer control to their unwind edge: the personality will
997 // terminate the program.
998 removeUnwindEdge(BB);
999 }
1000 }
1001 }
1002 }
1003}
1004
1005void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
1006 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
1007 // branches, etc.
1008 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
1009 BasicBlock *BB = &*FI++;
1010 SimplifyInstructionsInBlock(BB);
1011 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
1012 MergeBlockIntoPredecessor(BB);
1013 }
1014
1015 // We might have some unreachable blocks after cleaning up some impossible
1016 // control flow.
1017 removeUnreachableBlocks(F);
1018}
1019
1020#ifndef NDEBUG
1021void WinEHPrepare::verifyPreparedFunclets(Function &F) {
1022 for (BasicBlock &BB : F) {
1023 size_t NumColors = BlockColors[&BB].size();
1024 assert(NumColors == 1 && "Expected monochromatic BB!")((NumColors == 1 && "Expected monochromatic BB!") ? static_cast
<void> (0) : __assert_fail ("NumColors == 1 && \"Expected monochromatic BB!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 1024, __PRETTY_FUNCTION__))
;
1025 if (NumColors == 0)
1026 report_fatal_error("Uncolored BB!");
1027 if (NumColors > 1)
1028 report_fatal_error("Multicolor BB!");
1029 assert((DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) &&(((DisableDemotion || !(BB.isEHPad() && isa<PHINode
>(BB.begin()))) && "EH Pad still has a PHI!") ? static_cast
<void> (0) : __assert_fail ("(DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) && \"EH Pad still has a PHI!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 1030, __PRETTY_FUNCTION__))
1030 "EH Pad still has a PHI!")(((DisableDemotion || !(BB.isEHPad() && isa<PHINode
>(BB.begin()))) && "EH Pad still has a PHI!") ? static_cast
<void> (0) : __assert_fail ("(DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) && \"EH Pad still has a PHI!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 1030, __PRETTY_FUNCTION__))
;
1031 }
1032}
1033#endif
1034
1035bool WinEHPrepare::prepareExplicitEH(Function &F) {
1036 // Remove unreachable blocks. It is not valuable to assign them a color and
1037 // their existence can trick us into thinking values are alive when they are
1038 // not.
1039 removeUnreachableBlocks(F);
1040
1041 // Determine which blocks are reachable from which funclet entries.
1042 colorFunclets(F);
1043
1044 cloneCommonBlocks(F);
1045
1046 if (!DisableDemotion)
1047 demotePHIsOnFunclets(F, DemoteCatchSwitchPHIOnly ||
1048 DemoteCatchSwitchPHIOnlyOpt);
1049
1050 if (!DisableCleanups) {
1051 LLVM_DEBUG(verifyFunction(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { verifyFunction(F); } } while (false)
;
1052 removeImplausibleInstructions(F);
1053
1054 LLVM_DEBUG(verifyFunction(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { verifyFunction(F); } } while (false)
;
1055 cleanupPreparedFunclets(F);
1056 }
1057
1058 LLVM_DEBUG(verifyPreparedFunclets(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { verifyPreparedFunclets(F); } } while (false
)
;
1059 // Recolor the CFG to verify that all is well.
1060 LLVM_DEBUG(colorFunclets(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { colorFunclets(F); } } while (false)
;
1061 LLVM_DEBUG(verifyPreparedFunclets(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { verifyPreparedFunclets(F); } } while (false
)
;
1062
1063 BlockColors.clear();
1064 FuncletBlocks.clear();
1065
1066 return true;
1067}
1068
1069// TODO: Share loads when one use dominates another, or when a catchpad exit
1070// dominates uses (needs dominators).
1071AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
1072 BasicBlock *PHIBlock = PN->getParent();
1073 AllocaInst *SpillSlot = nullptr;
1074 Instruction *EHPad = PHIBlock->getFirstNonPHI();
1075
1076 if (!EHPad->isTerminator()) {
1077 // If the EHPad isn't a terminator, then we can insert a load in this block
1078 // that will dominate all uses.
1079 SpillSlot = new AllocaInst(PN->getType(), DL->getAllocaAddrSpace(), nullptr,
1080 Twine(PN->getName(), ".wineh.spillslot"),
1081 &F.getEntryBlock().front());
1082 Value *V = new LoadInst(PN->getType(), SpillSlot,
1083 Twine(PN->getName(), ".wineh.reload"),
1084 &*PHIBlock->getFirstInsertionPt());
1085 PN->replaceAllUsesWith(V);
1086 return SpillSlot;
1087 }
1088
1089 // Otherwise, we have a PHI on a terminator EHPad, and we give up and insert
1090 // loads of the slot before every use.
1091 DenseMap<BasicBlock *, Value *> Loads;
1092 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1093 UI != UE;) {
1094 Use &U = *UI++;
1095 auto *UsingInst = cast<Instruction>(U.getUser());
1096 if (isa<PHINode>(UsingInst) && UsingInst->getParent()->isEHPad()) {
1097 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
1098 // stores for it separately.
1099 continue;
1100 }
1101 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
1102 }
1103 return SpillSlot;
1104}
1105
1106// TODO: improve store placement. Inserting at def is probably good, but need
1107// to be careful not to introduce interfering stores (needs liveness analysis).
1108// TODO: identify related phi nodes that can share spill slots, and share them
1109// (also needs liveness).
1110void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
1111 AllocaInst *SpillSlot) {
1112 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
1113 // stored to the spill slot by the end of the given Block.
1114 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
1115
1116 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
1117
1118 while (!Worklist.empty()) {
1119 BasicBlock *EHBlock;
1120 Value *InVal;
1121 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
1122
1123 PHINode *PN = dyn_cast<PHINode>(InVal);
1124 if (PN && PN->getParent() == EHBlock) {
1125 // The value is defined by another PHI we need to remove, with no room to
1126 // insert a store after the PHI, so each predecessor needs to store its
1127 // incoming value.
1128 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1129 Value *PredVal = PN->getIncomingValue(i);
1130
1131 // Undef can safely be skipped.
1132 if (isa<UndefValue>(PredVal))
1133 continue;
1134
1135 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
1136 }
1137 } else {
1138 // We need to store InVal, which dominates EHBlock, but can't put a store
1139 // in EHBlock, so need to put stores in each predecessor.
1140 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
1141 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
1142 }
1143 }
1144 }
1145}
1146
1147void WinEHPrepare::insertPHIStore(
1148 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
1149 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
1150
1151 if (PredBlock->isEHPad() && PredBlock->getFirstNonPHI()->isTerminator()) {
1152 // Pred is unsplittable, so we need to queue it on the worklist.
1153 Worklist.push_back({PredBlock, PredVal});
1154 return;
1155 }
1156
1157 // Otherwise, insert the store at the end of the basic block.
1158 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
1159}
1160
1161void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
1162 DenseMap<BasicBlock *, Value *> &Loads,
1163 Function &F) {
1164 // Lazilly create the spill slot.
1165 if (!SpillSlot)
1166 SpillSlot = new AllocaInst(V->getType(), DL->getAllocaAddrSpace(), nullptr,
1167 Twine(V->getName(), ".wineh.spillslot"),
1168 &F.getEntryBlock().front());
1169
1170 auto *UsingInst = cast<Instruction>(U.getUser());
1171 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
1172 // If this is a PHI node, we can't insert a load of the value before
1173 // the use. Instead insert the load in the predecessor block
1174 // corresponding to the incoming value.
1175 //
1176 // Note that if there are multiple edges from a basic block to this
1177 // PHI node that we cannot have multiple loads. The problem is that
1178 // the resulting PHI node will have multiple values (from each load)
1179 // coming in from the same block, which is illegal SSA form.
1180 // For this reason, we keep track of and reuse loads we insert.
1181 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
1182 if (auto *CatchRet =
1183 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1184 // Putting a load above a catchret and use on the phi would still leave
1185 // a cross-funclet def/use. We need to split the edge, change the
1186 // catchret to target the new block, and put the load there.
1187 BasicBlock *PHIBlock = UsingInst->getParent();
1188 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
1189 // SplitEdge gives us:
1190 // IncomingBlock:
1191 // ...
1192 // br label %NewBlock
1193 // NewBlock:
1194 // catchret label %PHIBlock
1195 // But we need:
1196 // IncomingBlock:
1197 // ...
1198 // catchret label %NewBlock
1199 // NewBlock:
1200 // br label %PHIBlock
1201 // So move the terminators to each others' blocks and swap their
1202 // successors.
1203 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
1204 Goto->removeFromParent();
1205 CatchRet->removeFromParent();
1206 IncomingBlock->getInstList().push_back(CatchRet);
1207 NewBlock->getInstList().push_back(Goto);
1208 Goto->setSuccessor(0, PHIBlock);
1209 CatchRet->setSuccessor(NewBlock);
1210 // Update the color mapping for the newly split edge.
1211 // Grab a reference to the ColorVector to be inserted before getting the
1212 // reference to the vector we are copying because inserting the new
1213 // element in BlockColors might cause the map to be reallocated.
1214 ColorVector &ColorsForNewBlock = BlockColors[NewBlock];
1215 ColorVector &ColorsForPHIBlock = BlockColors[PHIBlock];
1216 ColorsForNewBlock = ColorsForPHIBlock;
1217 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
1218 FuncletBlocks[FuncletPad].push_back(NewBlock);
1219 // Treat the new block as incoming for load insertion.
1220 IncomingBlock = NewBlock;
1221 }
1222 Value *&Load = Loads[IncomingBlock];
1223 // Insert the load into the predecessor block
1224 if (!Load)
1225 Load = new LoadInst(V->getType(), SpillSlot,
1226 Twine(V->getName(), ".wineh.reload"),
1227 /*isVolatile=*/false, IncomingBlock->getTerminator());
1228
1229 U.set(Load);
1230 } else {
1231 // Reload right before the old use.
1232 auto *Load = new LoadInst(V->getType(), SpillSlot,
1233 Twine(V->getName(), ".wineh.reload"),
1234 /*isVolatile=*/false, UsingInst);
1235 U.set(Load);
1236 }
1237}
1238
1239void WinEHFuncInfo::addIPToStateRange(const InvokeInst *II,
1240 MCSymbol *InvokeBegin,
1241 MCSymbol *InvokeEnd) {
1242 assert(InvokeStateMap.count(II) &&((InvokeStateMap.count(II) && "should get invoke with precomputed state"
) ? static_cast<void> (0) : __assert_fail ("InvokeStateMap.count(II) && \"should get invoke with precomputed state\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 1243, __PRETTY_FUNCTION__))
1243 "should get invoke with precomputed state")((InvokeStateMap.count(II) && "should get invoke with precomputed state"
) ? static_cast<void> (0) : __assert_fail ("InvokeStateMap.count(II) && \"should get invoke with precomputed state\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/CodeGen/WinEHPrepare.cpp"
, 1243, __PRETTY_FUNCTION__))
;
1244 LabelToStateMap[InvokeBegin] = std::make_pair(InvokeStateMap[II], InvokeEnd);
1245}
1246
1247WinEHFuncInfo::WinEHFuncInfo() {}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/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/None.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/ADT/iterator.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/CallingConv.h"
29#include "llvm/IR/Constant.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/OperandTraits.h"
35#include "llvm/IR/Type.h"
36#include "llvm/IR/Use.h"
37#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
39#include "llvm/Support/AtomicOrdering.h"
40#include "llvm/Support/Casting.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <cassert>
43#include <cstddef>
44#include <cstdint>
45#include <iterator>
46
47namespace llvm {
48
49class APInt;
50class ConstantInt;
51class DataLayout;
52class LLVMContext;
53
54//===----------------------------------------------------------------------===//
55// AllocaInst Class
56//===----------------------------------------------------------------------===//
57
58/// an instruction to allocate memory on the stack
59class AllocaInst : public UnaryInstruction {
60 Type *AllocatedType;
61
62protected:
63 // Note: Instruction needs to be a friend here to call cloneImpl.
64 friend class Instruction;
65
66 AllocaInst *cloneImpl() const;
67
68public:
69 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
70 Value *ArraySize = nullptr,
71 const Twine &Name = "",
72 Instruction *InsertBefore = nullptr);
73 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
74 const Twine &Name, BasicBlock *InsertAtEnd);
75
76 AllocaInst(Type *Ty, unsigned AddrSpace,
77 const Twine &Name, Instruction *InsertBefore = nullptr);
78 AllocaInst(Type *Ty, unsigned AddrSpace,
79 const Twine &Name, BasicBlock *InsertAtEnd);
80
81 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, MaybeAlign Align,
82 const Twine &Name = "", Instruction *InsertBefore = nullptr);
83 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, MaybeAlign Align,
84 const Twine &Name, BasicBlock *InsertAtEnd);
85
86 /// Return true if there is an allocation size parameter to the allocation
87 /// instruction that is not 1.
88 bool isArrayAllocation() const;
89
90 /// Get the number of elements allocated. For a simple allocation of a single
91 /// element, this will return a constant 1 value.
92 const Value *getArraySize() const { return getOperand(0); }
93 Value *getArraySize() { return getOperand(0); }
94
95 /// Overload to return most specific pointer type.
96 PointerType *getType() const {
97 return cast<PointerType>(Instruction::getType());
98 }
99
100 /// Get allocation size in bits. Returns None if size can't be determined,
101 /// e.g. in case of a VLA.
102 Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const;
103
104 /// Return the type that is being allocated by the instruction.
105 Type *getAllocatedType() const { return AllocatedType; }
106 /// for use only in special circumstances that need to generically
107 /// transform a whole instruction (eg: IR linking and vectorization).
108 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
109
110 /// Return the alignment of the memory that is being allocated by the
111 /// instruction.
112 unsigned getAlignment() const {
113 if (const auto MA = decodeMaybeAlign(getSubclassDataFromInstruction() & 31))
114 return MA->value();
115 return 0;
116 }
117 void setAlignment(MaybeAlign Align);
118
119 /// Return true if this alloca is in the entry block of the function and is a
120 /// constant size. If so, the code generator will fold it into the
121 /// prolog/epilog code, so it is basically free.
122 bool isStaticAlloca() const;
123
124 /// Return true if this alloca is used as an inalloca argument to a call. Such
125 /// allocas are never considered static even if they are in the entry block.
126 bool isUsedWithInAlloca() const {
127 return getSubclassDataFromInstruction() & 32;
128 }
129
130 /// Specify whether this alloca is used to represent the arguments to a call.
131 void setUsedWithInAlloca(bool V) {
132 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
133 (V ? 32 : 0));
134 }
135
136 /// Return true if this alloca is used as a swifterror argument to a call.
137 bool isSwiftError() const {
138 return getSubclassDataFromInstruction() & 64;
139 }
140
141 /// Specify whether this alloca is used to represent a swifterror.
142 void setSwiftError(bool V) {
143 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
144 (V ? 64 : 0));
145 }
146
147 // Methods for support type inquiry through isa, cast, and dyn_cast:
148 static bool classof(const Instruction *I) {
149 return (I->getOpcode() == Instruction::Alloca);
150 }
151 static bool classof(const Value *V) {
152 return isa<Instruction>(V) && classof(cast<Instruction>(V));
153 }
154
155private:
156 // Shadow Instruction::setInstructionSubclassData with a private forwarding
157 // method so that subclasses cannot accidentally use it.
158 void setInstructionSubclassData(unsigned short D) {
159 Instruction::setInstructionSubclassData(D);
160 }
161};
162
163//===----------------------------------------------------------------------===//
164// LoadInst Class
165//===----------------------------------------------------------------------===//
166
167/// An instruction for reading from memory. This uses the SubclassData field in
168/// Value to store whether or not the load is volatile.
169class LoadInst : public UnaryInstruction {
170 void AssertOK();
171
172protected:
173 // Note: Instruction needs to be a friend here to call cloneImpl.
174 friend class Instruction;
175
176 LoadInst *cloneImpl() const;
177
178public:
179 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
180 Instruction *InsertBefore = nullptr);
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
182 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
183 Instruction *InsertBefore = nullptr);
184 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185 BasicBlock *InsertAtEnd);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 MaybeAlign Align, Instruction *InsertBefore = nullptr);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 MaybeAlign Align, BasicBlock *InsertAtEnd);
190 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
191 MaybeAlign Align, AtomicOrdering Order,
192 SyncScope::ID SSID = SyncScope::System,
193 Instruction *InsertBefore = nullptr);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
196 BasicBlock *InsertAtEnd);
197
198 // Deprecated [opaque pointer types]
199 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
200 Instruction *InsertBefore = nullptr)
201 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
202 InsertBefore) {}
203 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
204 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
205 InsertAtEnd) {}
206 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
207 Instruction *InsertBefore = nullptr)
208 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
209 isVolatile, InsertBefore) {}
210 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
211 BasicBlock *InsertAtEnd)
212 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
213 isVolatile, InsertAtEnd) {}
214 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
215 Instruction *InsertBefore = nullptr)
216 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
217 isVolatile, Align, InsertBefore) {}
218 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
219 BasicBlock *InsertAtEnd)
220 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
221 isVolatile, Align, InsertAtEnd) {}
222 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
223 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
224 Instruction *InsertBefore = nullptr)
225 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
226 isVolatile, Align, Order, SSID, InsertBefore) {}
227 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
228 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
229 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
230 isVolatile, Align, Order, SSID, InsertAtEnd) {}
231
232 /// Return true if this is a load from a volatile memory location.
233 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
234
235 /// Specify whether this is a volatile load or not.
236 void setVolatile(bool V) {
237 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
238 (V ? 1 : 0));
239 }
240
241 /// Return the alignment of the access that is being performed.
242 unsigned getAlignment() const {
243 if (const auto MA =
244 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
245 return MA->value();
246 return 0;
247 }
248
249 void setAlignment(MaybeAlign Align);
250
251 /// Returns the ordering constraint of this load instruction.
252 AtomicOrdering getOrdering() const {
253 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
254 }
255
256 /// Sets the ordering constraint of this load instruction. May not be Release
257 /// or AcquireRelease.
258 void setOrdering(AtomicOrdering Ordering) {
259 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
260 ((unsigned)Ordering << 7));
261 }
262
263 /// Returns the synchronization scope ID of this load instruction.
264 SyncScope::ID getSyncScopeID() const {
265 return SSID;
266 }
267
268 /// Sets the synchronization scope ID of this load instruction.
269 void setSyncScopeID(SyncScope::ID SSID) {
270 this->SSID = SSID;
271 }
272
273 /// Sets the ordering constraint and the synchronization scope ID of this load
274 /// instruction.
275 void setAtomic(AtomicOrdering Ordering,
276 SyncScope::ID SSID = SyncScope::System) {
277 setOrdering(Ordering);
278 setSyncScopeID(SSID);
279 }
280
281 bool isSimple() const { return !isAtomic() && !isVolatile(); }
282
283 bool isUnordered() const {
284 return (getOrdering() == AtomicOrdering::NotAtomic ||
285 getOrdering() == AtomicOrdering::Unordered) &&
286 !isVolatile();
287 }
288
289 Value *getPointerOperand() { return getOperand(0); }
290 const Value *getPointerOperand() const { return getOperand(0); }
291 static unsigned getPointerOperandIndex() { return 0U; }
292 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
293
294 /// Returns the address space of the pointer operand.
295 unsigned getPointerAddressSpace() const {
296 return getPointerOperandType()->getPointerAddressSpace();
297 }
298
299 // Methods for support type inquiry through isa, cast, and dyn_cast:
300 static bool classof(const Instruction *I) {
301 return I->getOpcode() == Instruction::Load;
302 }
303 static bool classof(const Value *V) {
304 return isa<Instruction>(V) && classof(cast<Instruction>(V));
305 }
306
307private:
308 // Shadow Instruction::setInstructionSubclassData with a private forwarding
309 // method so that subclasses cannot accidentally use it.
310 void setInstructionSubclassData(unsigned short D) {
311 Instruction::setInstructionSubclassData(D);
312 }
313
314 /// The synchronization scope ID of this load instruction. Not quite enough
315 /// room in SubClassData for everything, so synchronization scope ID gets its
316 /// own field.
317 SyncScope::ID SSID;
318};
319
320//===----------------------------------------------------------------------===//
321// StoreInst Class
322//===----------------------------------------------------------------------===//
323
324/// An instruction for storing to memory.
325class StoreInst : public Instruction {
326 void AssertOK();
327
328protected:
329 // Note: Instruction needs to be a friend here to call cloneImpl.
330 friend class Instruction;
331
332 StoreInst *cloneImpl() const;
333
334public:
335 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
336 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
337 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
338 Instruction *InsertBefore = nullptr);
339 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
340 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
341 Instruction *InsertBefore = nullptr);
342 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
343 BasicBlock *InsertAtEnd);
344 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
345 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
346 Instruction *InsertBefore = nullptr);
347 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
348 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
349
350 // allocate space for exactly two operands
351 void *operator new(size_t s) {
352 return User::operator new(s, 2);
353 }
354
355 /// Return true if this is a store to a volatile memory location.
356 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
357
358 /// Specify whether this is a volatile store or not.
359 void setVolatile(bool V) {
360 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
361 (V ? 1 : 0));
362 }
363
364 /// Transparently provide more efficient getOperand methods.
365 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
;
366
367 /// Return the alignment of the access that is being performed
368 unsigned getAlignment() const {
369 if (const auto MA =
370 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
371 return MA->value();
372 return 0;
373 }
374
375 void setAlignment(MaybeAlign Align);
376
377 /// Returns the ordering constraint of this store instruction.
378 AtomicOrdering getOrdering() const {
379 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
380 }
381
382 /// Sets the ordering constraint of this store instruction. May not be
383 /// Acquire or AcquireRelease.
384 void setOrdering(AtomicOrdering Ordering) {
385 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
386 ((unsigned)Ordering << 7));
387 }
388
389 /// Returns the synchronization scope ID of this store instruction.
390 SyncScope::ID getSyncScopeID() const {
391 return SSID;
392 }
393
394 /// Sets the synchronization scope ID of this store instruction.
395 void setSyncScopeID(SyncScope::ID SSID) {
396 this->SSID = SSID;
397 }
398
399 /// Sets the ordering constraint and the synchronization scope ID of this
400 /// store instruction.
401 void setAtomic(AtomicOrdering Ordering,
402 SyncScope::ID SSID = SyncScope::System) {
403 setOrdering(Ordering);
404 setSyncScopeID(SSID);
405 }
406
407 bool isSimple() const { return !isAtomic() && !isVolatile(); }
408
409 bool isUnordered() const {
410 return (getOrdering() == AtomicOrdering::NotAtomic ||
411 getOrdering() == AtomicOrdering::Unordered) &&
412 !isVolatile();
413 }
414
415 Value *getValueOperand() { return getOperand(0); }
416 const Value *getValueOperand() const { return getOperand(0); }
417
418 Value *getPointerOperand() { return getOperand(1); }
419 const Value *getPointerOperand() const { return getOperand(1); }
420 static unsigned getPointerOperandIndex() { return 1U; }
421 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
422
423 /// Returns the address space of the pointer operand.
424 unsigned getPointerAddressSpace() const {
425 return getPointerOperandType()->getPointerAddressSpace();
426 }
427
428 // Methods for support type inquiry through isa, cast, and dyn_cast:
429 static bool classof(const Instruction *I) {
430 return I->getOpcode() == Instruction::Store;
431 }
432 static bool classof(const Value *V) {
433 return isa<Instruction>(V) && classof(cast<Instruction>(V));
434 }
435
436private:
437 // Shadow Instruction::setInstructionSubclassData with a private forwarding
438 // method so that subclasses cannot accidentally use it.
439 void setInstructionSubclassData(unsigned short D) {
440 Instruction::setInstructionSubclassData(D);
441 }
442
443 /// The synchronization scope ID of this store instruction. Not quite enough
444 /// room in SubClassData for everything, so synchronization scope ID gets its
445 /// own field.
446 SyncScope::ID SSID;
447};
448
449template <>
450struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
451};
452
453DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 453, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 453, __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
); }
454
455//===----------------------------------------------------------------------===//
456// FenceInst Class
457//===----------------------------------------------------------------------===//
458
459/// An instruction for ordering other memory operations.
460class FenceInst : public Instruction {
461 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
462
463protected:
464 // Note: Instruction needs to be a friend here to call cloneImpl.
465 friend class Instruction;
466
467 FenceInst *cloneImpl() const;
468
469public:
470 // Ordering may only be Acquire, Release, AcquireRelease, or
471 // SequentiallyConsistent.
472 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
473 SyncScope::ID SSID = SyncScope::System,
474 Instruction *InsertBefore = nullptr);
475 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
476 BasicBlock *InsertAtEnd);
477
478 // allocate space for exactly zero operands
479 void *operator new(size_t s) {
480 return User::operator new(s, 0);
481 }
482
483 /// Returns the ordering constraint of this fence instruction.
484 AtomicOrdering getOrdering() const {
485 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
486 }
487
488 /// Sets the ordering constraint of this fence instruction. May only be
489 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
490 void setOrdering(AtomicOrdering Ordering) {
491 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
492 ((unsigned)Ordering << 1));
493 }
494
495 /// Returns the synchronization scope ID of this fence instruction.
496 SyncScope::ID getSyncScopeID() const {
497 return SSID;
498 }
499
500 /// Sets the synchronization scope ID of this fence instruction.
501 void setSyncScopeID(SyncScope::ID SSID) {
502 this->SSID = SSID;
503 }
504
505 // Methods for support type inquiry through isa, cast, and dyn_cast:
506 static bool classof(const Instruction *I) {
507 return I->getOpcode() == Instruction::Fence;
508 }
509 static bool classof(const Value *V) {
510 return isa<Instruction>(V) && classof(cast<Instruction>(V));
511 }
512
513private:
514 // Shadow Instruction::setInstructionSubclassData with a private forwarding
515 // method so that subclasses cannot accidentally use it.
516 void setInstructionSubclassData(unsigned short D) {
517 Instruction::setInstructionSubclassData(D);
518 }
519
520 /// The synchronization scope ID of this fence instruction. Not quite enough
521 /// room in SubClassData for everything, so synchronization scope ID gets its
522 /// own field.
523 SyncScope::ID SSID;
524};
525
526//===----------------------------------------------------------------------===//
527// AtomicCmpXchgInst Class
528//===----------------------------------------------------------------------===//
529
530/// An instruction that atomically checks whether a
531/// specified value is in a memory location, and, if it is, stores a new value
532/// there. The value returned by this instruction is a pair containing the
533/// original value as first element, and an i1 indicating success (true) or
534/// failure (false) as second element.
535///
536class AtomicCmpXchgInst : public Instruction {
537 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
538 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
539 SyncScope::ID SSID);
540
541protected:
542 // Note: Instruction needs to be a friend here to call cloneImpl.
543 friend class Instruction;
544
545 AtomicCmpXchgInst *cloneImpl() const;
546
547public:
548 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
549 AtomicOrdering SuccessOrdering,
550 AtomicOrdering FailureOrdering,
551 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
552 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
553 AtomicOrdering SuccessOrdering,
554 AtomicOrdering FailureOrdering,
555 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
556
557 // allocate space for exactly three operands
558 void *operator new(size_t s) {
559 return User::operator new(s, 3);
560 }
561
562 /// Return true if this is a cmpxchg from a volatile memory
563 /// location.
564 ///
565 bool isVolatile() const {
566 return getSubclassDataFromInstruction() & 1;
567 }
568
569 /// Specify whether this is a volatile cmpxchg.
570 ///
571 void setVolatile(bool V) {
572 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
573 (unsigned)V);
574 }
575
576 /// Return true if this cmpxchg may spuriously fail.
577 bool isWeak() const {
578 return getSubclassDataFromInstruction() & 0x100;
579 }
580
581 void setWeak(bool IsWeak) {
582 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
583 (IsWeak << 8));
584 }
585
586 /// Transparently provide more efficient getOperand methods.
587 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
;
588
589 /// Returns the success ordering constraint of this cmpxchg instruction.
590 AtomicOrdering getSuccessOrdering() const {
591 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
592 }
593
594 /// Sets the success ordering constraint of this cmpxchg instruction.
595 void setSuccessOrdering(AtomicOrdering Ordering) {
596 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 597, __PRETTY_FUNCTION__))
597 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 597, __PRETTY_FUNCTION__))
;
598 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
599 ((unsigned)Ordering << 2));
600 }
601
602 /// Returns the failure ordering constraint of this cmpxchg instruction.
603 AtomicOrdering getFailureOrdering() const {
604 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
605 }
606
607 /// Sets the failure ordering constraint of this cmpxchg instruction.
608 void setFailureOrdering(AtomicOrdering Ordering) {
609 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 610, __PRETTY_FUNCTION__))
610 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 610, __PRETTY_FUNCTION__))
;
611 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
612 ((unsigned)Ordering << 5));
613 }
614
615 /// Returns the synchronization scope ID of this cmpxchg instruction.
616 SyncScope::ID getSyncScopeID() const {
617 return SSID;
618 }
619
620 /// Sets the synchronization scope ID of this cmpxchg instruction.
621 void setSyncScopeID(SyncScope::ID SSID) {
622 this->SSID = SSID;
623 }
624
625 Value *getPointerOperand() { return getOperand(0); }
626 const Value *getPointerOperand() const { return getOperand(0); }
627 static unsigned getPointerOperandIndex() { return 0U; }
628
629 Value *getCompareOperand() { return getOperand(1); }
630 const Value *getCompareOperand() const { return getOperand(1); }
631
632 Value *getNewValOperand() { return getOperand(2); }
633 const Value *getNewValOperand() const { return getOperand(2); }
634
635 /// Returns the address space of the pointer operand.
636 unsigned getPointerAddressSpace() const {
637 return getPointerOperand()->getType()->getPointerAddressSpace();
638 }
639
640 /// Returns the strongest permitted ordering on failure, given the
641 /// desired ordering on success.
642 ///
643 /// If the comparison in a cmpxchg operation fails, there is no atomic store
644 /// so release semantics cannot be provided. So this function drops explicit
645 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
646 /// operation would remain SequentiallyConsistent.
647 static AtomicOrdering
648 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
649 switch (SuccessOrdering) {
650 default:
651 llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 651)
;
652 case AtomicOrdering::Release:
653 case AtomicOrdering::Monotonic:
654 return AtomicOrdering::Monotonic;
655 case AtomicOrdering::AcquireRelease:
656 case AtomicOrdering::Acquire:
657 return AtomicOrdering::Acquire;
658 case AtomicOrdering::SequentiallyConsistent:
659 return AtomicOrdering::SequentiallyConsistent;
660 }
661 }
662
663 // Methods for support type inquiry through isa, cast, and dyn_cast:
664 static bool classof(const Instruction *I) {
665 return I->getOpcode() == Instruction::AtomicCmpXchg;
666 }
667 static bool classof(const Value *V) {
668 return isa<Instruction>(V) && classof(cast<Instruction>(V));
669 }
670
671private:
672 // Shadow Instruction::setInstructionSubclassData with a private forwarding
673 // method so that subclasses cannot accidentally use it.
674 void setInstructionSubclassData(unsigned short D) {
675 Instruction::setInstructionSubclassData(D);
676 }
677
678 /// The synchronization scope ID of this cmpxchg instruction. Not quite
679 /// enough room in SubClassData for everything, so synchronization scope ID
680 /// gets its own field.
681 SyncScope::ID SSID;
682};
683
684template <>
685struct OperandTraits<AtomicCmpXchgInst> :
686 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
687};
688
689DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 689, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 689, __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); }
690
691//===----------------------------------------------------------------------===//
692// AtomicRMWInst Class
693//===----------------------------------------------------------------------===//
694
695/// an instruction that atomically reads a memory location,
696/// combines it with another value, and then stores the result back. Returns
697/// the old value.
698///
699class AtomicRMWInst : public Instruction {
700protected:
701 // Note: Instruction needs to be a friend here to call cloneImpl.
702 friend class Instruction;
703
704 AtomicRMWInst *cloneImpl() const;
705
706public:
707 /// This enumeration lists the possible modifications atomicrmw can make. In
708 /// the descriptions, 'p' is the pointer to the instruction's memory location,
709 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
710 /// instruction. These instructions always return 'old'.
711 enum BinOp {
712 /// *p = v
713 Xchg,
714 /// *p = old + v
715 Add,
716 /// *p = old - v
717 Sub,
718 /// *p = old & v
719 And,
720 /// *p = ~(old & v)
721 Nand,
722 /// *p = old | v
723 Or,
724 /// *p = old ^ v
725 Xor,
726 /// *p = old >signed v ? old : v
727 Max,
728 /// *p = old <signed v ? old : v
729 Min,
730 /// *p = old >unsigned v ? old : v
731 UMax,
732 /// *p = old <unsigned v ? old : v
733 UMin,
734
735 /// *p = old + v
736 FAdd,
737
738 /// *p = old - v
739 FSub,
740
741 FIRST_BINOP = Xchg,
742 LAST_BINOP = FSub,
743 BAD_BINOP
744 };
745
746 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
747 AtomicOrdering Ordering, SyncScope::ID SSID,
748 Instruction *InsertBefore = nullptr);
749 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
750 AtomicOrdering Ordering, SyncScope::ID SSID,
751 BasicBlock *InsertAtEnd);
752
753 // allocate space for exactly two operands
754 void *operator new(size_t s) {
755 return User::operator new(s, 2);
756 }
757
758 BinOp getOperation() const {
759 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
760 }
761
762 static StringRef getOperationName(BinOp Op);
763
764 static bool isFPOperation(BinOp Op) {
765 switch (Op) {
766 case AtomicRMWInst::FAdd:
767 case AtomicRMWInst::FSub:
768 return true;
769 default:
770 return false;
771 }
772 }
773
774 void setOperation(BinOp Operation) {
775 unsigned short SubclassData = getSubclassDataFromInstruction();
776 setInstructionSubclassData((SubclassData & 31) |
777 (Operation << 5));
778 }
779
780 /// Return true if this is a RMW on a volatile memory location.
781 ///
782 bool isVolatile() const {
783 return getSubclassDataFromInstruction() & 1;
784 }
785
786 /// Specify whether this is a volatile RMW or not.
787 ///
788 void setVolatile(bool V) {
789 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
790 (unsigned)V);
791 }
792
793 /// Transparently provide more efficient getOperand methods.
794 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
;
795
796 /// Returns the ordering constraint of this rmw instruction.
797 AtomicOrdering getOrdering() const {
798 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
799 }
800
801 /// Sets the ordering constraint of this rmw instruction.
802 void setOrdering(AtomicOrdering Ordering) {
803 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 804, __PRETTY_FUNCTION__))
804 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 804, __PRETTY_FUNCTION__))
;
805 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
806 ((unsigned)Ordering << 2));
807 }
808
809 /// Returns the synchronization scope ID of this rmw instruction.
810 SyncScope::ID getSyncScopeID() const {
811 return SSID;
812 }
813
814 /// Sets the synchronization scope ID of this rmw instruction.
815 void setSyncScopeID(SyncScope::ID SSID) {
816 this->SSID = SSID;
817 }
818
819 Value *getPointerOperand() { return getOperand(0); }
820 const Value *getPointerOperand() const { return getOperand(0); }
821 static unsigned getPointerOperandIndex() { return 0U; }
822
823 Value *getValOperand() { return getOperand(1); }
824 const Value *getValOperand() const { return getOperand(1); }
825
826 /// Returns the address space of the pointer operand.
827 unsigned getPointerAddressSpace() const {
828 return getPointerOperand()->getType()->getPointerAddressSpace();
829 }
830
831 bool isFloatingPointOperation() const {
832 return isFPOperation(getOperation());
833 }
834
835 // Methods for support type inquiry through isa, cast, and dyn_cast:
836 static bool classof(const Instruction *I) {
837 return I->getOpcode() == Instruction::AtomicRMW;
838 }
839 static bool classof(const Value *V) {
840 return isa<Instruction>(V) && classof(cast<Instruction>(V));
841 }
842
843private:
844 void Init(BinOp Operation, Value *Ptr, Value *Val,
845 AtomicOrdering Ordering, SyncScope::ID SSID);
846
847 // Shadow Instruction::setInstructionSubclassData with a private forwarding
848 // method so that subclasses cannot accidentally use it.
849 void setInstructionSubclassData(unsigned short D) {
850 Instruction::setInstructionSubclassData(D);
851 }
852
853 /// The synchronization scope ID of this rmw instruction. Not quite enough
854 /// room in SubClassData for everything, so synchronization scope ID gets its
855 /// own field.
856 SyncScope::ID SSID;
857};
858
859template <>
860struct OperandTraits<AtomicRMWInst>
861 : public FixedNumOperandTraits<AtomicRMWInst,2> {
862};
863
864DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 864, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 864, __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); }
865
866//===----------------------------------------------------------------------===//
867// GetElementPtrInst Class
868//===----------------------------------------------------------------------===//
869
870// checkGEPType - Simple wrapper function to give a better assertion failure
871// message on bad indexes for a gep instruction.
872//
873inline Type *checkGEPType(Type *Ty) {
874 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 874, __PRETTY_FUNCTION__))
;
875 return Ty;
876}
877
878/// an instruction for type-safe pointer arithmetic to
879/// access elements of arrays and structs
880///
881class GetElementPtrInst : public Instruction {
882 Type *SourceElementType;
883 Type *ResultElementType;
884
885 GetElementPtrInst(const GetElementPtrInst &GEPI);
886
887 /// Constructors - Create a getelementptr instruction with a base pointer an
888 /// list of indices. The first ctor can optionally insert before an existing
889 /// instruction, the second appends the new instruction to the specified
890 /// BasicBlock.
891 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
892 ArrayRef<Value *> IdxList, unsigned Values,
893 const Twine &NameStr, Instruction *InsertBefore);
894 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
895 ArrayRef<Value *> IdxList, unsigned Values,
896 const Twine &NameStr, BasicBlock *InsertAtEnd);
897
898 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
899
900protected:
901 // Note: Instruction needs to be a friend here to call cloneImpl.
902 friend class Instruction;
903
904 GetElementPtrInst *cloneImpl() const;
905
906public:
907 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
908 ArrayRef<Value *> IdxList,
909 const Twine &NameStr = "",
910 Instruction *InsertBefore = nullptr) {
911 unsigned Values = 1 + unsigned(IdxList.size());
912 if (!PointeeType)
913 PointeeType =
914 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
915 else
916 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 918, __PRETTY_FUNCTION__))
917 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 918, __PRETTY_FUNCTION__))
918 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 918, __PRETTY_FUNCTION__))
;
919 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
920 NameStr, InsertBefore);
921 }
922
923 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
924 ArrayRef<Value *> IdxList,
925 const Twine &NameStr,
926 BasicBlock *InsertAtEnd) {
927 unsigned Values = 1 + unsigned(IdxList.size());
928 if (!PointeeType)
929 PointeeType =
930 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
931 else
932 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 934, __PRETTY_FUNCTION__))
933 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 934, __PRETTY_FUNCTION__))
934 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 934, __PRETTY_FUNCTION__))
;
935 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
936 NameStr, InsertAtEnd);
937 }
938
939 /// Create an "inbounds" getelementptr. See the documentation for the
940 /// "inbounds" flag in LangRef.html for details.
941 static GetElementPtrInst *CreateInBounds(Value *Ptr,
942 ArrayRef<Value *> IdxList,
943 const Twine &NameStr = "",
944 Instruction *InsertBefore = nullptr){
945 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
946 }
947
948 static GetElementPtrInst *
949 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
950 const Twine &NameStr = "",
951 Instruction *InsertBefore = nullptr) {
952 GetElementPtrInst *GEP =
953 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
954 GEP->setIsInBounds(true);
955 return GEP;
956 }
957
958 static GetElementPtrInst *CreateInBounds(Value *Ptr,
959 ArrayRef<Value *> IdxList,
960 const Twine &NameStr,
961 BasicBlock *InsertAtEnd) {
962 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
963 }
964
965 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
966 ArrayRef<Value *> IdxList,
967 const Twine &NameStr,
968 BasicBlock *InsertAtEnd) {
969 GetElementPtrInst *GEP =
970 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
971 GEP->setIsInBounds(true);
972 return GEP;
973 }
974
975 /// Transparently provide more efficient getOperand methods.
976 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
;
977
978 Type *getSourceElementType() const { return SourceElementType; }
979
980 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
981 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
982
983 Type *getResultElementType() const {
984 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 985, __PRETTY_FUNCTION__))
985 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 985, __PRETTY_FUNCTION__))
;
986 return ResultElementType;
987 }
988
989 /// Returns the address space of this instruction's pointer type.
990 unsigned getAddressSpace() const {
991 // Note that this is always the same as the pointer operand's address space
992 // and that is cheaper to compute, so cheat here.
993 return getPointerAddressSpace();
994 }
995
996 /// Returns the type of the element that would be loaded with
997 /// a load instruction with the specified parameters.
998 ///
999 /// Null is returned if the indices are invalid for the specified
1000 /// pointer type.
1001 ///
1002 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1003 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1004 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1005
1006 inline op_iterator idx_begin() { return op_begin()+1; }
1007 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1008 inline op_iterator idx_end() { return op_end(); }
1009 inline const_op_iterator idx_end() const { return op_end(); }
1010
1011 inline iterator_range<op_iterator> indices() {
1012 return make_range(idx_begin(), idx_end());
1013 }
1014
1015 inline iterator_range<const_op_iterator> indices() const {
1016 return make_range(idx_begin(), idx_end());
1017 }
1018
1019 Value *getPointerOperand() {
1020 return getOperand(0);
1021 }
1022 const Value *getPointerOperand() const {
1023 return getOperand(0);
1024 }
1025 static unsigned getPointerOperandIndex() {
1026 return 0U; // get index for modifying correct operand.
1027 }
1028
1029 /// Method to return the pointer operand as a
1030 /// PointerType.
1031 Type *getPointerOperandType() const {
1032 return getPointerOperand()->getType();
1033 }
1034
1035 /// Returns the address space of the pointer operand.
1036 unsigned getPointerAddressSpace() const {
1037 return getPointerOperandType()->getPointerAddressSpace();
1038 }
1039
1040 /// Returns the pointer type returned by the GEP
1041 /// instruction, which may be a vector of pointers.
1042 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1043 ArrayRef<Value *> IdxList) {
1044 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1045 Ptr->getType()->getPointerAddressSpace());
1046 // Vector GEP
1047 if (Ptr->getType()->isVectorTy()) {
1048 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1049 return VectorType::get(PtrTy, NumElem);
1050 }
1051 for (Value *Index : IdxList)
1052 if (Index->getType()->isVectorTy()) {
1053 unsigned NumElem = Index->getType()->getVectorNumElements();
1054 return VectorType::get(PtrTy, NumElem);
1055 }
1056 // Scalar GEP
1057 return PtrTy;
1058 }
1059
1060 unsigned getNumIndices() const { // Note: always non-negative
1061 return getNumOperands() - 1;
1062 }
1063
1064 bool hasIndices() const {
1065 return getNumOperands() > 1;
1066 }
1067
1068 /// Return true if all of the indices of this GEP are
1069 /// zeros. If so, the result pointer and the first operand have the same
1070 /// value, just potentially different types.
1071 bool hasAllZeroIndices() const;
1072
1073 /// Return true if all of the indices of this GEP are
1074 /// constant integers. If so, the result pointer and the first operand have
1075 /// a constant offset between them.
1076 bool hasAllConstantIndices() const;
1077
1078 /// Set or clear the inbounds flag on this GEP instruction.
1079 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1080 void setIsInBounds(bool b = true);
1081
1082 /// Determine whether the GEP has the inbounds flag.
1083 bool isInBounds() const;
1084
1085 /// Accumulate the constant address offset of this GEP if possible.
1086 ///
1087 /// This routine accepts an APInt into which it will accumulate the constant
1088 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1089 /// all-constant, it returns false and the value of the offset APInt is
1090 /// undefined (it is *not* preserved!). The APInt passed into this routine
1091 /// must be at least as wide as the IntPtr type for the address space of
1092 /// the base GEP pointer.
1093 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1094
1095 // Methods for support type inquiry through isa, cast, and dyn_cast:
1096 static bool classof(const Instruction *I) {
1097 return (I->getOpcode() == Instruction::GetElementPtr);
1098 }
1099 static bool classof(const Value *V) {
1100 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1101 }
1102};
1103
1104template <>
1105struct OperandTraits<GetElementPtrInst> :
1106 public VariadicOperandTraits<GetElementPtrInst, 1> {
1107};
1108
1109GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1110 ArrayRef<Value *> IdxList, unsigned Values,
1111 const Twine &NameStr,
1112 Instruction *InsertBefore)
1113 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1114 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1115 Values, InsertBefore),
1116 SourceElementType(PointeeType),
1117 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1118 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1119, __PRETTY_FUNCTION__))
1119 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1119, __PRETTY_FUNCTION__))
;
1120 init(Ptr, IdxList, NameStr);
1121}
1122
1123GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1124 ArrayRef<Value *> IdxList, unsigned Values,
1125 const Twine &NameStr,
1126 BasicBlock *InsertAtEnd)
1127 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1128 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1129 Values, InsertAtEnd),
1130 SourceElementType(PointeeType),
1131 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1132 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1133, __PRETTY_FUNCTION__))
1133 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1133, __PRETTY_FUNCTION__))
;
1134 init(Ptr, IdxList, NameStr);
1135}
1136
1137DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1137, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1137, __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); }
1138
1139//===----------------------------------------------------------------------===//
1140// ICmpInst Class
1141//===----------------------------------------------------------------------===//
1142
1143/// This instruction compares its operands according to the predicate given
1144/// to the constructor. It only operates on integers or pointers. The operands
1145/// must be identical types.
1146/// Represent an integer comparison operator.
1147class ICmpInst: public CmpInst {
1148 void AssertOK() {
1149 assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1150, __PRETTY_FUNCTION__))
1150 "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1150, __PRETTY_FUNCTION__))
;
1151 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1152, __PRETTY_FUNCTION__))
1152 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1152, __PRETTY_FUNCTION__))
;
1153 // Check that the operands are the right type
1154 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1156, __PRETTY_FUNCTION__))
1155 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1156, __PRETTY_FUNCTION__))
1156 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1156, __PRETTY_FUNCTION__))
;
1157 }
1158
1159protected:
1160 // Note: Instruction needs to be a friend here to call cloneImpl.
1161 friend class Instruction;
1162
1163 /// Clone an identical ICmpInst
1164 ICmpInst *cloneImpl() const;
1165
1166public:
1167 /// Constructor with insert-before-instruction semantics.
1168 ICmpInst(
1169 Instruction *InsertBefore, ///< Where to insert
1170 Predicate pred, ///< The predicate to use for the comparison
1171 Value *LHS, ///< The left-hand-side of the expression
1172 Value *RHS, ///< The right-hand-side of the expression
1173 const Twine &NameStr = "" ///< Name of the instruction
1174 ) : CmpInst(makeCmpResultType(LHS->getType()),
1175 Instruction::ICmp, pred, LHS, RHS, NameStr,
1176 InsertBefore) {
1177#ifndef NDEBUG
1178 AssertOK();
1179#endif
1180 }
1181
1182 /// Constructor with insert-at-end semantics.
1183 ICmpInst(
1184 BasicBlock &InsertAtEnd, ///< Block to insert into.
1185 Predicate pred, ///< The predicate to use for the comparison
1186 Value *LHS, ///< The left-hand-side of the expression
1187 Value *RHS, ///< The right-hand-side of the expression
1188 const Twine &NameStr = "" ///< Name of the instruction
1189 ) : CmpInst(makeCmpResultType(LHS->getType()),
1190 Instruction::ICmp, pred, LHS, RHS, NameStr,
1191 &InsertAtEnd) {
1192#ifndef NDEBUG
1193 AssertOK();
1194#endif
1195 }
1196
1197 /// Constructor with no-insertion semantics
1198 ICmpInst(
1199 Predicate pred, ///< The predicate to use for the comparison
1200 Value *LHS, ///< The left-hand-side of the expression
1201 Value *RHS, ///< The right-hand-side of the expression
1202 const Twine &NameStr = "" ///< Name of the instruction
1203 ) : CmpInst(makeCmpResultType(LHS->getType()),
1204 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1205#ifndef NDEBUG
1206 AssertOK();
1207#endif
1208 }
1209
1210 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1211 /// @returns the predicate that would be the result if the operand were
1212 /// regarded as signed.
1213 /// Return the signed version of the predicate
1214 Predicate getSignedPredicate() const {
1215 return getSignedPredicate(getPredicate());
1216 }
1217
1218 /// This is a static version that you can use without an instruction.
1219 /// Return the signed version of the predicate.
1220 static Predicate getSignedPredicate(Predicate pred);
1221
1222 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1223 /// @returns the predicate that would be the result if the operand were
1224 /// regarded as unsigned.
1225 /// Return the unsigned version of the predicate
1226 Predicate getUnsignedPredicate() const {
1227 return getUnsignedPredicate(getPredicate());
1228 }
1229
1230 /// This is a static version that you can use without an instruction.
1231 /// Return the unsigned version of the predicate.
1232 static Predicate getUnsignedPredicate(Predicate pred);
1233
1234 /// Return true if this predicate is either EQ or NE. This also
1235 /// tests for commutativity.
1236 static bool isEquality(Predicate P) {
1237 return P == ICMP_EQ || P == ICMP_NE;
1238 }
1239
1240 /// Return true if this predicate is either EQ or NE. This also
1241 /// tests for commutativity.
1242 bool isEquality() const {
1243 return isEquality(getPredicate());
1244 }
1245
1246 /// @returns true if the predicate of this ICmpInst is commutative
1247 /// Determine if this relation is commutative.
1248 bool isCommutative() const { return isEquality(); }
1249
1250 /// Return true if the predicate is relational (not EQ or NE).
1251 ///
1252 bool isRelational() const {
1253 return !isEquality();
1254 }
1255
1256 /// Return true if the predicate is relational (not EQ or NE).
1257 ///
1258 static bool isRelational(Predicate P) {
1259 return !isEquality(P);
1260 }
1261
1262 /// Exchange the two operands to this instruction in such a way that it does
1263 /// not modify the semantics of the instruction. The predicate value may be
1264 /// changed to retain the same result if the predicate is order dependent
1265 /// (e.g. ult).
1266 /// Swap operands and adjust predicate.
1267 void swapOperands() {
1268 setPredicate(getSwappedPredicate());
1269 Op<0>().swap(Op<1>());
1270 }
1271
1272 // Methods for support type inquiry through isa, cast, and dyn_cast:
1273 static bool classof(const Instruction *I) {
1274 return I->getOpcode() == Instruction::ICmp;
1275 }
1276 static bool classof(const Value *V) {
1277 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1278 }
1279};
1280
1281//===----------------------------------------------------------------------===//
1282// FCmpInst Class
1283//===----------------------------------------------------------------------===//
1284
1285/// This instruction compares its operands according to the predicate given
1286/// to the constructor. It only operates on floating point values or packed
1287/// vectors of floating point values. The operands must be identical types.
1288/// Represents a floating point comparison operator.
1289class FCmpInst: public CmpInst {
1290 void AssertOK() {
1291 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1291, __PRETTY_FUNCTION__))
;
1292 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1293, __PRETTY_FUNCTION__))
1293 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1293, __PRETTY_FUNCTION__))
;
1294 // Check that the operands are the right type
1295 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1296, __PRETTY_FUNCTION__))
1296 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1296, __PRETTY_FUNCTION__))
;
1297 }
1298
1299protected:
1300 // Note: Instruction needs to be a friend here to call cloneImpl.
1301 friend class Instruction;
1302
1303 /// Clone an identical FCmpInst
1304 FCmpInst *cloneImpl() const;
1305
1306public:
1307 /// Constructor with insert-before-instruction semantics.
1308 FCmpInst(
1309 Instruction *InsertBefore, ///< Where to insert
1310 Predicate pred, ///< The predicate to use for the comparison
1311 Value *LHS, ///< The left-hand-side of the expression
1312 Value *RHS, ///< The right-hand-side of the expression
1313 const Twine &NameStr = "" ///< Name of the instruction
1314 ) : CmpInst(makeCmpResultType(LHS->getType()),
1315 Instruction::FCmp, pred, LHS, RHS, NameStr,
1316 InsertBefore) {
1317 AssertOK();
1318 }
1319
1320 /// Constructor with insert-at-end semantics.
1321 FCmpInst(
1322 BasicBlock &InsertAtEnd, ///< Block to insert into.
1323 Predicate pred, ///< The predicate to use for the comparison
1324 Value *LHS, ///< The left-hand-side of the expression
1325 Value *RHS, ///< The right-hand-side of the expression
1326 const Twine &NameStr = "" ///< Name of the instruction
1327 ) : CmpInst(makeCmpResultType(LHS->getType()),
1328 Instruction::FCmp, pred, LHS, RHS, NameStr,
1329 &InsertAtEnd) {
1330 AssertOK();
1331 }
1332
1333 /// Constructor with no-insertion semantics
1334 FCmpInst(
1335 Predicate Pred, ///< The predicate to use for the comparison
1336 Value *LHS, ///< The left-hand-side of the expression
1337 Value *RHS, ///< The right-hand-side of the expression
1338 const Twine &NameStr = "", ///< Name of the instruction
1339 Instruction *FlagsSource = nullptr
1340 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1341 RHS, NameStr, nullptr, FlagsSource) {
1342 AssertOK();
1343 }
1344
1345 /// @returns true if the predicate of this instruction is EQ or NE.
1346 /// Determine if this is an equality predicate.
1347 static bool isEquality(Predicate Pred) {
1348 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1349 Pred == FCMP_UNE;
1350 }
1351
1352 /// @returns true if the predicate of this instruction is EQ or NE.
1353 /// Determine if this is an equality predicate.
1354 bool isEquality() const { return isEquality(getPredicate()); }
1355
1356 /// @returns true if the predicate of this instruction is commutative.
1357 /// Determine if this is a commutative predicate.
1358 bool isCommutative() const {
1359 return isEquality() ||
1360 getPredicate() == FCMP_FALSE ||
1361 getPredicate() == FCMP_TRUE ||
1362 getPredicate() == FCMP_ORD ||
1363 getPredicate() == FCMP_UNO;
1364 }
1365
1366 /// @returns true if the predicate is relational (not EQ or NE).
1367 /// Determine if this a relational predicate.
1368 bool isRelational() const { return !isEquality(); }
1369
1370 /// Exchange the two operands to this instruction in such a way that it does
1371 /// not modify the semantics of the instruction. The predicate value may be
1372 /// changed to retain the same result if the predicate is order dependent
1373 /// (e.g. ult).
1374 /// Swap operands and adjust predicate.
1375 void swapOperands() {
1376 setPredicate(getSwappedPredicate());
1377 Op<0>().swap(Op<1>());
1378 }
1379
1380 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1381 static bool classof(const Instruction *I) {
1382 return I->getOpcode() == Instruction::FCmp;
1383 }
1384 static bool classof(const Value *V) {
1385 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1386 }
1387};
1388
1389//===----------------------------------------------------------------------===//
1390/// This class represents a function call, abstracting a target
1391/// machine's calling convention. This class uses low bit of the SubClassData
1392/// field to indicate whether or not this is a tail call. The rest of the bits
1393/// hold the calling convention of the call.
1394///
1395class CallInst : public CallBase {
1396 CallInst(const CallInst &CI);
1397
1398 /// Construct a CallInst given a range of arguments.
1399 /// Construct a CallInst from a range of arguments
1400 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1401 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1402 Instruction *InsertBefore);
1403
1404 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1405 const Twine &NameStr, Instruction *InsertBefore)
1406 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1407
1408 /// Construct a CallInst given a range of arguments.
1409 /// Construct a CallInst from a range of arguments
1410 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1411 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1412 BasicBlock *InsertAtEnd);
1413
1414 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1415 Instruction *InsertBefore);
1416
1417 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1418 BasicBlock *InsertAtEnd);
1419
1420 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1421 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1422 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1423
1424 /// Compute the number of operands to allocate.
1425 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1426 // We need one operand for the called function, plus the input operand
1427 // counts provided.
1428 return 1 + NumArgs + NumBundleInputs;
1429 }
1430
1431protected:
1432 // Note: Instruction needs to be a friend here to call cloneImpl.
1433 friend class Instruction;
1434
1435 CallInst *cloneImpl() const;
1436
1437public:
1438 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1439 Instruction *InsertBefore = nullptr) {
1440 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1441 }
1442
1443 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1444 const Twine &NameStr,
1445 Instruction *InsertBefore = nullptr) {
1446 return new (ComputeNumOperands(Args.size()))
1447 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1448 }
1449
1450 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1451 ArrayRef<OperandBundleDef> Bundles = None,
1452 const Twine &NameStr = "",
1453 Instruction *InsertBefore = nullptr) {
1454 const int NumOperands =
1455 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1456 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1457
1458 return new (NumOperands, DescriptorBytes)
1459 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1460 }
1461
1462 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1463 BasicBlock *InsertAtEnd) {
1464 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1465 }
1466
1467 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1468 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1469 return new (ComputeNumOperands(Args.size()))
1470 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1471 }
1472
1473 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1474 ArrayRef<OperandBundleDef> Bundles,
1475 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1476 const int NumOperands =
1477 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1478 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1479
1480 return new (NumOperands, DescriptorBytes)
1481 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1482 }
1483
1484 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1485 Instruction *InsertBefore = nullptr) {
1486 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1487 InsertBefore);
1488 }
1489
1490 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1491 ArrayRef<OperandBundleDef> Bundles = None,
1492 const Twine &NameStr = "",
1493 Instruction *InsertBefore = nullptr) {
1494 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1495 NameStr, InsertBefore);
1496 }
1497
1498 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1499 const Twine &NameStr,
1500 Instruction *InsertBefore = nullptr) {
1501 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1502 InsertBefore);
1503 }
1504
1505 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1506 BasicBlock *InsertAtEnd) {
1507 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1508 InsertAtEnd);
1509 }
1510
1511 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1512 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1513 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1514 InsertAtEnd);
1515 }
1516
1517 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1518 ArrayRef<OperandBundleDef> Bundles,
1519 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1520 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1521 NameStr, InsertAtEnd);
1522 }
1523
1524 // Deprecated [opaque pointer types]
1525 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1526 Instruction *InsertBefore = nullptr) {
1527 return Create(cast<FunctionType>(
1528 cast<PointerType>(Func->getType())->getElementType()),
1529 Func, NameStr, InsertBefore);
1530 }
1531
1532 // Deprecated [opaque pointer types]
1533 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1534 const Twine &NameStr,
1535 Instruction *InsertBefore = nullptr) {
1536 return Create(cast<FunctionType>(
1537 cast<PointerType>(Func->getType())->getElementType()),
1538 Func, Args, NameStr, InsertBefore);
1539 }
1540
1541 // Deprecated [opaque pointer types]
1542 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1543 ArrayRef<OperandBundleDef> Bundles = None,
1544 const Twine &NameStr = "",
1545 Instruction *InsertBefore = nullptr) {
1546 return Create(cast<FunctionType>(
1547 cast<PointerType>(Func->getType())->getElementType()),
1548 Func, Args, Bundles, NameStr, InsertBefore);
1549 }
1550
1551 // Deprecated [opaque pointer types]
1552 static CallInst *Create(Value *Func, const Twine &NameStr,
1553 BasicBlock *InsertAtEnd) {
1554 return Create(cast<FunctionType>(
1555 cast<PointerType>(Func->getType())->getElementType()),
1556 Func, NameStr, InsertAtEnd);
1557 }
1558
1559 // Deprecated [opaque pointer types]
1560 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1561 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1562 return Create(cast<FunctionType>(
1563 cast<PointerType>(Func->getType())->getElementType()),
1564 Func, Args, NameStr, InsertAtEnd);
1565 }
1566
1567 // Deprecated [opaque pointer types]
1568 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1569 ArrayRef<OperandBundleDef> Bundles,
1570 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1571 return Create(cast<FunctionType>(
1572 cast<PointerType>(Func->getType())->getElementType()),
1573 Func, Args, Bundles, NameStr, InsertAtEnd);
1574 }
1575
1576 /// Create a clone of \p CI with a different set of operand bundles and
1577 /// insert it before \p InsertPt.
1578 ///
1579 /// The returned call instruction is identical \p CI in every way except that
1580 /// the operand bundles for the new instruction are set to the operand bundles
1581 /// in \p Bundles.
1582 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1583 Instruction *InsertPt = nullptr);
1584
1585 /// Generate the IR for a call to malloc:
1586 /// 1. Compute the malloc call's argument as the specified type's size,
1587 /// possibly multiplied by the array size if the array size is not
1588 /// constant 1.
1589 /// 2. Call malloc with that argument.
1590 /// 3. Bitcast the result of the malloc call to the specified type.
1591 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1592 Type *AllocTy, Value *AllocSize,
1593 Value *ArraySize = nullptr,
1594 Function *MallocF = nullptr,
1595 const Twine &Name = "");
1596 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1597 Type *AllocTy, Value *AllocSize,
1598 Value *ArraySize = nullptr,
1599 Function *MallocF = nullptr,
1600 const Twine &Name = "");
1601 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1602 Type *AllocTy, Value *AllocSize,
1603 Value *ArraySize = nullptr,
1604 ArrayRef<OperandBundleDef> Bundles = None,
1605 Function *MallocF = nullptr,
1606 const Twine &Name = "");
1607 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1608 Type *AllocTy, Value *AllocSize,
1609 Value *ArraySize = nullptr,
1610 ArrayRef<OperandBundleDef> Bundles = None,
1611 Function *MallocF = nullptr,
1612 const Twine &Name = "");
1613 /// Generate the IR for a call to the builtin free function.
1614 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1615 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1616 static Instruction *CreateFree(Value *Source,
1617 ArrayRef<OperandBundleDef> Bundles,
1618 Instruction *InsertBefore);
1619 static Instruction *CreateFree(Value *Source,
1620 ArrayRef<OperandBundleDef> Bundles,
1621 BasicBlock *InsertAtEnd);
1622
1623 // Note that 'musttail' implies 'tail'.
1624 enum TailCallKind {
1625 TCK_None = 0,
1626 TCK_Tail = 1,
1627 TCK_MustTail = 2,
1628 TCK_NoTail = 3
1629 };
1630 TailCallKind getTailCallKind() const {
1631 return TailCallKind(getSubclassDataFromInstruction() & 3);
1632 }
1633
1634 bool isTailCall() const {
1635 unsigned Kind = getSubclassDataFromInstruction() & 3;
1636 return Kind == TCK_Tail || Kind == TCK_MustTail;
1637 }
1638
1639 bool isMustTailCall() const {
1640 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1641 }
1642
1643 bool isNoTailCall() const {
1644 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1645 }
1646
1647 void setTailCall(bool isTC = true) {
1648 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1649 unsigned(isTC ? TCK_Tail : TCK_None));
1650 }
1651
1652 void setTailCallKind(TailCallKind TCK) {
1653 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1654 unsigned(TCK));
1655 }
1656
1657 /// Return true if the call can return twice
1658 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1659 void setCanReturnTwice() {
1660 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1661 }
1662
1663 // Methods for support type inquiry through isa, cast, and dyn_cast:
1664 static bool classof(const Instruction *I) {
1665 return I->getOpcode() == Instruction::Call;
1666 }
1667 static bool classof(const Value *V) {
1668 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1669 }
1670
1671 /// Updates profile metadata by scaling it by \p S / \p T.
1672 void updateProfWeight(uint64_t S, uint64_t T);
1673
1674private:
1675 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1676 // method so that subclasses cannot accidentally use it.
1677 void setInstructionSubclassData(unsigned short D) {
1678 Instruction::setInstructionSubclassData(D);
1679 }
1680};
1681
1682CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1683 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1684 BasicBlock *InsertAtEnd)
1685 : CallBase(Ty->getReturnType(), Instruction::Call,
1686 OperandTraits<CallBase>::op_end(this) -
1687 (Args.size() + CountBundleInputs(Bundles) + 1),
1688 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1689 InsertAtEnd) {
1690 init(Ty, Func, Args, Bundles, NameStr);
1691}
1692
1693CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1694 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1695 Instruction *InsertBefore)
1696 : CallBase(Ty->getReturnType(), Instruction::Call,
1697 OperandTraits<CallBase>::op_end(this) -
1698 (Args.size() + CountBundleInputs(Bundles) + 1),
1699 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1700 InsertBefore) {
1701 init(Ty, Func, Args, Bundles, NameStr);
1702}
1703
1704//===----------------------------------------------------------------------===//
1705// SelectInst Class
1706//===----------------------------------------------------------------------===//
1707
1708/// This class represents the LLVM 'select' instruction.
1709///
1710class SelectInst : public Instruction {
1711 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1712 Instruction *InsertBefore)
1713 : Instruction(S1->getType(), Instruction::Select,
1714 &Op<0>(), 3, InsertBefore) {
1715 init(C, S1, S2);
1716 setName(NameStr);
1717 }
1718
1719 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1720 BasicBlock *InsertAtEnd)
1721 : Instruction(S1->getType(), Instruction::Select,
1722 &Op<0>(), 3, InsertAtEnd) {
1723 init(C, S1, S2);
1724 setName(NameStr);
1725 }
1726
1727 void init(Value *C, Value *S1, Value *S2) {
1728 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1728, __PRETTY_FUNCTION__))
;
1729 Op<0>() = C;
1730 Op<1>() = S1;
1731 Op<2>() = S2;
1732 }
1733
1734protected:
1735 // Note: Instruction needs to be a friend here to call cloneImpl.
1736 friend class Instruction;
1737
1738 SelectInst *cloneImpl() const;
1739
1740public:
1741 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1742 const Twine &NameStr = "",
1743 Instruction *InsertBefore = nullptr,
1744 Instruction *MDFrom = nullptr) {
1745 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1746 if (MDFrom)
1747 Sel->copyMetadata(*MDFrom);
1748 return Sel;
1749 }
1750
1751 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1752 const Twine &NameStr,
1753 BasicBlock *InsertAtEnd) {
1754 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1755 }
1756
1757 const Value *getCondition() const { return Op<0>(); }
1758 const Value *getTrueValue() const { return Op<1>(); }
1759 const Value *getFalseValue() const { return Op<2>(); }
1760 Value *getCondition() { return Op<0>(); }
1761 Value *getTrueValue() { return Op<1>(); }
1762 Value *getFalseValue() { return Op<2>(); }
1763
1764 void setCondition(Value *V) { Op<0>() = V; }
1765 void setTrueValue(Value *V) { Op<1>() = V; }
1766 void setFalseValue(Value *V) { Op<2>() = V; }
1767
1768 /// Swap the true and false values of the select instruction.
1769 /// This doesn't swap prof metadata.
1770 void swapValues() { Op<1>().swap(Op<2>()); }
1771
1772 /// Return a string if the specified operands are invalid
1773 /// for a select operation, otherwise return null.
1774 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1775
1776 /// Transparently provide more efficient getOperand methods.
1777 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
;
1778
1779 OtherOps getOpcode() const {
1780 return static_cast<OtherOps>(Instruction::getOpcode());
1781 }
1782
1783 // Methods for support type inquiry through isa, cast, and dyn_cast:
1784 static bool classof(const Instruction *I) {
1785 return I->getOpcode() == Instruction::Select;
1786 }
1787 static bool classof(const Value *V) {
1788 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1789 }
1790};
1791
1792template <>
1793struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1794};
1795
1796DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1796, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1796, __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); }
1797
1798//===----------------------------------------------------------------------===//
1799// VAArgInst Class
1800//===----------------------------------------------------------------------===//
1801
1802/// This class represents the va_arg llvm instruction, which returns
1803/// an argument of the specified type given a va_list and increments that list
1804///
1805class VAArgInst : public UnaryInstruction {
1806protected:
1807 // Note: Instruction needs to be a friend here to call cloneImpl.
1808 friend class Instruction;
1809
1810 VAArgInst *cloneImpl() const;
1811
1812public:
1813 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1814 Instruction *InsertBefore = nullptr)
1815 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1816 setName(NameStr);
1817 }
1818
1819 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1820 BasicBlock *InsertAtEnd)
1821 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1822 setName(NameStr);
1823 }
1824
1825 Value *getPointerOperand() { return getOperand(0); }
1826 const Value *getPointerOperand() const { return getOperand(0); }
1827 static unsigned getPointerOperandIndex() { return 0U; }
1828
1829 // Methods for support type inquiry through isa, cast, and dyn_cast:
1830 static bool classof(const Instruction *I) {
1831 return I->getOpcode() == VAArg;
1832 }
1833 static bool classof(const Value *V) {
1834 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1835 }
1836};
1837
1838//===----------------------------------------------------------------------===//
1839// ExtractElementInst Class
1840//===----------------------------------------------------------------------===//
1841
1842/// This instruction extracts a single (scalar)
1843/// element from a VectorType value
1844///
1845class ExtractElementInst : public Instruction {
1846 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1847 Instruction *InsertBefore = nullptr);
1848 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1849 BasicBlock *InsertAtEnd);
1850
1851protected:
1852 // Note: Instruction needs to be a friend here to call cloneImpl.
1853 friend class Instruction;
1854
1855 ExtractElementInst *cloneImpl() const;
1856
1857public:
1858 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1859 const Twine &NameStr = "",
1860 Instruction *InsertBefore = nullptr) {
1861 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1862 }
1863
1864 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1865 const Twine &NameStr,
1866 BasicBlock *InsertAtEnd) {
1867 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1868 }
1869
1870 /// Return true if an extractelement instruction can be
1871 /// formed with the specified operands.
1872 static bool isValidOperands(const Value *Vec, const Value *Idx);
1873
1874 Value *getVectorOperand() { return Op<0>(); }
1875 Value *getIndexOperand() { return Op<1>(); }
1876 const Value *getVectorOperand() const { return Op<0>(); }
1877 const Value *getIndexOperand() const { return Op<1>(); }
1878
1879 VectorType *getVectorOperandType() const {
1880 return cast<VectorType>(getVectorOperand()->getType());
1881 }
1882
1883 /// Transparently provide more efficient getOperand methods.
1884 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
;
1885
1886 // Methods for support type inquiry through isa, cast, and dyn_cast:
1887 static bool classof(const Instruction *I) {
1888 return I->getOpcode() == Instruction::ExtractElement;
1889 }
1890 static bool classof(const Value *V) {
1891 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1892 }
1893};
1894
1895template <>
1896struct OperandTraits<ExtractElementInst> :
1897 public FixedNumOperandTraits<ExtractElementInst, 2> {
1898};
1899
1900DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1900, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1900, __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); }
1901
1902//===----------------------------------------------------------------------===//
1903// InsertElementInst Class
1904//===----------------------------------------------------------------------===//
1905
1906/// This instruction inserts a single (scalar)
1907/// element into a VectorType value
1908///
1909class InsertElementInst : public Instruction {
1910 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1911 const Twine &NameStr = "",
1912 Instruction *InsertBefore = nullptr);
1913 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1914 BasicBlock *InsertAtEnd);
1915
1916protected:
1917 // Note: Instruction needs to be a friend here to call cloneImpl.
1918 friend class Instruction;
1919
1920 InsertElementInst *cloneImpl() const;
1921
1922public:
1923 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1924 const Twine &NameStr = "",
1925 Instruction *InsertBefore = nullptr) {
1926 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1927 }
1928
1929 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1930 const Twine &NameStr,
1931 BasicBlock *InsertAtEnd) {
1932 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1933 }
1934
1935 /// Return true if an insertelement instruction can be
1936 /// formed with the specified operands.
1937 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1938 const Value *Idx);
1939
1940 /// Overload to return most specific vector type.
1941 ///
1942 VectorType *getType() const {
1943 return cast<VectorType>(Instruction::getType());
1944 }
1945
1946 /// Transparently provide more efficient getOperand methods.
1947 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
;
1948
1949 // Methods for support type inquiry through isa, cast, and dyn_cast:
1950 static bool classof(const Instruction *I) {
1951 return I->getOpcode() == Instruction::InsertElement;
1952 }
1953 static bool classof(const Value *V) {
1954 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1955 }
1956};
1957
1958template <>
1959struct OperandTraits<InsertElementInst> :
1960 public FixedNumOperandTraits<InsertElementInst, 3> {
1961};
1962
1963DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1963, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1963, __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); }
1964
1965//===----------------------------------------------------------------------===//
1966// ShuffleVectorInst Class
1967//===----------------------------------------------------------------------===//
1968
1969/// This instruction constructs a fixed permutation of two
1970/// input vectors.
1971///
1972class ShuffleVectorInst : public Instruction {
1973protected:
1974 // Note: Instruction needs to be a friend here to call cloneImpl.
1975 friend class Instruction;
1976
1977 ShuffleVectorInst *cloneImpl() const;
1978
1979public:
1980 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1981 const Twine &NameStr = "",
1982 Instruction *InsertBefor = nullptr);
1983 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1984 const Twine &NameStr, BasicBlock *InsertAtEnd);
1985
1986 // allocate space for exactly three operands
1987 void *operator new(size_t s) {
1988 return User::operator new(s, 3);
1989 }
1990
1991 /// Swap the first 2 operands and adjust the mask to preserve the semantics
1992 /// of the instruction.
1993 void commute();
1994
1995 /// Return true if a shufflevector instruction can be
1996 /// formed with the specified operands.
1997 static bool isValidOperands(const Value *V1, const Value *V2,
1998 const Value *Mask);
1999
2000 /// Overload to return most specific vector type.
2001 ///
2002 VectorType *getType() const {
2003 return cast<VectorType>(Instruction::getType());
2004 }
2005
2006 /// Transparently provide more efficient getOperand methods.
2007 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
;
2008
2009 Constant *getMask() const {
2010 return cast<Constant>(getOperand(2));
2011 }
2012
2013 /// Return the shuffle mask value for the specified element of the mask.
2014 /// Return -1 if the element is undef.
2015 static int getMaskValue(const Constant *Mask, unsigned Elt);
2016
2017 /// Return the shuffle mask value of this instruction for the given element
2018 /// index. Return -1 if the element is undef.
2019 int getMaskValue(unsigned Elt) const {
2020 return getMaskValue(getMask(), Elt);
2021 }
2022
2023 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2024 /// elements of the mask are returned as -1.
2025 static void getShuffleMask(const Constant *Mask,
2026 SmallVectorImpl<int> &Result);
2027
2028 /// Return the mask for this instruction as a vector of integers. Undefined
2029 /// elements of the mask are returned as -1.
2030 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2031 return getShuffleMask(getMask(), Result);
2032 }
2033
2034 SmallVector<int, 16> getShuffleMask() const {
2035 SmallVector<int, 16> Mask;
2036 getShuffleMask(Mask);
2037 return Mask;
2038 }
2039
2040 /// Return true if this shuffle returns a vector with a different number of
2041 /// elements than its source vectors.
2042 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2043 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2044 bool changesLength() const {
2045 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2046 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2047 return NumSourceElts != NumMaskElts;
2048 }
2049
2050 /// Return true if this shuffle returns a vector with a greater number of
2051 /// elements than its source vectors.
2052 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2053 bool increasesLength() const {
2054 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2055 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2056 return NumSourceElts < NumMaskElts;
2057 }
2058
2059 /// Return true if this shuffle mask chooses elements from exactly one source
2060 /// vector.
2061 /// Example: <7,5,undef,7>
2062 /// This assumes that vector operands are the same length as the mask.
2063 static bool isSingleSourceMask(ArrayRef<int> Mask);
2064 static bool isSingleSourceMask(const Constant *Mask) {
2065 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2065, __PRETTY_FUNCTION__))
;
2066 SmallVector<int, 16> MaskAsInts;
2067 getShuffleMask(Mask, MaskAsInts);
2068 return isSingleSourceMask(MaskAsInts);
2069 }
2070
2071 /// Return true if this shuffle chooses elements from exactly one source
2072 /// vector without changing the length of that vector.
2073 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2074 /// TODO: Optionally allow length-changing shuffles.
2075 bool isSingleSource() const {
2076 return !changesLength() && isSingleSourceMask(getMask());
2077 }
2078
2079 /// Return true if this shuffle mask chooses elements from exactly one source
2080 /// vector without lane crossings. A shuffle using this mask is not
2081 /// necessarily a no-op because it may change the number of elements from its
2082 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2083 /// Example: <undef,undef,2,3>
2084 static bool isIdentityMask(ArrayRef<int> Mask);
2085 static bool isIdentityMask(const Constant *Mask) {
2086 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2086, __PRETTY_FUNCTION__))
;
2087 SmallVector<int, 16> MaskAsInts;
2088 getShuffleMask(Mask, MaskAsInts);
2089 return isIdentityMask(MaskAsInts);
2090 }
2091
2092 /// Return true if this shuffle chooses elements from exactly one source
2093 /// vector without lane crossings and does not change the number of elements
2094 /// from its input vectors.
2095 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2096 bool isIdentity() const {
2097 return !changesLength() && isIdentityMask(getShuffleMask());
2098 }
2099
2100 /// Return true if this shuffle lengthens exactly one source vector with
2101 /// undefs in the high elements.
2102 bool isIdentityWithPadding() const;
2103
2104 /// Return true if this shuffle extracts the first N elements of exactly one
2105 /// source vector.
2106 bool isIdentityWithExtract() const;
2107
2108 /// Return true if this shuffle concatenates its 2 source vectors. This
2109 /// returns false if either input is undefined. In that case, the shuffle is
2110 /// is better classified as an identity with padding operation.
2111 bool isConcat() const;
2112
2113 /// Return true if this shuffle mask chooses elements from its source vectors
2114 /// without lane crossings. A shuffle using this mask would be
2115 /// equivalent to a vector select with a constant condition operand.
2116 /// Example: <4,1,6,undef>
2117 /// This returns false if the mask does not choose from both input vectors.
2118 /// In that case, the shuffle is better classified as an identity shuffle.
2119 /// This assumes that vector operands are the same length as the mask
2120 /// (a length-changing shuffle can never be equivalent to a vector select).
2121 static bool isSelectMask(ArrayRef<int> Mask);
2122 static bool isSelectMask(const Constant *Mask) {
2123 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2123, __PRETTY_FUNCTION__))
;
2124 SmallVector<int, 16> MaskAsInts;
2125 getShuffleMask(Mask, MaskAsInts);
2126 return isSelectMask(MaskAsInts);
2127 }
2128
2129 /// Return true if this shuffle chooses elements from its source vectors
2130 /// without lane crossings and all operands have the same number of elements.
2131 /// In other words, this shuffle is equivalent to a vector select with a
2132 /// constant condition operand.
2133 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2134 /// This returns false if the mask does not choose from both input vectors.
2135 /// In that case, the shuffle is better classified as an identity shuffle.
2136 /// TODO: Optionally allow length-changing shuffles.
2137 bool isSelect() const {
2138 return !changesLength() && isSelectMask(getMask());
2139 }
2140
2141 /// Return true if this shuffle mask swaps the order of elements from exactly
2142 /// one source vector.
2143 /// Example: <7,6,undef,4>
2144 /// This assumes that vector operands are the same length as the mask.
2145 static bool isReverseMask(ArrayRef<int> Mask);
2146 static bool isReverseMask(const Constant *Mask) {
2147 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2147, __PRETTY_FUNCTION__))
;
2148 SmallVector<int, 16> MaskAsInts;
2149 getShuffleMask(Mask, MaskAsInts);
2150 return isReverseMask(MaskAsInts);
2151 }
2152
2153 /// Return true if this shuffle swaps the order of elements from exactly
2154 /// one source vector.
2155 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2156 /// TODO: Optionally allow length-changing shuffles.
2157 bool isReverse() const {
2158 return !changesLength() && isReverseMask(getMask());
2159 }
2160
2161 /// Return true if this shuffle mask chooses all elements with the same value
2162 /// as the first element of exactly one source vector.
2163 /// Example: <4,undef,undef,4>
2164 /// This assumes that vector operands are the same length as the mask.
2165 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2166 static bool isZeroEltSplatMask(const Constant *Mask) {
2167 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2167, __PRETTY_FUNCTION__))
;
2168 SmallVector<int, 16> MaskAsInts;
2169 getShuffleMask(Mask, MaskAsInts);
2170 return isZeroEltSplatMask(MaskAsInts);
2171 }
2172
2173 /// Return true if all elements of this shuffle are the same value as the
2174 /// first element of exactly one source vector without changing the length
2175 /// of that vector.
2176 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2177 /// TODO: Optionally allow length-changing shuffles.
2178 /// TODO: Optionally allow splats from other elements.
2179 bool isZeroEltSplat() const {
2180 return !changesLength() && isZeroEltSplatMask(getMask());
2181 }
2182
2183 /// Return true if this shuffle mask is a transpose mask.
2184 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2185 /// even- or odd-numbered vector elements from two n-dimensional source
2186 /// vectors and write each result into consecutive elements of an
2187 /// n-dimensional destination vector. Two shuffles are necessary to complete
2188 /// the transpose, one for the even elements and another for the odd elements.
2189 /// This description closely follows how the TRN1 and TRN2 AArch64
2190 /// instructions operate.
2191 ///
2192 /// For example, a simple 2x2 matrix can be transposed with:
2193 ///
2194 /// ; Original matrix
2195 /// m0 = < a, b >
2196 /// m1 = < c, d >
2197 ///
2198 /// ; Transposed matrix
2199 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2200 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2201 ///
2202 /// For matrices having greater than n columns, the resulting nx2 transposed
2203 /// matrix is stored in two result vectors such that one vector contains
2204 /// interleaved elements from all the even-numbered rows and the other vector
2205 /// contains interleaved elements from all the odd-numbered rows. For example,
2206 /// a 2x4 matrix can be transposed with:
2207 ///
2208 /// ; Original matrix
2209 /// m0 = < a, b, c, d >
2210 /// m1 = < e, f, g, h >
2211 ///
2212 /// ; Transposed matrix
2213 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2214 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2215 static bool isTransposeMask(ArrayRef<int> Mask);
2216 static bool isTransposeMask(const Constant *Mask) {
2217 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2217, __PRETTY_FUNCTION__))
;
2218 SmallVector<int, 16> MaskAsInts;
2219 getShuffleMask(Mask, MaskAsInts);
2220 return isTransposeMask(MaskAsInts);
2221 }
2222
2223 /// Return true if this shuffle transposes the elements of its inputs without
2224 /// changing the length of the vectors. This operation may also be known as a
2225 /// merge or interleave. See the description for isTransposeMask() for the
2226 /// exact specification.
2227 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2228 bool isTranspose() const {
2229 return !changesLength() && isTransposeMask(getMask());
2230 }
2231
2232 /// Return true if this shuffle mask is an extract subvector mask.
2233 /// A valid extract subvector mask returns a smaller vector from a single
2234 /// source operand. The base extraction index is returned as well.
2235 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2236 int &Index);
2237 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2238 int &Index) {
2239 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2239, __PRETTY_FUNCTION__))
;
2240 SmallVector<int, 16> MaskAsInts;
2241 getShuffleMask(Mask, MaskAsInts);
2242 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2243 }
2244
2245 /// Return true if this shuffle mask is an extract subvector mask.
2246 bool isExtractSubvectorMask(int &Index) const {
2247 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2248 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2249 }
2250
2251 /// Change values in a shuffle permute mask assuming the two vector operands
2252 /// of length InVecNumElts have swapped position.
2253 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2254 unsigned InVecNumElts) {
2255 for (int &Idx : Mask) {
2256 if (Idx == -1)
2257 continue;
2258 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2259 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2260, __PRETTY_FUNCTION__))
2260 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2260, __PRETTY_FUNCTION__))
;
2261 }
2262 }
2263
2264 // Methods for support type inquiry through isa, cast, and dyn_cast:
2265 static bool classof(const Instruction *I) {
2266 return I->getOpcode() == Instruction::ShuffleVector;
2267 }
2268 static bool classof(const Value *V) {
2269 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2270 }
2271};
2272
2273template <>
2274struct OperandTraits<ShuffleVectorInst> :
2275 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2276};
2277
2278DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2278, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2278, __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); }
2279
2280//===----------------------------------------------------------------------===//
2281// ExtractValueInst Class
2282//===----------------------------------------------------------------------===//
2283
2284/// This instruction extracts a struct member or array
2285/// element value from an aggregate value.
2286///
2287class ExtractValueInst : public UnaryInstruction {
2288 SmallVector<unsigned, 4> Indices;
2289
2290 ExtractValueInst(const ExtractValueInst &EVI);
2291
2292 /// Constructors - Create a extractvalue instruction with a base aggregate
2293 /// value and a list of indices. The first ctor can optionally insert before
2294 /// an existing instruction, the second appends the new instruction to the
2295 /// specified BasicBlock.
2296 inline ExtractValueInst(Value *Agg,
2297 ArrayRef<unsigned> Idxs,
2298 const Twine &NameStr,
2299 Instruction *InsertBefore);
2300 inline ExtractValueInst(Value *Agg,
2301 ArrayRef<unsigned> Idxs,
2302 const Twine &NameStr, BasicBlock *InsertAtEnd);
2303
2304 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2305
2306protected:
2307 // Note: Instruction needs to be a friend here to call cloneImpl.
2308 friend class Instruction;
2309
2310 ExtractValueInst *cloneImpl() const;
2311
2312public:
2313 static ExtractValueInst *Create(Value *Agg,
2314 ArrayRef<unsigned> Idxs,
2315 const Twine &NameStr = "",
2316 Instruction *InsertBefore = nullptr) {
2317 return new
2318 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2319 }
2320
2321 static ExtractValueInst *Create(Value *Agg,
2322 ArrayRef<unsigned> Idxs,
2323 const Twine &NameStr,
2324 BasicBlock *InsertAtEnd) {
2325 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2326 }
2327
2328 /// Returns the type of the element that would be extracted
2329 /// with an extractvalue instruction with the specified parameters.
2330 ///
2331 /// Null is returned if the indices are invalid for the specified type.
2332 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2333
2334 using idx_iterator = const unsigned*;
2335
2336 inline idx_iterator idx_begin() const { return Indices.begin(); }
2337 inline idx_iterator idx_end() const { return Indices.end(); }
2338 inline iterator_range<idx_iterator> indices() const {
2339 return make_range(idx_begin(), idx_end());
2340 }
2341
2342 Value *getAggregateOperand() {
2343 return getOperand(0);
2344 }
2345 const Value *getAggregateOperand() const {
2346 return getOperand(0);
2347 }
2348 static unsigned getAggregateOperandIndex() {
2349 return 0U; // get index for modifying correct operand
2350 }
2351
2352 ArrayRef<unsigned> getIndices() const {
2353 return Indices;
2354 }
2355
2356 unsigned getNumIndices() const {
2357 return (unsigned)Indices.size();
2358 }
2359
2360 bool hasIndices() const {
2361 return true;
2362 }
2363
2364 // Methods for support type inquiry through isa, cast, and dyn_cast:
2365 static bool classof(const Instruction *I) {
2366 return I->getOpcode() == Instruction::ExtractValue;
2367 }
2368 static bool classof(const Value *V) {
2369 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2370 }
2371};
2372
2373ExtractValueInst::ExtractValueInst(Value *Agg,
2374 ArrayRef<unsigned> Idxs,
2375 const Twine &NameStr,
2376 Instruction *InsertBefore)
2377 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2378 ExtractValue, Agg, InsertBefore) {
2379 init(Idxs, NameStr);
2380}
2381
2382ExtractValueInst::ExtractValueInst(Value *Agg,
2383 ArrayRef<unsigned> Idxs,
2384 const Twine &NameStr,
2385 BasicBlock *InsertAtEnd)
2386 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2387 ExtractValue, Agg, InsertAtEnd) {
2388 init(Idxs, NameStr);
2389}
2390
2391//===----------------------------------------------------------------------===//
2392// InsertValueInst Class
2393//===----------------------------------------------------------------------===//
2394
2395/// This instruction inserts a struct field of array element
2396/// value into an aggregate value.
2397///
2398class InsertValueInst : public Instruction {
2399 SmallVector<unsigned, 4> Indices;
2400
2401 InsertValueInst(const InsertValueInst &IVI);
2402
2403 /// Constructors - Create a insertvalue instruction with a base aggregate
2404 /// value, a value to insert, and a list of indices. The first ctor can
2405 /// optionally insert before an existing instruction, the second appends
2406 /// the new instruction to the specified BasicBlock.
2407 inline InsertValueInst(Value *Agg, Value *Val,
2408 ArrayRef<unsigned> Idxs,
2409 const Twine &NameStr,
2410 Instruction *InsertBefore);
2411 inline InsertValueInst(Value *Agg, Value *Val,
2412 ArrayRef<unsigned> Idxs,
2413 const Twine &NameStr, BasicBlock *InsertAtEnd);
2414
2415 /// Constructors - These two constructors are convenience methods because one
2416 /// and two index insertvalue instructions are so common.
2417 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2418 const Twine &NameStr = "",
2419 Instruction *InsertBefore = nullptr);
2420 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2421 BasicBlock *InsertAtEnd);
2422
2423 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2424 const Twine &NameStr);
2425
2426protected:
2427 // Note: Instruction needs to be a friend here to call cloneImpl.
2428 friend class Instruction;
2429
2430 InsertValueInst *cloneImpl() const;
2431
2432public:
2433 // allocate space for exactly two operands
2434 void *operator new(size_t s) {
2435 return User::operator new(s, 2);
2436 }
2437
2438 static InsertValueInst *Create(Value *Agg, Value *Val,
2439 ArrayRef<unsigned> Idxs,
2440 const Twine &NameStr = "",
2441 Instruction *InsertBefore = nullptr) {
2442 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2443 }
2444
2445 static InsertValueInst *Create(Value *Agg, Value *Val,
2446 ArrayRef<unsigned> Idxs,
2447 const Twine &NameStr,
2448 BasicBlock *InsertAtEnd) {
2449 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2450 }
2451
2452 /// Transparently provide more efficient getOperand methods.
2453 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
;
2454
2455 using idx_iterator = const unsigned*;
2456
2457 inline idx_iterator idx_begin() const { return Indices.begin(); }
2458 inline idx_iterator idx_end() const { return Indices.end(); }
2459 inline iterator_range<idx_iterator> indices() const {
2460 return make_range(idx_begin(), idx_end());
2461 }
2462
2463 Value *getAggregateOperand() {
2464 return getOperand(0);
2465 }
2466 const Value *getAggregateOperand() const {
2467 return getOperand(0);
2468 }
2469 static unsigned getAggregateOperandIndex() {
2470 return 0U; // get index for modifying correct operand
2471 }
2472
2473 Value *getInsertedValueOperand() {
2474 return getOperand(1);
2475 }
2476 const Value *getInsertedValueOperand() const {
2477 return getOperand(1);
2478 }
2479 static unsigned getInsertedValueOperandIndex() {
2480 return 1U; // get index for modifying correct operand
2481 }
2482
2483 ArrayRef<unsigned> getIndices() const {
2484 return Indices;
2485 }
2486
2487 unsigned getNumIndices() const {
2488 return (unsigned)Indices.size();
2489 }
2490
2491 bool hasIndices() const {
2492 return true;
2493 }
2494
2495 // Methods for support type inquiry through isa, cast, and dyn_cast:
2496 static bool classof(const Instruction *I) {
2497 return I->getOpcode() == Instruction::InsertValue;
2498 }
2499 static bool classof(const Value *V) {
2500 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2501 }
2502};
2503
2504template <>
2505struct OperandTraits<InsertValueInst> :
2506 public FixedNumOperandTraits<InsertValueInst, 2> {
2507};
2508
2509InsertValueInst::InsertValueInst(Value *Agg,
2510 Value *Val,
2511 ArrayRef<unsigned> Idxs,
2512 const Twine &NameStr,
2513 Instruction *InsertBefore)
2514 : Instruction(Agg->getType(), InsertValue,
2515 OperandTraits<InsertValueInst>::op_begin(this),
2516 2, InsertBefore) {
2517 init(Agg, Val, Idxs, NameStr);
2518}
2519
2520InsertValueInst::InsertValueInst(Value *Agg,
2521 Value *Val,
2522 ArrayRef<unsigned> Idxs,
2523 const Twine &NameStr,
2524 BasicBlock *InsertAtEnd)
2525 : Instruction(Agg->getType(), InsertValue,
2526 OperandTraits<InsertValueInst>::op_begin(this),
2527 2, InsertAtEnd) {
2528 init(Agg, Val, Idxs, NameStr);
2529}
2530
2531DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2531, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2531, __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); }
2532
2533//===----------------------------------------------------------------------===//
2534// PHINode Class
2535//===----------------------------------------------------------------------===//
2536
2537// PHINode - The PHINode class is used to represent the magical mystical PHI
2538// node, that can not exist in nature, but can be synthesized in a computer
2539// scientist's overactive imagination.
2540//
2541class PHINode : public Instruction {
2542 /// The number of operands actually allocated. NumOperands is
2543 /// the number actually in use.
2544 unsigned ReservedSpace;
2545
2546 PHINode(const PHINode &PN);
2547
2548 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2549 const Twine &NameStr = "",
2550 Instruction *InsertBefore = nullptr)
2551 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2552 ReservedSpace(NumReservedValues) {
2553 setName(NameStr);
2554 allocHungoffUses(ReservedSpace);
2555 }
2556
2557 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2558 BasicBlock *InsertAtEnd)
2559 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2560 ReservedSpace(NumReservedValues) {
2561 setName(NameStr);
2562 allocHungoffUses(ReservedSpace);
2563 }
2564
2565protected:
2566 // Note: Instruction needs to be a friend here to call cloneImpl.
2567 friend class Instruction;
2568
2569 PHINode *cloneImpl() const;
2570
2571 // allocHungoffUses - this is more complicated than the generic
2572 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2573 // values and pointers to the incoming blocks, all in one allocation.
2574 void allocHungoffUses(unsigned N) {
2575 User::allocHungoffUses(N, /* IsPhi */ true);
2576 }
2577
2578public:
2579 /// Constructors - NumReservedValues is a hint for the number of incoming
2580 /// edges that this phi node will have (use 0 if you really have no idea).
2581 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2582 const Twine &NameStr = "",
2583 Instruction *InsertBefore = nullptr) {
2584 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2585 }
2586
2587 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2588 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2589 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2590 }
2591
2592 /// Provide fast operand accessors
2593 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
;
2594
2595 // Block iterator interface. This provides access to the list of incoming
2596 // basic blocks, which parallels the list of incoming values.
2597
2598 using block_iterator = BasicBlock **;
2599 using const_block_iterator = BasicBlock * const *;
2600
2601 block_iterator block_begin() {
2602 Use::UserRef *ref =
2603 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2604 return reinterpret_cast<block_iterator>(ref + 1);
2605 }
2606
2607 const_block_iterator block_begin() const {
2608 const Use::UserRef *ref =
2609 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2610 return reinterpret_cast<const_block_iterator>(ref + 1);
2611 }
2612
2613 block_iterator block_end() {
2614 return block_begin() + getNumOperands();
2615 }
2616
2617 const_block_iterator block_end() const {
2618 return block_begin() + getNumOperands();
2619 }
2620
2621 iterator_range<block_iterator> blocks() {
2622 return make_range(block_begin(), block_end());
2623 }
2624
2625 iterator_range<const_block_iterator> blocks() const {
2626 return make_range(block_begin(), block_end());
2627 }
2628
2629 op_range incoming_values() { return operands(); }
2630
2631 const_op_range incoming_values() const { return operands(); }
2632
2633 /// Return the number of incoming edges
2634 ///
2635 unsigned getNumIncomingValues() const { return getNumOperands(); }
2636
2637 /// Return incoming value number x
2638 ///
2639 Value *getIncomingValue(unsigned i) const {
2640 return getOperand(i);
2641 }
2642 void setIncomingValue(unsigned i, Value *V) {
2643 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2643, __PRETTY_FUNCTION__))
;
2644 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2645, __PRETTY_FUNCTION__))
2645 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2645, __PRETTY_FUNCTION__))
;
2646 setOperand(i, V);
2647 }
2648
2649 static unsigned getOperandNumForIncomingValue(unsigned i) {
2650 return i;
2651 }
2652
2653 static unsigned getIncomingValueNumForOperand(unsigned i) {
2654 return i;
2655 }
2656
2657 /// Return incoming basic block number @p i.
2658 ///
2659 BasicBlock *getIncomingBlock(unsigned i) const {
2660 return block_begin()[i];
2661 }
2662
2663 /// Return incoming basic block corresponding
2664 /// to an operand of the PHI.
2665 ///
2666 BasicBlock *getIncomingBlock(const Use &U) const {
2667 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2667, __PRETTY_FUNCTION__))
;
2668 return getIncomingBlock(unsigned(&U - op_begin()));
2669 }
2670
2671 /// Return incoming basic block corresponding
2672 /// to value use iterator.
2673 ///
2674 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2675 return getIncomingBlock(I.getUse());
2676 }
2677
2678 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2679 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2679, __PRETTY_FUNCTION__))
;
2680 block_begin()[i] = BB;
2681 }
2682
2683 /// Replace every incoming basic block \p Old to basic block \p New.
2684 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
2685 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2685, __PRETTY_FUNCTION__))
;
2686 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2687 if (getIncomingBlock(Op) == Old)
2688 setIncomingBlock(Op, New);
2689 }
2690
2691 /// Add an incoming value to the end of the PHI list
2692 ///
2693 void addIncoming(Value *V, BasicBlock *BB) {
2694 if (getNumOperands() == ReservedSpace)
2695 growOperands(); // Get more space!
2696 // Initialize some new operands.
2697 setNumHungOffUseOperands(getNumOperands() + 1);
2698 setIncomingValue(getNumOperands() - 1, V);
2699 setIncomingBlock(getNumOperands() - 1, BB);
2700 }
2701
2702 /// Remove an incoming value. This is useful if a
2703 /// predecessor basic block is deleted. The value removed is returned.
2704 ///
2705 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2706 /// is true), the PHI node is destroyed and any uses of it are replaced with
2707 /// dummy values. The only time there should be zero incoming values to a PHI
2708 /// node is when the block is dead, so this strategy is sound.
2709 ///
2710 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2711
2712 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2713 int Idx = getBasicBlockIndex(BB);
2714 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2714, __PRETTY_FUNCTION__))
;
2715 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2716 }
2717
2718 /// Return the first index of the specified basic
2719 /// block in the value list for this PHI. Returns -1 if no instance.
2720 ///
2721 int getBasicBlockIndex(const BasicBlock *BB) const {
2722 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2723 if (block_begin()[i] == BB)
2724 return i;
2725 return -1;
2726 }
2727
2728 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2729 int Idx = getBasicBlockIndex(BB);
2730 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2730, __PRETTY_FUNCTION__))
;
2731 return getIncomingValue(Idx);
2732 }
2733
2734 /// Set every incoming value(s) for block \p BB to \p V.
2735 void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
2736 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2736, __PRETTY_FUNCTION__))
;
2737 bool Found = false;
2738 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2739 if (getIncomingBlock(Op) == BB) {
2740 Found = true;
2741 setIncomingValue(Op, V);
2742 }
2743 (void)Found;
2744 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2744, __PRETTY_FUNCTION__))
;
2745 }
2746
2747 /// If the specified PHI node always merges together the
2748 /// same value, return the value, otherwise return null.
2749 Value *hasConstantValue() const;
2750
2751 /// Whether the specified PHI node always merges
2752 /// together the same value, assuming undefs are equal to a unique
2753 /// non-undef value.
2754 bool hasConstantOrUndefValue() const;
2755
2756 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2757 static bool classof(const Instruction *I) {
2758 return I->getOpcode() == Instruction::PHI;
2759 }
2760 static bool classof(const Value *V) {
2761 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2762 }
2763
2764private:
2765 void growOperands();
2766};
2767
2768template <>
2769struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2770};
2771
2772DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2772, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2772, __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
); }
2773
2774//===----------------------------------------------------------------------===//
2775// LandingPadInst Class
2776//===----------------------------------------------------------------------===//
2777
2778//===---------------------------------------------------------------------------
2779/// The landingpad instruction holds all of the information
2780/// necessary to generate correct exception handling. The landingpad instruction
2781/// cannot be moved from the top of a landing pad block, which itself is
2782/// accessible only from the 'unwind' edge of an invoke. This uses the
2783/// SubclassData field in Value to store whether or not the landingpad is a
2784/// cleanup.
2785///
2786class LandingPadInst : public Instruction {
2787 /// The number of operands actually allocated. NumOperands is
2788 /// the number actually in use.
2789 unsigned ReservedSpace;
2790
2791 LandingPadInst(const LandingPadInst &LP);
2792
2793public:
2794 enum ClauseType { Catch, Filter };
2795
2796private:
2797 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2798 const Twine &NameStr, Instruction *InsertBefore);
2799 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2800 const Twine &NameStr, BasicBlock *InsertAtEnd);
2801
2802 // Allocate space for exactly zero operands.
2803 void *operator new(size_t s) {
2804 return User::operator new(s);
2805 }
2806
2807 void growOperands(unsigned Size);
2808 void init(unsigned NumReservedValues, const Twine &NameStr);
2809
2810protected:
2811 // Note: Instruction needs to be a friend here to call cloneImpl.
2812 friend class Instruction;
2813
2814 LandingPadInst *cloneImpl() const;
2815
2816public:
2817 /// Constructors - NumReservedClauses is a hint for the number of incoming
2818 /// clauses that this landingpad will have (use 0 if you really have no idea).
2819 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2820 const Twine &NameStr = "",
2821 Instruction *InsertBefore = nullptr);
2822 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2823 const Twine &NameStr, BasicBlock *InsertAtEnd);
2824
2825 /// Provide fast operand accessors
2826 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
;
2827
2828 /// Return 'true' if this landingpad instruction is a
2829 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2830 /// doesn't catch the exception.
2831 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2832
2833 /// Indicate that this landingpad instruction is a cleanup.
2834 void setCleanup(bool V) {
2835 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2836 (V ? 1 : 0));
2837 }
2838
2839 /// Add a catch or filter clause to the landing pad.
2840 void addClause(Constant *ClauseVal);
2841
2842 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2843 /// determine what type of clause this is.
2844 Constant *getClause(unsigned Idx) const {
2845 return cast<Constant>(getOperandList()[Idx]);
2846 }
2847
2848 /// Return 'true' if the clause and index Idx is a catch clause.
2849 bool isCatch(unsigned Idx) const {
2850 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2851 }
2852
2853 /// Return 'true' if the clause and index Idx is a filter clause.
2854 bool isFilter(unsigned Idx) const {
2855 return isa<ArrayType>(getOperandList()[Idx]->getType());
2856 }
2857
2858 /// Get the number of clauses for this landing pad.
2859 unsigned getNumClauses() const { return getNumOperands(); }
2860
2861 /// Grow the size of the operand list to accommodate the new
2862 /// number of clauses.
2863 void reserveClauses(unsigned Size) { growOperands(Size); }
2864
2865 // Methods for support type inquiry through isa, cast, and dyn_cast:
2866 static bool classof(const Instruction *I) {
2867 return I->getOpcode() == Instruction::LandingPad;
2868 }
2869 static bool classof(const Value *V) {
2870 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2871 }
2872};
2873
2874template <>
2875struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2876};
2877
2878DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2878, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2878, __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); }
2879
2880//===----------------------------------------------------------------------===//
2881// ReturnInst Class
2882//===----------------------------------------------------------------------===//
2883
2884//===---------------------------------------------------------------------------
2885/// Return a value (possibly void), from a function. Execution
2886/// does not continue in this function any longer.
2887///
2888class ReturnInst : public Instruction {
2889 ReturnInst(const ReturnInst &RI);
2890
2891private:
2892 // ReturnInst constructors:
2893 // ReturnInst() - 'ret void' instruction
2894 // ReturnInst( null) - 'ret void' instruction
2895 // ReturnInst(Value* X) - 'ret X' instruction
2896 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2897 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2898 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2899 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2900 //
2901 // NOTE: If the Value* passed is of type void then the constructor behaves as
2902 // if it was passed NULL.
2903 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2904 Instruction *InsertBefore = nullptr);
2905 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2906 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2907
2908protected:
2909 // Note: Instruction needs to be a friend here to call cloneImpl.
2910 friend class Instruction;
2911
2912 ReturnInst *cloneImpl() const;
2913
2914public:
2915 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2916 Instruction *InsertBefore = nullptr) {
2917 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2918 }
2919
2920 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2921 BasicBlock *InsertAtEnd) {
2922 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2923 }
2924
2925 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2926 return new(0) ReturnInst(C, InsertAtEnd);
2927 }
2928
2929 /// Provide fast operand accessors
2930 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
;
2931
2932 /// Convenience accessor. Returns null if there is no return value.
2933 Value *getReturnValue() const {
2934 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2935 }
2936
2937 unsigned getNumSuccessors() const { return 0; }
2938
2939 // Methods for support type inquiry through isa, cast, and dyn_cast:
2940 static bool classof(const Instruction *I) {
2941 return (I->getOpcode() == Instruction::Ret);
2942 }
2943 static bool classof(const Value *V) {
2944 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2945 }
2946
2947private:
2948 BasicBlock *getSuccessor(unsigned idx) const {
2949 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2949)
;
2950 }
2951
2952 void setSuccessor(unsigned idx, BasicBlock *B) {
2953 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2953)
;
2954 }
2955};
2956
2957template <>
2958struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2959};
2960
2961DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2961, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 2961, __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); }
2962
2963//===----------------------------------------------------------------------===//
2964// BranchInst Class
2965//===----------------------------------------------------------------------===//
2966
2967//===---------------------------------------------------------------------------
2968/// Conditional or Unconditional Branch instruction.
2969///
2970class BranchInst : public Instruction {
2971 /// Ops list - Branches are strange. The operands are ordered:
2972 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2973 /// they don't have to check for cond/uncond branchness. These are mostly
2974 /// accessed relative from op_end().
2975 BranchInst(const BranchInst &BI);
2976 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2977 // BranchInst(BB *B) - 'br B'
2978 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2979 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2980 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2981 // BranchInst(BB* B, BB *I) - 'br B' insert at end
2982 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2983 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2984 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2985 Instruction *InsertBefore = nullptr);
2986 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2987 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2988 BasicBlock *InsertAtEnd);
2989
2990 void AssertOK();
2991
2992protected:
2993 // Note: Instruction needs to be a friend here to call cloneImpl.
2994 friend class Instruction;
2995
2996 BranchInst *cloneImpl() const;
2997
2998public:
2999 /// Iterator type that casts an operand to a basic block.
3000 ///
3001 /// This only makes sense because the successors are stored as adjacent
3002 /// operands for branch instructions.
3003 struct succ_op_iterator
3004 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3005 std::random_access_iterator_tag, BasicBlock *,
3006 ptrdiff_t, BasicBlock *, BasicBlock *> {
3007 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3008
3009 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3010 BasicBlock *operator->() const { return operator*(); }
3011 };
3012
3013 /// The const version of `succ_op_iterator`.
3014 struct const_succ_op_iterator
3015 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3016 std::random_access_iterator_tag,
3017 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3018 const BasicBlock *> {
3019 explicit const_succ_op_iterator(const_value_op_iterator I)
3020 : iterator_adaptor_base(I) {}
3021
3022 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3023 const BasicBlock *operator->() const { return operator*(); }
3024 };
3025
3026 static BranchInst *Create(BasicBlock *IfTrue,
3027 Instruction *InsertBefore = nullptr) {
3028 return new(1) BranchInst(IfTrue, InsertBefore);
3029 }
3030
3031 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3032 Value *Cond, Instruction *InsertBefore = nullptr) {
3033 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3034 }
3035
3036 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3037 return new(1) BranchInst(IfTrue, InsertAtEnd);
3038 }
3039
3040 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3041 Value *Cond, BasicBlock *InsertAtEnd) {
3042 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3043 }
3044
3045 /// Transparently provide more efficient getOperand methods.
3046 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
;
3047
3048 bool isUnconditional() const { return getNumOperands() == 1; }
3049 bool isConditional() const { return getNumOperands() == 3; }
3050
3051 Value *getCondition() const {
3052 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3052, __PRETTY_FUNCTION__))
;
3053 return Op<-3>();
3054 }
3055
3056 void setCondition(Value *V) {
3057 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3057, __PRETTY_FUNCTION__))
;
3058 Op<-3>() = V;
3059 }
3060
3061 unsigned getNumSuccessors() const { return 1+isConditional(); }
3062
3063 BasicBlock *getSuccessor(unsigned i) const {
3064 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3064, __PRETTY_FUNCTION__))
;
3065 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3066 }
3067
3068 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3069 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3069, __PRETTY_FUNCTION__))
;
3070 *(&Op<-1>() - idx) = NewSucc;
3071 }
3072
3073 /// Swap the successors of this branch instruction.
3074 ///
3075 /// Swaps the successors of the branch instruction. This also swaps any
3076 /// branch weight metadata associated with the instruction so that it
3077 /// continues to map correctly to each operand.
3078 void swapSuccessors();
3079
3080 iterator_range<succ_op_iterator> successors() {
3081 return make_range(
3082 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3083 succ_op_iterator(value_op_end()));
3084 }
3085
3086 iterator_range<const_succ_op_iterator> successors() const {
3087 return make_range(const_succ_op_iterator(
3088 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3089 const_succ_op_iterator(value_op_end()));
3090 }
3091
3092 // Methods for support type inquiry through isa, cast, and dyn_cast:
3093 static bool classof(const Instruction *I) {
3094 return (I->getOpcode() == Instruction::Br);
3095 }
3096 static bool classof(const Value *V) {
3097 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3098 }
3099};
3100
3101template <>
3102struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3103};
3104
3105DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3105, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3105, __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); }
3106
3107//===----------------------------------------------------------------------===//
3108// SwitchInst Class
3109//===----------------------------------------------------------------------===//
3110
3111//===---------------------------------------------------------------------------
3112/// Multiway switch
3113///
3114class SwitchInst : public Instruction {
3115 unsigned ReservedSpace;
3116
3117 // Operand[0] = Value to switch on
3118 // Operand[1] = Default basic block destination
3119 // Operand[2n ] = Value to match
3120 // Operand[2n+1] = BasicBlock to go to on match
3121 SwitchInst(const SwitchInst &SI);
3122
3123 /// Create a new switch instruction, specifying a value to switch on and a
3124 /// default destination. The number of additional cases can be specified here
3125 /// to make memory allocation more efficient. This constructor can also
3126 /// auto-insert before another instruction.
3127 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3128 Instruction *InsertBefore);
3129
3130 /// Create a new switch instruction, specifying a value to switch on and a
3131 /// default destination. The number of additional cases can be specified here
3132 /// to make memory allocation more efficient. This constructor also
3133 /// auto-inserts at the end of the specified BasicBlock.
3134 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3135 BasicBlock *InsertAtEnd);
3136
3137 // allocate space for exactly zero operands
3138 void *operator new(size_t s) {
3139 return User::operator new(s);
3140 }
3141
3142 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3143 void growOperands();
3144
3145protected:
3146 // Note: Instruction needs to be a friend here to call cloneImpl.
3147 friend class Instruction;
3148
3149 SwitchInst *cloneImpl() const;
3150
3151public:
3152 // -2
3153 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3154
3155 template <typename CaseHandleT> class CaseIteratorImpl;
3156
3157 /// A handle to a particular switch case. It exposes a convenient interface
3158 /// to both the case value and the successor block.
3159 ///
3160 /// We define this as a template and instantiate it to form both a const and
3161 /// non-const handle.
3162 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3163 class CaseHandleImpl {
3164 // Directly befriend both const and non-const iterators.
3165 friend class SwitchInst::CaseIteratorImpl<
3166 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3167
3168 protected:
3169 // Expose the switch type we're parameterized with to the iterator.
3170 using SwitchInstType = SwitchInstT;
3171
3172 SwitchInstT *SI;
3173 ptrdiff_t Index;
3174
3175 CaseHandleImpl() = default;
3176 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3177
3178 public:
3179 /// Resolves case value for current case.
3180 ConstantIntT *getCaseValue() const {
3181 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3182, __PRETTY_FUNCTION__))
3182 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3182, __PRETTY_FUNCTION__))
;
3183 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3184 }
3185
3186 /// Resolves successor for current case.
3187 BasicBlockT *getCaseSuccessor() const {
3188 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3190, __PRETTY_FUNCTION__))
3189 (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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3190, __PRETTY_FUNCTION__))
3190 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3190, __PRETTY_FUNCTION__))
;
3191 return SI->getSuccessor(getSuccessorIndex());
3192 }
3193
3194 /// Returns number of current case.
3195 unsigned getCaseIndex() const { return Index; }
3196
3197 /// Returns successor index for current case successor.
3198 unsigned getSuccessorIndex() const {
3199 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3201, __PRETTY_FUNCTION__))
3200 (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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3201, __PRETTY_FUNCTION__))
3201 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3201, __PRETTY_FUNCTION__))
;
3202 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3203 }
3204
3205 bool operator==(const CaseHandleImpl &RHS) const {
3206 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3206, __PRETTY_FUNCTION__))
;
3207 return Index == RHS.Index;
3208 }
3209 };
3210
3211 using ConstCaseHandle =
3212 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3213
3214 class CaseHandle
3215 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3216 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3217
3218 public:
3219 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3220
3221 /// Sets the new value for current case.
3222 void setValue(ConstantInt *V) {
3223 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3224, __PRETTY_FUNCTION__))
3224 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3224, __PRETTY_FUNCTION__))
;
3225 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3226 }
3227
3228 /// Sets the new successor for current case.
3229 void setSuccessor(BasicBlock *S) {
3230 SI->setSuccessor(getSuccessorIndex(), S);
3231 }
3232 };
3233
3234 template <typename CaseHandleT>
3235 class CaseIteratorImpl
3236 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3237 std::random_access_iterator_tag,
3238 CaseHandleT> {
3239 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3240
3241 CaseHandleT Case;
3242
3243 public:
3244 /// Default constructed iterator is in an invalid state until assigned to
3245 /// a case for a particular switch.
3246 CaseIteratorImpl() = default;
3247
3248 /// Initializes case iterator for given SwitchInst and for given
3249 /// case number.
3250 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3251
3252 /// Initializes case iterator for given SwitchInst and for given
3253 /// successor index.
3254 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3255 unsigned SuccessorIndex) {
3256 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3257, __PRETTY_FUNCTION__))
3257 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3257, __PRETTY_FUNCTION__))
;
3258 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3259 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3260 }
3261
3262 /// Support converting to the const variant. This will be a no-op for const
3263 /// variant.
3264 operator CaseIteratorImpl<ConstCaseHandle>() const {
3265 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3266 }
3267
3268 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3269 // Check index correctness after addition.
3270 // Note: Index == getNumCases() means end().
3271 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3273, __PRETTY_FUNCTION__))
3272 (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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3273, __PRETTY_FUNCTION__))
3273 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3273, __PRETTY_FUNCTION__))
;
3274 Case.Index += N;
3275 return *this;
3276 }
3277 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3278 // Check index correctness after subtraction.
3279 // Note: Case.Index == getNumCases() means end().
3280 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3282, __PRETTY_FUNCTION__))
3281 (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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3282, __PRETTY_FUNCTION__))
3282 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3282, __PRETTY_FUNCTION__))
;
3283 Case.Index -= N;
3284 return *this;
3285 }
3286 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3287 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3287, __PRETTY_FUNCTION__))
;
3288 return Case.Index - RHS.Case.Index;
3289 }
3290 bool operator==(const CaseIteratorImpl &RHS) const {
3291 return Case == RHS.Case;
3292 }
3293 bool operator<(const CaseIteratorImpl &RHS) const {
3294 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3294, __PRETTY_FUNCTION__))
;
3295 return Case.Index < RHS.Case.Index;
3296 }
3297 CaseHandleT &operator*() { return Case; }
3298 const CaseHandleT &operator*() const { return Case; }
3299 };
3300
3301 using CaseIt = CaseIteratorImpl<CaseHandle>;
3302 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3303
3304 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3305 unsigned NumCases,
3306 Instruction *InsertBefore = nullptr) {
3307 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3308 }
3309
3310 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3311 unsigned NumCases, BasicBlock *InsertAtEnd) {
3312 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3313 }
3314
3315 /// Provide fast operand accessors
3316 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
;
3317
3318 // Accessor Methods for Switch stmt
3319 Value *getCondition() const { return getOperand(0); }
3320 void setCondition(Value *V) { setOperand(0, V); }
3321
3322 BasicBlock *getDefaultDest() const {
3323 return cast<BasicBlock>(getOperand(1));
3324 }
3325
3326 void setDefaultDest(BasicBlock *DefaultCase) {
3327 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3328 }
3329
3330 /// Return the number of 'cases' in this switch instruction, excluding the
3331 /// default case.
3332 unsigned getNumCases() const {
3333 return getNumOperands()/2 - 1;
3334 }
3335
3336 /// Returns a read/write iterator that points to the first case in the
3337 /// SwitchInst.
3338 CaseIt case_begin() {
3339 return CaseIt(this, 0);
3340 }
3341
3342 /// Returns a read-only iterator that points to the first case in the
3343 /// SwitchInst.
3344 ConstCaseIt case_begin() const {
3345 return ConstCaseIt(this, 0);
3346 }
3347
3348 /// Returns a read/write iterator that points one past the last in the
3349 /// SwitchInst.
3350 CaseIt case_end() {
3351 return CaseIt(this, getNumCases());
3352 }
3353
3354 /// Returns a read-only iterator that points one past the last in the
3355 /// SwitchInst.
3356 ConstCaseIt case_end() const {
3357 return ConstCaseIt(this, getNumCases());
3358 }
3359
3360 /// Iteration adapter for range-for loops.
3361 iterator_range<CaseIt> cases() {
3362 return make_range(case_begin(), case_end());
3363 }
3364
3365 /// Constant iteration adapter for range-for loops.
3366 iterator_range<ConstCaseIt> cases() const {
3367 return make_range(case_begin(), case_end());
3368 }
3369
3370 /// Returns an iterator that points to the default case.
3371 /// Note: this iterator allows to resolve successor only. Attempt
3372 /// to resolve case value causes an assertion.
3373 /// Also note, that increment and decrement also causes an assertion and
3374 /// makes iterator invalid.
3375 CaseIt case_default() {
3376 return CaseIt(this, DefaultPseudoIndex);
3377 }
3378 ConstCaseIt case_default() const {
3379 return ConstCaseIt(this, DefaultPseudoIndex);
3380 }
3381
3382 /// Search all of the case values for the specified constant. If it is
3383 /// explicitly handled, return the case iterator of it, otherwise return
3384 /// default case iterator to indicate that it is handled by the default
3385 /// handler.
3386 CaseIt findCaseValue(const ConstantInt *C) {
3387 CaseIt I = llvm::find_if(
3388 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3389 if (I != case_end())
3390 return I;
3391
3392 return case_default();
3393 }
3394 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3395 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3396 return Case.getCaseValue() == C;
3397 });
3398 if (I != case_end())
3399 return I;
3400
3401 return case_default();
3402 }
3403
3404 /// Finds the unique case value for a given successor. Returns null if the
3405 /// successor is not found, not unique, or is the default case.
3406 ConstantInt *findCaseDest(BasicBlock *BB) {
3407 if (BB == getDefaultDest())
3408 return nullptr;
3409
3410 ConstantInt *CI = nullptr;
3411 for (auto Case : cases()) {
3412 if (Case.getCaseSuccessor() != BB)
3413 continue;
3414
3415 if (CI)
3416 return nullptr; // Multiple cases lead to BB.
3417
3418 CI = Case.getCaseValue();
3419 }
3420
3421 return CI;
3422 }
3423
3424 /// Add an entry to the switch instruction.
3425 /// Note:
3426 /// This action invalidates case_end(). Old case_end() iterator will
3427 /// point to the added case.
3428 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3429
3430 /// This method removes the specified case and its successor from the switch
3431 /// instruction. Note that this operation may reorder the remaining cases at
3432 /// index idx and above.
3433 /// Note:
3434 /// This action invalidates iterators for all cases following the one removed,
3435 /// including the case_end() iterator. It returns an iterator for the next
3436 /// case.
3437 CaseIt removeCase(CaseIt I);
3438
3439 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3440 BasicBlock *getSuccessor(unsigned idx) const {
3441 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3441, __PRETTY_FUNCTION__))
;
3442 return cast<BasicBlock>(getOperand(idx*2+1));
3443 }
3444 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3445 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3445, __PRETTY_FUNCTION__))
;
3446 setOperand(idx * 2 + 1, NewSucc);
3447 }
3448
3449 // Methods for support type inquiry through isa, cast, and dyn_cast:
3450 static bool classof(const Instruction *I) {
3451 return I->getOpcode() == Instruction::Switch;
3452 }
3453 static bool classof(const Value *V) {
3454 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3455 }
3456};
3457
3458/// A wrapper class to simplify modification of SwitchInst cases along with
3459/// their prof branch_weights metadata.
3460class SwitchInstProfUpdateWrapper {
3461 SwitchInst &SI;
3462 Optional<SmallVector<uint32_t, 8> > Weights = None;
3463 bool Changed = false;
3464
3465protected:
3466 static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
3467
3468 MDNode *buildProfBranchWeightsMD();
3469
3470 void init();
3471
3472public:
3473 using CaseWeightOpt = Optional<uint32_t>;
3474 SwitchInst *operator->() { return &SI; }
3475 SwitchInst &operator*() { return SI; }
3476 operator SwitchInst *() { return &SI; }
3477
3478 SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
3479
3480 ~SwitchInstProfUpdateWrapper() {
3481 if (Changed)
3482 SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
3483 }
3484
3485 /// Delegate the call to the underlying SwitchInst::removeCase() and remove
3486 /// correspondent branch weight.
3487 SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
3488
3489 /// Delegate the call to the underlying SwitchInst::addCase() and set the
3490 /// specified branch weight for the added case.
3491 void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
3492
3493 /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
3494 /// this object to not touch the underlying SwitchInst in destructor.
3495 SymbolTableList<Instruction>::iterator eraseFromParent();
3496
3497 void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
3498 CaseWeightOpt getSuccessorWeight(unsigned idx);
3499
3500 static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
3501};
3502
3503template <>
3504struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3505};
3506
3507DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3507, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3507, __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); }
3508
3509//===----------------------------------------------------------------------===//
3510// IndirectBrInst Class
3511//===----------------------------------------------------------------------===//
3512
3513//===---------------------------------------------------------------------------
3514/// Indirect Branch Instruction.
3515///
3516class IndirectBrInst : public Instruction {
3517 unsigned ReservedSpace;
3518
3519 // Operand[0] = Address to jump to
3520 // Operand[n+1] = n-th destination
3521 IndirectBrInst(const IndirectBrInst &IBI);
3522
3523 /// Create a new indirectbr instruction, specifying an
3524 /// Address to jump to. The number of expected destinations can be specified
3525 /// here to make memory allocation more efficient. This constructor can also
3526 /// autoinsert before another instruction.
3527 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3528
3529 /// Create a new indirectbr instruction, specifying an
3530 /// Address to jump to. The number of expected destinations can be specified
3531 /// here to make memory allocation more efficient. This constructor also
3532 /// autoinserts at the end of the specified BasicBlock.
3533 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3534
3535 // allocate space for exactly zero operands
3536 void *operator new(size_t s) {
3537 return User::operator new(s);
3538 }
3539
3540 void init(Value *Address, unsigned NumDests);
3541 void growOperands();
3542
3543protected:
3544 // Note: Instruction needs to be a friend here to call cloneImpl.
3545 friend class Instruction;
3546
3547 IndirectBrInst *cloneImpl() const;
3548
3549public:
3550 /// Iterator type that casts an operand to a basic block.
3551 ///
3552 /// This only makes sense because the successors are stored as adjacent
3553 /// operands for indirectbr instructions.
3554 struct succ_op_iterator
3555 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3556 std::random_access_iterator_tag, BasicBlock *,
3557 ptrdiff_t, BasicBlock *, BasicBlock *> {
3558 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3559
3560 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3561 BasicBlock *operator->() const { return operator*(); }
3562 };
3563
3564 /// The const version of `succ_op_iterator`.
3565 struct const_succ_op_iterator
3566 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3567 std::random_access_iterator_tag,
3568 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3569 const BasicBlock *> {
3570 explicit const_succ_op_iterator(const_value_op_iterator I)
3571 : iterator_adaptor_base(I) {}
3572
3573 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3574 const BasicBlock *operator->() const { return operator*(); }
3575 };
3576
3577 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3578 Instruction *InsertBefore = nullptr) {
3579 return new IndirectBrInst(Address, NumDests, InsertBefore);
3580 }
3581
3582 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3583 BasicBlock *InsertAtEnd) {
3584 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3585 }
3586
3587 /// Provide fast operand accessors.
3588 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
;
3589
3590 // Accessor Methods for IndirectBrInst instruction.
3591 Value *getAddress() { return getOperand(0); }
3592 const Value *getAddress() const { return getOperand(0); }
3593 void setAddress(Value *V) { setOperand(0, V); }
3594
3595 /// return the number of possible destinations in this
3596 /// indirectbr instruction.
3597 unsigned getNumDestinations() const { return getNumOperands()-1; }
3598
3599 /// Return the specified destination.
3600 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3601 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3602
3603 /// Add a destination.
3604 ///
3605 void addDestination(BasicBlock *Dest);
3606
3607 /// This method removes the specified successor from the
3608 /// indirectbr instruction.
3609 void removeDestination(unsigned i);
3610
3611 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3612 BasicBlock *getSuccessor(unsigned i) const {
3613 return cast<BasicBlock>(getOperand(i+1));
3614 }
3615 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3616 setOperand(i + 1, NewSucc);
3617 }
3618
3619 iterator_range<succ_op_iterator> successors() {
3620 return make_range(succ_op_iterator(std::next(value_op_begin())),
3621 succ_op_iterator(value_op_end()));
3622 }
3623
3624 iterator_range<const_succ_op_iterator> successors() const {
3625 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3626 const_succ_op_iterator(value_op_end()));
3627 }
3628
3629 // Methods for support type inquiry through isa, cast, and dyn_cast:
3630 static bool classof(const Instruction *I) {
3631 return I->getOpcode() == Instruction::IndirectBr;
3632 }
3633 static bool classof(const Value *V) {
3634 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3635 }
3636};
3637
3638template <>
3639struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3640};
3641
3642DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3642, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3642, __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); }
3643
3644//===----------------------------------------------------------------------===//
3645// InvokeInst Class
3646//===----------------------------------------------------------------------===//
3647
3648/// Invoke instruction. The SubclassData field is used to hold the
3649/// calling convention of the call.
3650///
3651class InvokeInst : public CallBase {
3652 /// The number of operands for this call beyond the called function,
3653 /// arguments, and operand bundles.
3654 static constexpr int NumExtraOperands = 2;
3655
3656 /// The index from the end of the operand array to the normal destination.
3657 static constexpr int NormalDestOpEndIdx = -3;
3658
3659 /// The index from the end of the operand array to the unwind destination.
3660 static constexpr int UnwindDestOpEndIdx = -2;
3661
3662 InvokeInst(const InvokeInst &BI);
3663
3664 /// Construct an InvokeInst given a range of arguments.
3665 ///
3666 /// Construct an InvokeInst from a range of arguments
3667 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3668 BasicBlock *IfException, ArrayRef<Value *> Args,
3669 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3670 const Twine &NameStr, Instruction *InsertBefore);
3671
3672 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3673 BasicBlock *IfException, ArrayRef<Value *> Args,
3674 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3675 const Twine &NameStr, BasicBlock *InsertAtEnd);
3676
3677 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3678 BasicBlock *IfException, ArrayRef<Value *> Args,
3679 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3680
3681 /// Compute the number of operands to allocate.
3682 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3683 // We need one operand for the called function, plus our extra operands and
3684 // the input operand counts provided.
3685 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3686 }
3687
3688protected:
3689 // Note: Instruction needs to be a friend here to call cloneImpl.
3690 friend class Instruction;
3691
3692 InvokeInst *cloneImpl() const;
3693
3694public:
3695 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3696 BasicBlock *IfException, ArrayRef<Value *> Args,
3697 const Twine &NameStr,
3698 Instruction *InsertBefore = nullptr) {
3699 int NumOperands = ComputeNumOperands(Args.size());
3700 return new (NumOperands)
3701 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3702 NameStr, InsertBefore);
3703 }
3704
3705 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3706 BasicBlock *IfException, ArrayRef<Value *> Args,
3707 ArrayRef<OperandBundleDef> Bundles = None,
3708 const Twine &NameStr = "",
3709 Instruction *InsertBefore = nullptr) {
3710 int NumOperands =
3711 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3712 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3713
3714 return new (NumOperands, DescriptorBytes)
3715 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3716 NameStr, InsertBefore);
3717 }
3718
3719 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3720 BasicBlock *IfException, ArrayRef<Value *> Args,
3721 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3722 int NumOperands = ComputeNumOperands(Args.size());
3723 return new (NumOperands)
3724 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3725 NameStr, InsertAtEnd);
3726 }
3727
3728 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3729 BasicBlock *IfException, ArrayRef<Value *> Args,
3730 ArrayRef<OperandBundleDef> Bundles,
3731 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3732 int NumOperands =
3733 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3734 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3735
3736 return new (NumOperands, DescriptorBytes)
3737 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3738 NameStr, InsertAtEnd);
3739 }
3740
3741 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3742 BasicBlock *IfException, ArrayRef<Value *> Args,
3743 const Twine &NameStr,
3744 Instruction *InsertBefore = nullptr) {
3745 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3746 IfException, Args, None, NameStr, InsertBefore);
3747 }
3748
3749 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3750 BasicBlock *IfException, ArrayRef<Value *> Args,
3751 ArrayRef<OperandBundleDef> Bundles = None,
3752 const Twine &NameStr = "",
3753 Instruction *InsertBefore = nullptr) {
3754 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3755 IfException, Args, Bundles, NameStr, InsertBefore);
3756 }
3757
3758 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3759 BasicBlock *IfException, ArrayRef<Value *> Args,
3760 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3761 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3762 IfException, Args, NameStr, InsertAtEnd);
3763 }
3764
3765 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3766 BasicBlock *IfException, ArrayRef<Value *> Args,
3767 ArrayRef<OperandBundleDef> Bundles,
3768 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3769 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3770 IfException, Args, Bundles, NameStr, InsertAtEnd);
3771 }
3772
3773 // Deprecated [opaque pointer types]
3774 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3775 BasicBlock *IfException, ArrayRef<Value *> Args,
3776 const Twine &NameStr,
3777 Instruction *InsertBefore = nullptr) {
3778 return Create(cast<FunctionType>(
3779 cast<PointerType>(Func->getType())->getElementType()),
3780 Func, IfNormal, IfException, Args, None, NameStr,
3781 InsertBefore);
3782 }
3783
3784 // Deprecated [opaque pointer types]
3785 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3786 BasicBlock *IfException, ArrayRef<Value *> Args,
3787 ArrayRef<OperandBundleDef> Bundles = None,
3788 const Twine &NameStr = "",
3789 Instruction *InsertBefore = nullptr) {
3790 return Create(cast<FunctionType>(
3791 cast<PointerType>(Func->getType())->getElementType()),
3792 Func, IfNormal, IfException, Args, Bundles, NameStr,
3793 InsertBefore);
3794 }
3795
3796 // Deprecated [opaque pointer types]
3797 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3798 BasicBlock *IfException, ArrayRef<Value *> Args,
3799 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3800 return Create(cast<FunctionType>(
3801 cast<PointerType>(Func->getType())->getElementType()),
3802 Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3803 }
3804
3805 // Deprecated [opaque pointer types]
3806 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3807 BasicBlock *IfException, ArrayRef<Value *> Args,
3808 ArrayRef<OperandBundleDef> Bundles,
3809 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3810 return Create(cast<FunctionType>(
3811 cast<PointerType>(Func->getType())->getElementType()),
3812 Func, IfNormal, IfException, Args, Bundles, NameStr,
3813 InsertAtEnd);
3814 }
3815
3816 /// Create a clone of \p II with a different set of operand bundles and
3817 /// insert it before \p InsertPt.
3818 ///
3819 /// The returned invoke instruction is identical to \p II in every way except
3820 /// that the operand bundles for the new instruction are set to the operand
3821 /// bundles in \p Bundles.
3822 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3823 Instruction *InsertPt = nullptr);
3824
3825 /// Determine if the call should not perform indirect branch tracking.
3826 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3827
3828 /// Determine if the call cannot unwind.
3829 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3830 void setDoesNotThrow() {
3831 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3832 }
3833
3834 // get*Dest - Return the destination basic blocks...
3835 BasicBlock *getNormalDest() const {
3836 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3837 }
3838 BasicBlock *getUnwindDest() const {
3839 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
15
Calling 'cast<llvm::BasicBlock, llvm::Use>'
28
Returning from 'cast<llvm::BasicBlock, llvm::Use>'
29
Returning pointer
3840 }
3841 void setNormalDest(BasicBlock *B) {
3842 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3843 }
3844 void setUnwindDest(BasicBlock *B) {
3845 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3846 }
3847
3848 /// Get the landingpad instruction from the landing pad
3849 /// block (the unwind destination).
3850 LandingPadInst *getLandingPadInst() const;
3851
3852 BasicBlock *getSuccessor(unsigned i) const {
3853 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3853, __PRETTY_FUNCTION__))
;
3854 return i == 0 ? getNormalDest() : getUnwindDest();
3855 }
3856
3857 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3858 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 3858, __PRETTY_FUNCTION__))
;
3859 if (i == 0)
3860 setNormalDest(NewSucc);
3861 else
3862 setUnwindDest(NewSucc);
3863 }
3864
3865 unsigned getNumSuccessors() const { return 2; }
3866
3867 // Methods for support type inquiry through isa, cast, and dyn_cast:
3868 static bool classof(const Instruction *I) {
3869 return (I->getOpcode() == Instruction::Invoke);
3870 }
3871 static bool classof(const Value *V) {
3872 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3873 }
3874
3875private:
3876
3877 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3878 // method so that subclasses cannot accidentally use it.
3879 void setInstructionSubclassData(unsigned short D) {
3880 Instruction::setInstructionSubclassData(D);
3881 }
3882};
3883
3884InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3885 BasicBlock *IfException, ArrayRef<Value *> Args,
3886 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3887 const Twine &NameStr, Instruction *InsertBefore)
3888 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3889 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3890 InsertBefore) {
3891 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3892}
3893
3894InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3895 BasicBlock *IfException, ArrayRef<Value *> Args,
3896 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3897 const Twine &NameStr, BasicBlock *InsertAtEnd)
3898 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3899 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3900 InsertAtEnd) {
3901 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3902}
3903
3904//===----------------------------------------------------------------------===//
3905// CallBrInst Class
3906//===----------------------------------------------------------------------===//
3907
3908/// CallBr instruction, tracking function calls that may not return control but
3909/// instead transfer it to a third location. The SubclassData field is used to
3910/// hold the calling convention of the call.
3911///
3912class CallBrInst : public CallBase {
3913
3914 unsigned NumIndirectDests;
3915
3916 CallBrInst(const CallBrInst &BI);
3917
3918 /// Construct a CallBrInst given a range of arguments.
3919 ///
3920 /// Construct a CallBrInst from a range of arguments
3921 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3922 ArrayRef<BasicBlock *> IndirectDests,
3923 ArrayRef<Value *> Args,
3924 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3925 const Twine &NameStr, Instruction *InsertBefore);
3926
3927 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3928 ArrayRef<BasicBlock *> IndirectDests,
3929 ArrayRef<Value *> Args,
3930 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3931 const Twine &NameStr, BasicBlock *InsertAtEnd);
3932
3933 void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3934 ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3935 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3936
3937 /// Should the Indirect Destinations change, scan + update the Arg list.
3938 void updateArgBlockAddresses(unsigned i, BasicBlock *B);
3939
3940 /// Compute the number of operands to allocate.
3941 static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3942 int NumBundleInputs = 0) {
3943 // We need one operand for the called function, plus our extra operands and
3944 // the input operand counts provided.
3945 return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3946 }
3947
3948protected:
3949 // Note: Instruction needs to be a friend here to call cloneImpl.
3950 friend class Instruction;
3951
3952 CallBrInst *cloneImpl() const;
3953
3954public:
3955 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3956 BasicBlock *DefaultDest,
3957 ArrayRef<BasicBlock *> IndirectDests,
3958 ArrayRef<Value *> Args, const Twine &NameStr,
3959 Instruction *InsertBefore = nullptr) {
3960 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3961 return new (NumOperands)
3962 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3963 NumOperands, NameStr, InsertBefore);
3964 }
3965
3966 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3967 BasicBlock *DefaultDest,
3968 ArrayRef<BasicBlock *> IndirectDests,
3969 ArrayRef<Value *> Args,
3970 ArrayRef<OperandBundleDef> Bundles = None,
3971 const Twine &NameStr = "",
3972 Instruction *InsertBefore = nullptr) {
3973 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3974 CountBundleInputs(Bundles));
3975 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3976
3977 return new (NumOperands, DescriptorBytes)
3978 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3979 NumOperands, NameStr, InsertBefore);
3980 }
3981
3982 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3983 BasicBlock *DefaultDest,
3984 ArrayRef<BasicBlock *> IndirectDests,
3985 ArrayRef<Value *> Args, const Twine &NameStr,
3986 BasicBlock *InsertAtEnd) {
3987 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3988 return new (NumOperands)
3989 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3990 NumOperands, NameStr, InsertAtEnd);
3991 }
3992
3993 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3994 BasicBlock *DefaultDest,
3995 ArrayRef<BasicBlock *> IndirectDests,
3996 ArrayRef<Value *> Args,
3997 ArrayRef<OperandBundleDef> Bundles,
3998 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3999 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
4000 CountBundleInputs(Bundles));
4001 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
4002
4003 return new (NumOperands, DescriptorBytes)
4004 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
4005 NumOperands, NameStr, InsertAtEnd);
4006 }
4007
4008 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4009 ArrayRef<BasicBlock *> IndirectDests,
4010 ArrayRef<Value *> Args, const Twine &NameStr,
4011 Instruction *InsertBefore = nullptr) {
4012 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4013 IndirectDests, Args, NameStr, InsertBefore);
4014 }
4015
4016 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4017 ArrayRef<BasicBlock *> IndirectDests,
4018 ArrayRef<Value *> Args,
4019 ArrayRef<OperandBundleDef> Bundles = None,
4020 const Twine &NameStr = "",
4021 Instruction *InsertBefore = nullptr) {
4022 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4023 IndirectDests, Args, Bundles, NameStr, InsertBefore);
4024 }
4025
4026 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4027 ArrayRef<BasicBlock *> IndirectDests,
4028 ArrayRef<Value *> Args, const Twine &NameStr,
4029 BasicBlock *InsertAtEnd) {
4030 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4031 IndirectDests, Args, NameStr, InsertAtEnd);
4032 }
4033
4034 static CallBrInst *Create(FunctionCallee Func,
4035 BasicBlock *DefaultDest,
4036 ArrayRef<BasicBlock *> IndirectDests,
4037 ArrayRef<Value *> Args,
4038 ArrayRef<OperandBundleDef> Bundles,
4039 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4040 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4041 IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4042 }
4043
4044 /// Create a clone of \p CBI with a different set of operand bundles and
4045 /// insert it before \p InsertPt.
4046 ///
4047 /// The returned callbr instruction is identical to \p CBI in every way
4048 /// except that the operand bundles for the new instruction are set to the
4049 /// operand bundles in \p Bundles.
4050 static CallBrInst *Create(CallBrInst *CBI,
4051 ArrayRef<OperandBundleDef> Bundles,
4052 Instruction *InsertPt = nullptr);
4053
4054 /// Return the number of callbr indirect dest labels.
4055 ///
4056 unsigned getNumIndirectDests() const { return NumIndirectDests; }
4057
4058 /// getIndirectDestLabel - Return the i-th indirect dest label.
4059 ///
4060 Value *getIndirectDestLabel(unsigned i) const {
4061 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 4061, __PRETTY_FUNCTION__))
;
4062 return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4063 1);
4064 }
4065
4066 Value *getIndirectDestLabelUse(unsigned i) const {
4067 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 4067, __PRETTY_FUNCTION__))
;
4068 return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4069 1);
4070 }
4071
4072 // Return the destination basic blocks...
4073 BasicBlock *getDefaultDest() const {
4074 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4075 }
4076 BasicBlock *getIndirectDest(unsigned i) const {
4077 return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4078 }
4079 SmallVector<BasicBlock *, 16> getIndirectDests() const {
4080 SmallVector<BasicBlock *, 16> IndirectDests;
4081 for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4082 IndirectDests.push_back(getIndirectDest(i));
4083 return IndirectDests;
4084 }
4085 void setDefaultDest(BasicBlock *B) {
4086 *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4087 }
4088 void setIndirectDest(unsigned i, BasicBlock *B) {
4089 updateArgBlockAddresses(i, B);
4090 *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4091 }
4092
4093 BasicBlock *getSuccessor(unsigned i) const {
4094 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 4095, __PRETTY_FUNCTION__))
4095 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 4095, __PRETTY_FUNCTION__))
;
4096 return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4097 }
4098
4099 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4100 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 4101, __PRETTY_FUNCTION__))
4101 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 4101, __PRETTY_FUNCTION__))
;
4102 return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
4103 }
4104
4105 unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4106
4107 // Methods for support type inquiry through isa, cast, and dyn_cast:
4108 static bool classof(const Instruction *I) {
4109 return (I->getOpcode() == Instruction::CallBr);
4110 }
4111 static bool classof(const Value *V) {
4112 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4113 }
4114
4115private:
4116
4117 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4118 // method so that subclasses cannot accidentally use it.
4119 void setInstructionSubclassData(unsigned short D) {
4120 Instruction::setInstructionSubclassData(D);
4121 }
4122};
4123
4124CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4125 ArrayRef<BasicBlock *> IndirectDests,
4126 ArrayRef<Value *> Args,
4127 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4128 const Twine &NameStr, Instruction *InsertBefore)
4129 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4130 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4131 InsertBefore) {
4132 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4133}
4134
4135CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4136 ArrayRef<BasicBlock *> IndirectDests,
4137 ArrayRef<Value *> Args,
4138 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4139 const Twine &NameStr, BasicBlock *InsertAtEnd)
4140 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4141 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4142 InsertAtEnd) {
4143 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4144}
4145
4146//===----------------------------------------------------------------------===//
4147// ResumeInst Class
4148//===----------------------------------------------------------------------===//
4149
4150//===---------------------------------------------------------------------------
4151/// Resume the propagation of an exception.
4152///
4153class ResumeInst : public Instruction {
4154 ResumeInst(const ResumeInst &RI);
4155
4156 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4157 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4158
4159protected