Bug Summary

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

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318211/lib/CodeGen/WinEHPrepare.cpp

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

/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/Instructions.h

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

/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h

1//===- llvm/User.h - User class definition ----------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class defines the interface that one who uses a Value must implement.
11// Each instance of the Value class keeps track of what User's have handles
12// to it.
13//
14// * Instructions are the largest class of Users.
15// * Constants may be users of other constants (think arrays and stuff)
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_IR_USER_H
20#define LLVM_IR_USER_H
21
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/IR/Use.h"
25#include "llvm/IR/Value.h"
26#include "llvm/Support/Casting.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/ErrorHandling.h"
29#include <cassert>
30#include <cstddef>
31#include <cstdint>
32#include <iterator>
33
34namespace llvm {
35
36template <typename T> class ArrayRef;
37template <typename T> class MutableArrayRef;
38
39/// \brief Compile-time customization of User operands.
40///
41/// Customizes operand-related allocators and accessors.
42template <class>
43struct OperandTraits;
44
45class User : public Value {
46 template <unsigned>
47 friend struct HungoffOperandTraits;
48
49 LLVM_ATTRIBUTE_ALWAYS_INLINE__attribute__((always_inline)) inline static void *
50 allocateFixedOperandUser(size_t, unsigned, unsigned);
51
52protected:
53 /// Allocate a User with an operand pointer co-allocated.
54 ///
55 /// This is used for subclasses which need to allocate a variable number
56 /// of operands, ie, 'hung off uses'.
57 void *operator new(size_t Size);
58
59 /// Allocate a User with the operands co-allocated.
60 ///
61 /// This is used for subclasses which have a fixed number of operands.
62 void *operator new(size_t Size, unsigned Us);
63
64 /// Allocate a User with the operands co-allocated. If DescBytes is non-zero
65 /// then allocate an additional DescBytes bytes before the operands. These
66 /// bytes can be accessed by calling getDescriptor.
67 ///
68 /// DescBytes needs to be divisible by sizeof(void *). The allocated
69 /// descriptor, if any, is aligned to sizeof(void *) bytes.
70 ///
71 /// This is used for subclasses which have a fixed number of operands.
72 void *operator new(size_t Size, unsigned Us, unsigned DescBytes);
73
74 User(Type *ty, unsigned vty, Use *, unsigned NumOps)
75 : Value(ty, vty) {
76 assert(NumOps < (1u << NumUserOperandsBits) && "Too many operands")((NumOps < (1u << NumUserOperandsBits) && "Too many operands"
) ? static_cast<void> (0) : __assert_fail ("NumOps < (1u << NumUserOperandsBits) && \"Too many operands\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 76, __PRETTY_FUNCTION__))
;
77 NumUserOperands = NumOps;
78 // If we have hung off uses, then the operand list should initially be
79 // null.
80 assert((!HasHungOffUses || !getOperandList()) &&(((!HasHungOffUses || !getOperandList()) && "Error in initializing hung off uses for User"
) ? static_cast<void> (0) : __assert_fail ("(!HasHungOffUses || !getOperandList()) && \"Error in initializing hung off uses for User\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 81, __PRETTY_FUNCTION__))
81 "Error in initializing hung off uses for User")(((!HasHungOffUses || !getOperandList()) && "Error in initializing hung off uses for User"
) ? static_cast<void> (0) : __assert_fail ("(!HasHungOffUses || !getOperandList()) && \"Error in initializing hung off uses for User\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 81, __PRETTY_FUNCTION__))
;
82 }
83
84 /// \brief Allocate the array of Uses, followed by a pointer
85 /// (with bottom bit set) to the User.
86 /// \param IsPhi identifies callers which are phi nodes and which need
87 /// N BasicBlock* allocated along with N
88 void allocHungoffUses(unsigned N, bool IsPhi = false);
89
90 /// \brief Grow the number of hung off uses. Note that allocHungoffUses
91 /// should be called if there are no uses.
92 void growHungoffUses(unsigned N, bool IsPhi = false);
93
94protected:
95 ~User() = default; // Use deleteValue() to delete a generic Instruction.
96
97public:
98 User(const User &) = delete;
99
100 /// \brief Free memory allocated for User and Use objects.
101 void operator delete(void *Usr);
102 /// \brief Placement delete - required by std, but never called.
103 void operator delete(void*, unsigned) {
104 llvm_unreachable("Constructor throws?")::llvm::llvm_unreachable_internal("Constructor throws?", "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 104)
;
105 }
106 /// \brief Placement delete - required by std, but never called.
107 void operator delete(void*, unsigned, bool) {
108 llvm_unreachable("Constructor throws?")::llvm::llvm_unreachable_internal("Constructor throws?", "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 108)
;
109 }
110
111protected:
112 template <int Idx, typename U> static Use &OpFrom(const U *that) {
113 return Idx < 0
39
'?' condition is true
114 ? OperandTraits<U>::op_end(const_cast<U*>(that))[Idx]
40
Calling 'VariadicOperandTraits::op_end'
41
Returning from 'VariadicOperandTraits::op_end'
115 : OperandTraits<U>::op_begin(const_cast<U*>(that))[Idx];
116 }
117
118 template <int Idx> Use &Op() {
119 return OpFrom<Idx>(this);
120 }
121 template <int Idx> const Use &Op() const {
122 return OpFrom<Idx>(this);
123 }
124
125private:
126 const Use *getHungOffOperands() const {
127 return *(reinterpret_cast<const Use *const *>(this) - 1);
128 }
129
130 Use *&getHungOffOperands() { return *(reinterpret_cast<Use **>(this) - 1); }
131
132 const Use *getIntrusiveOperands() const {
133 return reinterpret_cast<const Use *>(this) - NumUserOperands;
134 }
135
136 Use *getIntrusiveOperands() {
137 return reinterpret_cast<Use *>(this) - NumUserOperands;
138 }
139
140 void setOperandList(Use *NewList) {
141 assert(HasHungOffUses &&((HasHungOffUses && "Setting operand list only required for hung off uses"
) ? static_cast<void> (0) : __assert_fail ("HasHungOffUses && \"Setting operand list only required for hung off uses\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 142, __PRETTY_FUNCTION__))
142 "Setting operand list only required for hung off uses")((HasHungOffUses && "Setting operand list only required for hung off uses"
) ? static_cast<void> (0) : __assert_fail ("HasHungOffUses && \"Setting operand list only required for hung off uses\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 142, __PRETTY_FUNCTION__))
;
143 getHungOffOperands() = NewList;
144 }
145
146public:
147 const Use *getOperandList() const {
148 return HasHungOffUses ? getHungOffOperands() : getIntrusiveOperands();
149 }
150 Use *getOperandList() {
151 return const_cast<Use *>(static_cast<const User *>(this)->getOperandList());
152 }
153
154 Value *getOperand(unsigned i) const {
155 assert(i < NumUserOperands && "getOperand() out of range!")((i < NumUserOperands && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumUserOperands && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 155, __PRETTY_FUNCTION__))
;
156 return getOperandList()[i];
157 }
158
159 void setOperand(unsigned i, Value *Val) {
160 assert(i < NumUserOperands && "setOperand() out of range!")((i < NumUserOperands && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumUserOperands && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 160, __PRETTY_FUNCTION__))
;
161 assert((!isa<Constant>((const Value*)this) ||(((!isa<Constant>((const Value*)this) || isa<GlobalValue
>((const Value*)this)) && "Cannot mutate a constant with setOperand!"
) ? static_cast<void> (0) : __assert_fail ("(!isa<Constant>((const Value*)this) || isa<GlobalValue>((const Value*)this)) && \"Cannot mutate a constant with setOperand!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 163, __PRETTY_FUNCTION__))
162 isa<GlobalValue>((const Value*)this)) &&(((!isa<Constant>((const Value*)this) || isa<GlobalValue
>((const Value*)this)) && "Cannot mutate a constant with setOperand!"
) ? static_cast<void> (0) : __assert_fail ("(!isa<Constant>((const Value*)this) || isa<GlobalValue>((const Value*)this)) && \"Cannot mutate a constant with setOperand!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 163, __PRETTY_FUNCTION__))
163 "Cannot mutate a constant with setOperand!")(((!isa<Constant>((const Value*)this) || isa<GlobalValue
>((const Value*)this)) && "Cannot mutate a constant with setOperand!"
) ? static_cast<void> (0) : __assert_fail ("(!isa<Constant>((const Value*)this) || isa<GlobalValue>((const Value*)this)) && \"Cannot mutate a constant with setOperand!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 163, __PRETTY_FUNCTION__))
;
164 getOperandList()[i] = Val;
165 }
166
167 const Use &getOperandUse(unsigned i) const {
168 assert(i < NumUserOperands && "getOperandUse() out of range!")((i < NumUserOperands && "getOperandUse() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumUserOperands && \"getOperandUse() out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 168, __PRETTY_FUNCTION__))
;
169 return getOperandList()[i];
170 }
171 Use &getOperandUse(unsigned i) {
172 assert(i < NumUserOperands && "getOperandUse() out of range!")((i < NumUserOperands && "getOperandUse() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumUserOperands && \"getOperandUse() out of range!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 172, __PRETTY_FUNCTION__))
;
173 return getOperandList()[i];
174 }
175
176 unsigned getNumOperands() const { return NumUserOperands; }
177
178 /// Returns the descriptor co-allocated with this User instance.
179 ArrayRef<const uint8_t> getDescriptor() const;
180
181 /// Returns the descriptor co-allocated with this User instance.
182 MutableArrayRef<uint8_t> getDescriptor();
183
184 /// Set the number of operands on a GlobalVariable.
185 ///
186 /// GlobalVariable always allocates space for a single operands, but
187 /// doesn't always use it.
188 ///
189 /// FIXME: As that the number of operands is used to find the start of
190 /// the allocated memory in operator delete, we need to always think we have
191 /// 1 operand before delete.
192 void setGlobalVariableNumOperands(unsigned NumOps) {
193 assert(NumOps <= 1 && "GlobalVariable can only have 0 or 1 operands")((NumOps <= 1 && "GlobalVariable can only have 0 or 1 operands"
) ? static_cast<void> (0) : __assert_fail ("NumOps <= 1 && \"GlobalVariable can only have 0 or 1 operands\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 193, __PRETTY_FUNCTION__))
;
194 NumUserOperands = NumOps;
195 }
196
197 /// \brief Subclasses with hung off uses need to manage the operand count
198 /// themselves. In these instances, the operand count isn't used to find the
199 /// OperandList, so there's no issue in having the operand count change.
200 void setNumHungOffUseOperands(unsigned NumOps) {
201 assert(HasHungOffUses && "Must have hung off uses to use this method")((HasHungOffUses && "Must have hung off uses to use this method"
) ? static_cast<void> (0) : __assert_fail ("HasHungOffUses && \"Must have hung off uses to use this method\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 201, __PRETTY_FUNCTION__))
;
202 assert(NumOps < (1u << NumUserOperandsBits) && "Too many operands")((NumOps < (1u << NumUserOperandsBits) && "Too many operands"
) ? static_cast<void> (0) : __assert_fail ("NumOps < (1u << NumUserOperandsBits) && \"Too many operands\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/IR/User.h"
, 202, __PRETTY_FUNCTION__))
;
203 NumUserOperands = NumOps;
204 }
205
206 // ---------------------------------------------------------------------------
207 // Operand Iterator interface...
208 //
209 using op_iterator = Use*;
210 using const_op_iterator = const Use*;
211 using op_range = iterator_range<op_iterator>;
212 using const_op_range = iterator_range<const_op_iterator>;
213
214 op_iterator op_begin() { return getOperandList(); }
215 const_op_iterator op_begin() const { return getOperandList(); }
216 op_iterator op_end() {
217 return getOperandList() + NumUserOperands;
218 }
219 const_op_iterator op_end() const {
220 return getOperandList() + NumUserOperands;
221 }
222 op_range operands() {
223 return op_range(op_begin(), op_end());
224 }
225 const_op_range operands() const {
226 return const_op_range(op_begin(), op_end());
227 }
228
229 /// \brief Iterator for directly iterating over the operand Values.
230 struct value_op_iterator
231 : iterator_adaptor_base<value_op_iterator, op_iterator,
232 std::random_access_iterator_tag, Value *,
233 ptrdiff_t, Value *, Value *> {
234 explicit value_op_iterator(Use *U = nullptr) : iterator_adaptor_base(U) {}
235
236 Value *operator*() const { return *I; }
237 Value *operator->() const { return operator*(); }
238 };
239
240 value_op_iterator value_op_begin() {
241 return value_op_iterator(op_begin());
242 }
243 value_op_iterator value_op_end() {
244 return value_op_iterator(op_end());
245 }
246 iterator_range<value_op_iterator> operand_values() {
247 return make_range(value_op_begin(), value_op_end());
248 }
249
250 struct const_value_op_iterator
251 : iterator_adaptor_base<const_value_op_iterator, const_op_iterator,
252 std::random_access_iterator_tag, const Value *,
253 ptrdiff_t, const Value *, const Value *> {
254 explicit const_value_op_iterator(const Use *U = nullptr) :
255 iterator_adaptor_base(U) {}
256
257 const Value *operator*() const { return *I; }
258 const Value *operator->() const { return operator*(); }
259 };
260
261 const_value_op_iterator value_op_begin() const {
262 return const_value_op_iterator(op_begin());
263 }
264 const_value_op_iterator value_op_end() const {
265 return const_value_op_iterator(op_end());
266 }
267 iterator_range<const_value_op_iterator> operand_values() const {
268 return make_range(value_op_begin(), value_op_end());
269 }
270
271 /// \brief Drop all references to operands.
272 ///
273 /// This function is in charge of "letting go" of all objects that this User
274 /// refers to. This allows one to 'delete' a whole class at a time, even
275 /// though there may be circular references... First all references are
276 /// dropped, and all use counts go to zero. Then everything is deleted for
277 /// real. Note that no operations are valid on an object that has "dropped
278 /// all references", except operator delete.
279 void dropAllReferences() {
280 for (Use &U : operands())
281 U.set(nullptr);
282 }
283
284 /// \brief Replace uses of one Value with another.
285 ///
286 /// Replaces all references to the "From" definition with references to the
287 /// "To" definition.
288 void replaceUsesOfWith(Value *From, Value *To);
289
290 // Methods for support type inquiry through isa, cast, and dyn_cast:
291 static bool classof(const Value *V) {
292 return isa<Instruction>(V) || isa<Constant>(V);
293 }
294};
295
296// Either Use objects, or a Use pointer can be prepended to User.
297static_assert(alignof(Use) >= alignof(User),
298 "Alignment is insufficient after objects prepended to User");
299static_assert(alignof(Use *) >= alignof(User),
300 "Alignment is insufficient after objects prepended to User");
301
302template<> struct simplify_type<User::op_iterator> {
303 using SimpleType = Value*;
304
305 static SimpleType getSimplifiedValue(User::op_iterator &Val) {
306 return Val->get();
307 }
308};
309template<> struct simplify_type<User::const_op_iterator> {
310 using SimpleType = /*const*/ Value*;
311
312 static SimpleType getSimplifiedValue(User::const_op_iterator &Val) {
313 return Val->get();
314 }
315};
316
317} // end namespace llvm
318
319#endif // LLVM_IR_USER_H

/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
60 }
61};
62
63/// \brief Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Casting.h"
, 85, __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Casting.h"
, 92, __PRETTY_FUNCTION__))
;
52
Within the expansion of the macro 'assert':
a
Assuming 'Val' is non-null
93 return isa_impl<To, From>::doit(*Val);
53