Bug Summary

File:llvm/lib/CodeGen/WinEHPrepare.cpp
Warning:line 211, 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 -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -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~++20200112100611+7fa5290d5bd/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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~++20200112100611+7fa5290d5bd/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -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-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/CodeGen/WinEHPrepare.cpp

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

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