Bug Summary

File:src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/Alignment.h
Warning:line 85, column 47
The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'uint64_t'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Verifier.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 1 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Analysis -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ASMParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/BinaryFormat -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitstream -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /include/llvm/CodeGen -I /include/llvm/CodeGen/PBQP -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Coroutines -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData/Coverage -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/CodeView -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/DWARF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/MSF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/PDB -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Demangle -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/JITLink -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/Orc -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenACC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenMP -I /include/llvm/CodeGen/GlobalISel -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IRReader -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/LTO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Linker -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC/MCParser -I /include/llvm/CodeGen/MIRParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Option -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Passes -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Scalar -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/Symbolize -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Target -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Utils -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Vectorize -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/IPO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libLLVM/../include -I /usr/src/gnu/usr.bin/clang/libLLVM/obj -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -D PIC -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -D_RET_PROTECTOR -ret-protector -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/IR/Verifier.cpp

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/IR/Verifier.cpp

1//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the function verifier interface, that can be used for some
10// sanity checking of input to the system.
11//
12// Note that this does not provide full `Java style' security and verifications,
13// instead it just tries to ensure that code is well-formed.
14//
15// * Both of a binary operator's parameters are of the same type
16// * Verify that the indices of mem access instructions match other operands
17// * Verify that arithmetic and other things are only performed on first-class
18// types. Verify that shifts & logicals only happen on integrals f.e.
19// * All of the constants in a switch statement are of the correct type
20// * The code is in valid SSA form
21// * It should be illegal to put a label into any other type (like a structure)
22// or to return one. [except constant arrays!]
23// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24// * PHI nodes must have an entry for each predecessor, with no extras.
25// * PHI nodes must be the first thing in a basic block, all grouped together
26// * PHI nodes must have at least one entry
27// * All basic blocks should only end with terminator insts, not contain them
28// * The entry node to a function must not have predecessors
29// * All Instructions must be embedded into a basic block
30// * Functions cannot take a void-typed parameter
31// * Verify that a function's argument list agrees with it's declared type.
32// * It is illegal to specify a name for a void value.
33// * It is illegal to have a internal global value with no initializer
34// * It is illegal to have a ret instruction that returns a value that does not
35// agree with the function return value type.
36// * Function call argument types match the function prototype
37// * A landing pad is defined by a landingpad instruction, and can be jumped to
38// only by the unwind edge of an invoke instruction.
39// * A landingpad instruction must be the first non-PHI instruction in the
40// block.
41// * Landingpad instructions must be in a function with a personality function.
42// * All other things that are tested by asserts spread about the code...
43//
44//===----------------------------------------------------------------------===//
45
46#include "llvm/IR/Verifier.h"
47#include "llvm/ADT/APFloat.h"
48#include "llvm/ADT/APInt.h"
49#include "llvm/ADT/ArrayRef.h"
50#include "llvm/ADT/DenseMap.h"
51#include "llvm/ADT/MapVector.h"
52#include "llvm/ADT/Optional.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallSet.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/StringExtras.h"
58#include "llvm/ADT/StringMap.h"
59#include "llvm/ADT/StringRef.h"
60#include "llvm/ADT/Twine.h"
61#include "llvm/ADT/ilist.h"
62#include "llvm/BinaryFormat/Dwarf.h"
63#include "llvm/IR/Argument.h"
64#include "llvm/IR/Attributes.h"
65#include "llvm/IR/BasicBlock.h"
66#include "llvm/IR/CFG.h"
67#include "llvm/IR/CallingConv.h"
68#include "llvm/IR/Comdat.h"
69#include "llvm/IR/Constant.h"
70#include "llvm/IR/ConstantRange.h"
71#include "llvm/IR/Constants.h"
72#include "llvm/IR/DataLayout.h"
73#include "llvm/IR/DebugInfo.h"
74#include "llvm/IR/DebugInfoMetadata.h"
75#include "llvm/IR/DebugLoc.h"
76#include "llvm/IR/DerivedTypes.h"
77#include "llvm/IR/Dominators.h"
78#include "llvm/IR/Function.h"
79#include "llvm/IR/GlobalAlias.h"
80#include "llvm/IR/GlobalValue.h"
81#include "llvm/IR/GlobalVariable.h"
82#include "llvm/IR/InlineAsm.h"
83#include "llvm/IR/InstVisitor.h"
84#include "llvm/IR/InstrTypes.h"
85#include "llvm/IR/Instruction.h"
86#include "llvm/IR/Instructions.h"
87#include "llvm/IR/IntrinsicInst.h"
88#include "llvm/IR/Intrinsics.h"
89#include "llvm/IR/IntrinsicsWebAssembly.h"
90#include "llvm/IR/LLVMContext.h"
91#include "llvm/IR/Metadata.h"
92#include "llvm/IR/Module.h"
93#include "llvm/IR/ModuleSlotTracker.h"
94#include "llvm/IR/PassManager.h"
95#include "llvm/IR/Statepoint.h"
96#include "llvm/IR/Type.h"
97#include "llvm/IR/Use.h"
98#include "llvm/IR/User.h"
99#include "llvm/IR/Value.h"
100#include "llvm/InitializePasses.h"
101#include "llvm/Pass.h"
102#include "llvm/Support/AtomicOrdering.h"
103#include "llvm/Support/Casting.h"
104#include "llvm/Support/CommandLine.h"
105#include "llvm/Support/Debug.h"
106#include "llvm/Support/ErrorHandling.h"
107#include "llvm/Support/MathExtras.h"
108#include "llvm/Support/raw_ostream.h"
109#include <algorithm>
110#include <cassert>
111#include <cstdint>
112#include <memory>
113#include <string>
114#include <utility>
115
116using namespace llvm;
117
118static cl::opt<bool> VerifyNoAliasScopeDomination(
119 "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
120 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
121 "scopes are not dominating"));
122
123namespace llvm {
124
125struct VerifierSupport {
126 raw_ostream *OS;
127 const Module &M;
128 ModuleSlotTracker MST;
129 Triple TT;
130 const DataLayout &DL;
131 LLVMContext &Context;
132
133 /// Track the brokenness of the module while recursively visiting.
134 bool Broken = false;
135 /// Broken debug info can be "recovered" from by stripping the debug info.
136 bool BrokenDebugInfo = false;
137 /// Whether to treat broken debug info as an error.
138 bool TreatBrokenDebugInfoAsError = true;
139
140 explicit VerifierSupport(raw_ostream *OS, const Module &M)
141 : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
142 Context(M.getContext()) {}
143
144private:
145 void Write(const Module *M) {
146 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
147 }
148
149 void Write(const Value *V) {
150 if (V)
151 Write(*V);
152 }
153
154 void Write(const Value &V) {
155 if (isa<Instruction>(V)) {
156 V.print(*OS, MST);
157 *OS << '\n';
158 } else {
159 V.printAsOperand(*OS, true, MST);
160 *OS << '\n';
161 }
162 }
163
164 void Write(const Metadata *MD) {
165 if (!MD)
166 return;
167 MD->print(*OS, MST, &M);
168 *OS << '\n';
169 }
170
171 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
172 Write(MD.get());
173 }
174
175 void Write(const NamedMDNode *NMD) {
176 if (!NMD)
177 return;
178 NMD->print(*OS, MST);
179 *OS << '\n';
180 }
181
182 void Write(Type *T) {
183 if (!T)
184 return;
185 *OS << ' ' << *T;
186 }
187
188 void Write(const Comdat *C) {
189 if (!C)
190 return;
191 *OS << *C;
192 }
193
194 void Write(const APInt *AI) {
195 if (!AI)
196 return;
197 *OS << *AI << '\n';
198 }
199
200 void Write(const unsigned i) { *OS << i << '\n'; }
201
202 // NOLINTNEXTLINE(readability-identifier-naming)
203 void Write(const Attribute *A) {
204 if (!A)
205 return;
206 *OS << A->getAsString() << '\n';
207 }
208
209 // NOLINTNEXTLINE(readability-identifier-naming)
210 void Write(const AttributeSet *AS) {
211 if (!AS)
212 return;
213 *OS << AS->getAsString() << '\n';
214 }
215
216 // NOLINTNEXTLINE(readability-identifier-naming)
217 void Write(const AttributeList *AL) {
218 if (!AL)
219 return;
220 AL->print(*OS);
221 }
222
223 template <typename T> void Write(ArrayRef<T> Vs) {
224 for (const T &V : Vs)
225 Write(V);
226 }
227
228 template <typename T1, typename... Ts>
229 void WriteTs(const T1 &V1, const Ts &... Vs) {
230 Write(V1);
231 WriteTs(Vs...);
232 }
233
234 template <typename... Ts> void WriteTs() {}
235
236public:
237 /// A check failed, so printout out the condition and the message.
238 ///
239 /// This provides a nice place to put a breakpoint if you want to see why
240 /// something is not correct.
241 void CheckFailed(const Twine &Message) {
242 if (OS)
243 *OS << Message << '\n';
244 Broken = true;
245 }
246
247 /// A check failed (with values to print).
248 ///
249 /// This calls the Message-only version so that the above is easier to set a
250 /// breakpoint on.
251 template <typename T1, typename... Ts>
252 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
253 CheckFailed(Message);
254 if (OS)
255 WriteTs(V1, Vs...);
256 }
257
258 /// A debug info check failed.
259 void DebugInfoCheckFailed(const Twine &Message) {
260 if (OS)
261 *OS << Message << '\n';
262 Broken |= TreatBrokenDebugInfoAsError;
263 BrokenDebugInfo = true;
264 }
265
266 /// A debug info check failed (with values to print).
267 template <typename T1, typename... Ts>
268 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
269 const Ts &... Vs) {
270 DebugInfoCheckFailed(Message);
271 if (OS)
272 WriteTs(V1, Vs...);
273 }
274};
275
276} // namespace llvm
277
278namespace {
279
280class Verifier : public InstVisitor<Verifier>, VerifierSupport {
281 friend class InstVisitor<Verifier>;
282
283 DominatorTree DT;
284
285 /// When verifying a basic block, keep track of all of the
286 /// instructions we have seen so far.
287 ///
288 /// This allows us to do efficient dominance checks for the case when an
289 /// instruction has an operand that is an instruction in the same block.
290 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
291
292 /// Keep track of the metadata nodes that have been checked already.
293 SmallPtrSet<const Metadata *, 32> MDNodes;
294
295 /// Keep track which DISubprogram is attached to which function.
296 DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
297
298 /// Track all DICompileUnits visited.
299 SmallPtrSet<const Metadata *, 2> CUVisited;
300
301 /// The result type for a landingpad.
302 Type *LandingPadResultTy;
303
304 /// Whether we've seen a call to @llvm.localescape in this function
305 /// already.
306 bool SawFrameEscape;
307
308 /// Whether the current function has a DISubprogram attached to it.
309 bool HasDebugInfo = false;
310
311 /// The current source language.
312 dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user;
313
314 /// Whether source was present on the first DIFile encountered in each CU.
315 DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
316
317 /// Stores the count of how many objects were passed to llvm.localescape for a
318 /// given function and the largest index passed to llvm.localrecover.
319 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
320
321 // Maps catchswitches and cleanuppads that unwind to siblings to the
322 // terminators that indicate the unwind, used to detect cycles therein.
323 MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
324
325 /// Cache of constants visited in search of ConstantExprs.
326 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
327
328 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
329 SmallVector<const Function *, 4> DeoptimizeDeclarations;
330
331 /// Cache of attribute lists verified.
332 SmallPtrSet<const void *, 32> AttributeListsVisited;
333
334 // Verify that this GlobalValue is only used in this module.
335 // This map is used to avoid visiting uses twice. We can arrive at a user
336 // twice, if they have multiple operands. In particular for very large
337 // constant expressions, we can arrive at a particular user many times.
338 SmallPtrSet<const Value *, 32> GlobalValueVisited;
339
340 // Keeps track of duplicate function argument debug info.
341 SmallVector<const DILocalVariable *, 16> DebugFnArgs;
342
343 TBAAVerifier TBAAVerifyHelper;
344
345 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
346
347 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
348
349public:
350 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
351 const Module &M)
352 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
353 SawFrameEscape(false), TBAAVerifyHelper(this) {
354 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
355 }
356
357 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
358
359 bool verify(const Function &F) {
360 assert(F.getParent() == &M &&((void)0)
361 "An instance of this class only works with a specific module!")((void)0);
362
363 // First ensure the function is well-enough formed to compute dominance
364 // information, and directly compute a dominance tree. We don't rely on the
365 // pass manager to provide this as it isolates us from a potentially
366 // out-of-date dominator tree and makes it significantly more complex to run
367 // this code outside of a pass manager.
368 // FIXME: It's really gross that we have to cast away constness here.
369 if (!F.empty())
370 DT.recalculate(const_cast<Function &>(F));
371
372 for (const BasicBlock &BB : F) {
373 if (!BB.empty() && BB.back().isTerminator())
374 continue;
375
376 if (OS) {
377 *OS << "Basic Block in function '" << F.getName()
378 << "' does not have terminator!\n";
379 BB.printAsOperand(*OS, true, MST);
380 *OS << "\n";
381 }
382 return false;
383 }
384
385 Broken = false;
386 // FIXME: We strip const here because the inst visitor strips const.
387 visit(const_cast<Function &>(F));
388 verifySiblingFuncletUnwinds();
389 InstsInThisBlock.clear();
390 DebugFnArgs.clear();
391 LandingPadResultTy = nullptr;
392 SawFrameEscape = false;
393 SiblingFuncletInfo.clear();
394 verifyNoAliasScopeDecl();
395 NoAliasScopeDecls.clear();
396
397 return !Broken;
398 }
399
400 /// Verify the module that this instance of \c Verifier was initialized with.
401 bool verify() {
402 Broken = false;
403
404 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
405 for (const Function &F : M)
406 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
407 DeoptimizeDeclarations.push_back(&F);
408
409 // Now that we've visited every function, verify that we never asked to
410 // recover a frame index that wasn't escaped.
411 verifyFrameRecoverIndices();
412 for (const GlobalVariable &GV : M.globals())
413 visitGlobalVariable(GV);
414
415 for (const GlobalAlias &GA : M.aliases())
416 visitGlobalAlias(GA);
417
418 for (const NamedMDNode &NMD : M.named_metadata())
419 visitNamedMDNode(NMD);
420
421 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
422 visitComdat(SMEC.getValue());
423
424 visitModuleFlags(M);
425 visitModuleIdents(M);
426 visitModuleCommandLines(M);
427
428 verifyCompileUnits();
429
430 verifyDeoptimizeCallingConvs();
431 DISubprogramAttachments.clear();
432 return !Broken;
433 }
434
435private:
436 /// Whether a metadata node is allowed to be, or contain, a DILocation.
437 enum class AreDebugLocsAllowed { No, Yes };
438
439 // Verification methods...
440 void visitGlobalValue(const GlobalValue &GV);
441 void visitGlobalVariable(const GlobalVariable &GV);
442 void visitGlobalAlias(const GlobalAlias &GA);
443 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
444 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
445 const GlobalAlias &A, const Constant &C);
446 void visitNamedMDNode(const NamedMDNode &NMD);
447 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
448 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
449 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
450 void visitComdat(const Comdat &C);
451 void visitModuleIdents(const Module &M);
452 void visitModuleCommandLines(const Module &M);
453 void visitModuleFlags(const Module &M);
454 void visitModuleFlag(const MDNode *Op,
455 DenseMap<const MDString *, const MDNode *> &SeenIDs,
456 SmallVectorImpl<const MDNode *> &Requirements);
457 void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
458 void visitFunction(const Function &F);
459 void visitBasicBlock(BasicBlock &BB);
460 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
461 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
462 void visitProfMetadata(Instruction &I, MDNode *MD);
463 void visitAnnotationMetadata(MDNode *Annotation);
464
465 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
466#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
467#include "llvm/IR/Metadata.def"
468 void visitDIScope(const DIScope &N);
469 void visitDIVariable(const DIVariable &N);
470 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
471 void visitDITemplateParameter(const DITemplateParameter &N);
472
473 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
474
475 // InstVisitor overrides...
476 using InstVisitor<Verifier>::visit;
477 void visit(Instruction &I);
478
479 void visitTruncInst(TruncInst &I);
480 void visitZExtInst(ZExtInst &I);
481 void visitSExtInst(SExtInst &I);
482 void visitFPTruncInst(FPTruncInst &I);
483 void visitFPExtInst(FPExtInst &I);
484 void visitFPToUIInst(FPToUIInst &I);
485 void visitFPToSIInst(FPToSIInst &I);
486 void visitUIToFPInst(UIToFPInst &I);
487 void visitSIToFPInst(SIToFPInst &I);
488 void visitIntToPtrInst(IntToPtrInst &I);
489 void visitPtrToIntInst(PtrToIntInst &I);
490 void visitBitCastInst(BitCastInst &I);
491 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
492 void visitPHINode(PHINode &PN);
493 void visitCallBase(CallBase &Call);
494 void visitUnaryOperator(UnaryOperator &U);
495 void visitBinaryOperator(BinaryOperator &B);
496 void visitICmpInst(ICmpInst &IC);
497 void visitFCmpInst(FCmpInst &FC);
498 void visitExtractElementInst(ExtractElementInst &EI);
499 void visitInsertElementInst(InsertElementInst &EI);
500 void visitShuffleVectorInst(ShuffleVectorInst &EI);
501 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
502 void visitCallInst(CallInst &CI);
503 void visitInvokeInst(InvokeInst &II);
504 void visitGetElementPtrInst(GetElementPtrInst &GEP);
505 void visitLoadInst(LoadInst &LI);
506 void visitStoreInst(StoreInst &SI);
507 void verifyDominatesUse(Instruction &I, unsigned i);
508 void visitInstruction(Instruction &I);
509 void visitTerminator(Instruction &I);
510 void visitBranchInst(BranchInst &BI);
511 void visitReturnInst(ReturnInst &RI);
512 void visitSwitchInst(SwitchInst &SI);
513 void visitIndirectBrInst(IndirectBrInst &BI);
514 void visitCallBrInst(CallBrInst &CBI);
515 void visitSelectInst(SelectInst &SI);
516 void visitUserOp1(Instruction &I);
517 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
518 void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
519 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
520 void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
521 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
522 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
523 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
524 void visitFenceInst(FenceInst &FI);
525 void visitAllocaInst(AllocaInst &AI);
526 void visitExtractValueInst(ExtractValueInst &EVI);
527 void visitInsertValueInst(InsertValueInst &IVI);
528 void visitEHPadPredecessors(Instruction &I);
529 void visitLandingPadInst(LandingPadInst &LPI);
530 void visitResumeInst(ResumeInst &RI);
531 void visitCatchPadInst(CatchPadInst &CPI);
532 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
533 void visitCleanupPadInst(CleanupPadInst &CPI);
534 void visitFuncletPadInst(FuncletPadInst &FPI);
535 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
536 void visitCleanupReturnInst(CleanupReturnInst &CRI);
537
538 void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
539 void verifySwiftErrorValue(const Value *SwiftErrorVal);
540 void verifyTailCCMustTailAttrs(AttrBuilder Attrs, StringRef Context);
541 void verifyMustTailCall(CallInst &CI);
542 bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
543 void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
544 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
545 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
546 const Value *V);
547 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
548 const Value *V, bool IsIntrinsic);
549 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
550
551 void visitConstantExprsRecursively(const Constant *EntryC);
552 void visitConstantExpr(const ConstantExpr *CE);
553 void verifyStatepoint(const CallBase &Call);
554 void verifyFrameRecoverIndices();
555 void verifySiblingFuncletUnwinds();
556
557 void verifyFragmentExpression(const DbgVariableIntrinsic &I);
558 template <typename ValueOrMetadata>
559 void verifyFragmentExpression(const DIVariable &V,
560 DIExpression::FragmentInfo Fragment,
561 ValueOrMetadata *Desc);
562 void verifyFnArgs(const DbgVariableIntrinsic &I);
563 void verifyNotEntryValue(const DbgVariableIntrinsic &I);
564
565 /// Module-level debug info verification...
566 void verifyCompileUnits();
567
568 /// Module-level verification that all @llvm.experimental.deoptimize
569 /// declarations share the same calling convention.
570 void verifyDeoptimizeCallingConvs();
571
572 /// Verify all-or-nothing property of DIFile source attribute within a CU.
573 void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
574
575 /// Verify the llvm.experimental.noalias.scope.decl declarations
576 void verifyNoAliasScopeDecl();
577};
578
579} // end anonymous namespace
580
581/// We know that cond should be true, if not print an error message.
582#define Assert(C, ...)do { if (!(C)) { CheckFailed(...); return; } } while (false) \
583 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
584
585/// We know that a debug info condition should be true, if not print
586/// an error message.
587#define AssertDI(C, ...)do { if (!(C)) { DebugInfoCheckFailed(...); return; } } while
(false)
\
588 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
589
590void Verifier::visit(Instruction &I) {
591 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
592 Assert(I.getOperand(i) != nullptr, "Operand is null", &I)do { if (!(I.getOperand(i) != nullptr)) { CheckFailed("Operand is null"
, &I); return; } } while (false)
;
593 InstVisitor<Verifier>::visit(I);
594}
595
596// Helper to recursively iterate over indirect users. By
597// returning false, the callback can ask to stop recursing
598// further.
599static void forEachUser(const Value *User,
600 SmallPtrSet<const Value *, 32> &Visited,
601 llvm::function_ref<bool(const Value *)> Callback) {
602 if (!Visited.insert(User).second)
603 return;
604 for (const Value *TheNextUser : User->materialized_users())
605 if (Callback(TheNextUser))
606 forEachUser(TheNextUser, Visited, Callback);
607}
608
609void Verifier::visitGlobalValue(const GlobalValue &GV) {
610 Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),do { if (!(!GV.isDeclaration() || GV.hasValidDeclarationLinkage
())) { CheckFailed("Global is external, but doesn't have external or weak linkage!"
, &GV); return; } } while (false)
611 "Global is external, but doesn't have external or weak linkage!", &GV)do { if (!(!GV.isDeclaration() || GV.hasValidDeclarationLinkage
())) { CheckFailed("Global is external, but doesn't have external or weak linkage!"
, &GV); return; } } while (false)
;
612
613 if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV))
614 Assert(GO->getAlignment() <= Value::MaximumAlignment,do { if (!(GO->getAlignment() <= Value::MaximumAlignment
)) { CheckFailed("huge alignment values are unsupported", GO)
; return; } } while (false)
615 "huge alignment values are unsupported", GO)do { if (!(GO->getAlignment() <= Value::MaximumAlignment
)) { CheckFailed("huge alignment values are unsupported", GO)
; return; } } while (false)
;
616 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),do { if (!(!GV.hasAppendingLinkage() || isa<GlobalVariable
>(GV))) { CheckFailed("Only global variables can have appending linkage!"
, &GV); return; } } while (false)
617 "Only global variables can have appending linkage!", &GV)do { if (!(!GV.hasAppendingLinkage() || isa<GlobalVariable
>(GV))) { CheckFailed("Only global variables can have appending linkage!"
, &GV); return; } } while (false)
;
618
619 if (GV.hasAppendingLinkage()) {
620 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
621 Assert(GVar && GVar->getValueType()->isArrayTy(),do { if (!(GVar && GVar->getValueType()->isArrayTy
())) { CheckFailed("Only global arrays can have appending linkage!"
, GVar); return; } } while (false)
622 "Only global arrays can have appending linkage!", GVar)do { if (!(GVar && GVar->getValueType()->isArrayTy
())) { CheckFailed("Only global arrays can have appending linkage!"
, GVar); return; } } while (false)
;
623 }
624
625 if (GV.isDeclarationForLinker())
626 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV)do { if (!(!GV.hasComdat())) { CheckFailed("Declaration may not be in a Comdat!"
, &GV); return; } } while (false)
;
627
628 if (GV.hasDLLImportStorageClass()) {
629 Assert(!GV.isDSOLocal(),do { if (!(!GV.isDSOLocal())) { CheckFailed("GlobalValue with DLLImport Storage is dso_local!"
, &GV); return; } } while (false)
630 "GlobalValue with DLLImport Storage is dso_local!", &GV)do { if (!(!GV.isDSOLocal())) { CheckFailed("GlobalValue with DLLImport Storage is dso_local!"
, &GV); return; } } while (false)
;
631
632 Assert((GV.isDeclaration() &&do { if (!((GV.isDeclaration() && (GV.hasExternalLinkage
() || GV.hasExternalWeakLinkage())) || GV.hasAvailableExternallyLinkage
())) { CheckFailed("Global is marked as dllimport, but not external"
, &GV); return; } } while (false)
633 (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) ||do { if (!((GV.isDeclaration() && (GV.hasExternalLinkage
() || GV.hasExternalWeakLinkage())) || GV.hasAvailableExternallyLinkage
())) { CheckFailed("Global is marked as dllimport, but not external"
, &GV); return; } } while (false)
634 GV.hasAvailableExternallyLinkage(),do { if (!((GV.isDeclaration() && (GV.hasExternalLinkage
() || GV.hasExternalWeakLinkage())) || GV.hasAvailableExternallyLinkage
())) { CheckFailed("Global is marked as dllimport, but not external"
, &GV); return; } } while (false)
635 "Global is marked as dllimport, but not external", &GV)do { if (!((GV.isDeclaration() && (GV.hasExternalLinkage
() || GV.hasExternalWeakLinkage())) || GV.hasAvailableExternallyLinkage
())) { CheckFailed("Global is marked as dllimport, but not external"
, &GV); return; } } while (false)
;
636 }
637
638 if (GV.isImplicitDSOLocal())
639 Assert(GV.isDSOLocal(),do { if (!(GV.isDSOLocal())) { CheckFailed("GlobalValue with local linkage or non-default "
"visibility must be dso_local!", &GV); return; } } while
(false)
640 "GlobalValue with local linkage or non-default "do { if (!(GV.isDSOLocal())) { CheckFailed("GlobalValue with local linkage or non-default "
"visibility must be dso_local!", &GV); return; } } while
(false)
641 "visibility must be dso_local!",do { if (!(GV.isDSOLocal())) { CheckFailed("GlobalValue with local linkage or non-default "
"visibility must be dso_local!", &GV); return; } } while
(false)
642 &GV)do { if (!(GV.isDSOLocal())) { CheckFailed("GlobalValue with local linkage or non-default "
"visibility must be dso_local!", &GV); return; } } while
(false)
;
643
644 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
645 if (const Instruction *I = dyn_cast<Instruction>(V)) {
646 if (!I->getParent() || !I->getParent()->getParent())
647 CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
648 I);
649 else if (I->getParent()->getParent()->getParent() != &M)
650 CheckFailed("Global is referenced in a different module!", &GV, &M, I,
651 I->getParent()->getParent(),
652 I->getParent()->getParent()->getParent());
653 return false;
654 } else if (const Function *F = dyn_cast<Function>(V)) {
655 if (F->getParent() != &M)
656 CheckFailed("Global is used by function in a different module", &GV, &M,
657 F, F->getParent());
658 return false;
659 }
660 return true;
661 });
662}
663
664void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
665 if (GV.hasInitializer()) {
666 Assert(GV.getInitializer()->getType() == GV.getValueType(),do { if (!(GV.getInitializer()->getType() == GV.getValueType
())) { CheckFailed("Global variable initializer type does not match global "
"variable type!", &GV); return; } } while (false)
667 "Global variable initializer type does not match global "do { if (!(GV.getInitializer()->getType() == GV.getValueType
())) { CheckFailed("Global variable initializer type does not match global "
"variable type!", &GV); return; } } while (false)
668 "variable type!",do { if (!(GV.getInitializer()->getType() == GV.getValueType
())) { CheckFailed("Global variable initializer type does not match global "
"variable type!", &GV); return; } } while (false)
669 &GV)do { if (!(GV.getInitializer()->getType() == GV.getValueType
())) { CheckFailed("Global variable initializer type does not match global "
"variable type!", &GV); return; } } while (false)
;
670 // If the global has common linkage, it must have a zero initializer and
671 // cannot be constant.
672 if (GV.hasCommonLinkage()) {
673 Assert(GV.getInitializer()->isNullValue(),do { if (!(GV.getInitializer()->isNullValue())) { CheckFailed
("'common' global must have a zero initializer!", &GV); return
; } } while (false)
674 "'common' global must have a zero initializer!", &GV)do { if (!(GV.getInitializer()->isNullValue())) { CheckFailed
("'common' global must have a zero initializer!", &GV); return
; } } while (false)
;
675 Assert(!GV.isConstant(), "'common' global may not be marked constant!",do { if (!(!GV.isConstant())) { CheckFailed("'common' global may not be marked constant!"
, &GV); return; } } while (false)
676 &GV)do { if (!(!GV.isConstant())) { CheckFailed("'common' global may not be marked constant!"
, &GV); return; } } while (false)
;
677 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV)do { if (!(!GV.hasComdat())) { CheckFailed("'common' global may not be in a Comdat!"
, &GV); return; } } while (false)
;
678 }
679 }
680
681 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
682 GV.getName() == "llvm.global_dtors")) {
683 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),do { if (!(!GV.hasInitializer() || GV.hasAppendingLinkage()))
{ CheckFailed("invalid linkage for intrinsic global variable"
, &GV); return; } } while (false)
684 "invalid linkage for intrinsic global variable", &GV)do { if (!(!GV.hasInitializer() || GV.hasAppendingLinkage()))
{ CheckFailed("invalid linkage for intrinsic global variable"
, &GV); return; } } while (false)
;
685 // Don't worry about emitting an error for it not being an array,
686 // visitGlobalValue will complain on appending non-array.
687 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
688 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
689 PointerType *FuncPtrTy =
690 FunctionType::get(Type::getVoidTy(Context), false)->
691 getPointerTo(DL.getProgramAddressSpace());
692 Assert(STy &&do { if (!(STy && (STy->getNumElements() == 2 || STy
->getNumElements() == 3) && STy->getTypeAtIndex
(0u)->isIntegerTy(32) && STy->getTypeAtIndex(1)
== FuncPtrTy)) { CheckFailed("wrong type for intrinsic global variable"
, &GV); return; } } while (false)
693 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&do { if (!(STy && (STy->getNumElements() == 2 || STy
->getNumElements() == 3) && STy->getTypeAtIndex
(0u)->isIntegerTy(32) && STy->getTypeAtIndex(1)
== FuncPtrTy)) { CheckFailed("wrong type for intrinsic global variable"
, &GV); return; } } while (false)
694 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&do { if (!(STy && (STy->getNumElements() == 2 || STy
->getNumElements() == 3) && STy->getTypeAtIndex
(0u)->isIntegerTy(32) && STy->getTypeAtIndex(1)
== FuncPtrTy)) { CheckFailed("wrong type for intrinsic global variable"
, &GV); return; } } while (false)
695 STy->getTypeAtIndex(1) == FuncPtrTy,do { if (!(STy && (STy->getNumElements() == 2 || STy
->getNumElements() == 3) && STy->getTypeAtIndex
(0u)->isIntegerTy(32) && STy->getTypeAtIndex(1)
== FuncPtrTy)) { CheckFailed("wrong type for intrinsic global variable"
, &GV); return; } } while (false)
696 "wrong type for intrinsic global variable", &GV)do { if (!(STy && (STy->getNumElements() == 2 || STy
->getNumElements() == 3) && STy->getTypeAtIndex
(0u)->isIntegerTy(32) && STy->getTypeAtIndex(1)
== FuncPtrTy)) { CheckFailed("wrong type for intrinsic global variable"
, &GV); return; } } while (false)
;
697 Assert(STy->getNumElements() == 3,do { if (!(STy->getNumElements() == 3)) { CheckFailed("the third field of the element type is mandatory, "
"specify i8* null to migrate from the obsoleted 2-field form"
); return; } } while (false)
698 "the third field of the element type is mandatory, "do { if (!(STy->getNumElements() == 3)) { CheckFailed("the third field of the element type is mandatory, "
"specify i8* null to migrate from the obsoleted 2-field form"
); return; } } while (false)
699 "specify i8* null to migrate from the obsoleted 2-field form")do { if (!(STy->getNumElements() == 3)) { CheckFailed("the third field of the element type is mandatory, "
"specify i8* null to migrate from the obsoleted 2-field form"
); return; } } while (false)
;
700 Type *ETy = STy->getTypeAtIndex(2);
701 Type *Int8Ty = Type::getInt8Ty(ETy->getContext());
702 Assert(ETy->isPointerTy() &&do { if (!(ETy->isPointerTy() && cast<PointerType
>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty))) { CheckFailed
("wrong type for intrinsic global variable", &GV); return
; } } while (false)
703 cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty),do { if (!(ETy->isPointerTy() && cast<PointerType
>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty))) { CheckFailed
("wrong type for intrinsic global variable", &GV); return
; } } while (false)
704 "wrong type for intrinsic global variable", &GV)do { if (!(ETy->isPointerTy() && cast<PointerType
>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty))) { CheckFailed
("wrong type for intrinsic global variable", &GV); return
; } } while (false)
;
705 }
706 }
707
708 if (GV.hasName() && (GV.getName() == "llvm.used" ||
709 GV.getName() == "llvm.compiler.used")) {
710 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),do { if (!(!GV.hasInitializer() || GV.hasAppendingLinkage()))
{ CheckFailed("invalid linkage for intrinsic global variable"
, &GV); return; } } while (false)
711 "invalid linkage for intrinsic global variable", &GV)do { if (!(!GV.hasInitializer() || GV.hasAppendingLinkage()))
{ CheckFailed("invalid linkage for intrinsic global variable"
, &GV); return; } } while (false)
;
712 Type *GVType = GV.getValueType();
713 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
714 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
715 Assert(PTy, "wrong type for intrinsic global variable", &GV)do { if (!(PTy)) { CheckFailed("wrong type for intrinsic global variable"
, &GV); return; } } while (false)
;
716 if (GV.hasInitializer()) {
717 const Constant *Init = GV.getInitializer();
718 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
719 Assert(InitArray, "wrong initalizer for intrinsic global variable",do { if (!(InitArray)) { CheckFailed("wrong initalizer for intrinsic global variable"
, Init); return; } } while (false)
720 Init)do { if (!(InitArray)) { CheckFailed("wrong initalizer for intrinsic global variable"
, Init); return; } } while (false)
;
721 for (Value *Op : InitArray->operands()) {
722 Value *V = Op->stripPointerCasts();
723 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||do { if (!(isa<GlobalVariable>(V) || isa<Function>
(V) || isa<GlobalAlias>(V))) { CheckFailed("invalid llvm.used member"
, V); return; } } while (false)
724 isa<GlobalAlias>(V),do { if (!(isa<GlobalVariable>(V) || isa<Function>
(V) || isa<GlobalAlias>(V))) { CheckFailed("invalid llvm.used member"
, V); return; } } while (false)
725 "invalid llvm.used member", V)do { if (!(isa<GlobalVariable>(V) || isa<Function>
(V) || isa<GlobalAlias>(V))) { CheckFailed("invalid llvm.used member"
, V); return; } } while (false)
;
726 Assert(V->hasName(), "members of llvm.used must be named", V)do { if (!(V->hasName())) { CheckFailed("members of llvm.used must be named"
, V); return; } } while (false)
;
727 }
728 }
729 }
730 }
731
732 // Visit any debug info attachments.
733 SmallVector<MDNode *, 1> MDs;
734 GV.getMetadata(LLVMContext::MD_dbg, MDs);
735 for (auto *MD : MDs) {
736 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
737 visitDIGlobalVariableExpression(*GVE);
738 else
739 AssertDI(false, "!dbg attachment of global variable must be a "do { if (!(false)) { DebugInfoCheckFailed("!dbg attachment of global variable must be a "
"DIGlobalVariableExpression"); return; } } while (false)
740 "DIGlobalVariableExpression")do { if (!(false)) { DebugInfoCheckFailed("!dbg attachment of global variable must be a "
"DIGlobalVariableExpression"); return; } } while (false)
;
741 }
742
743 // Scalable vectors cannot be global variables, since we don't know
744 // the runtime size. If the global is an array containing scalable vectors,
745 // that will be caught by the isValidElementType methods in StructType or
746 // ArrayType instead.
747 Assert(!isa<ScalableVectorType>(GV.getValueType()),do { if (!(!isa<ScalableVectorType>(GV.getValueType()))
) { CheckFailed("Globals cannot contain scalable vectors", &
GV); return; } } while (false)
748 "Globals cannot contain scalable vectors", &GV)do { if (!(!isa<ScalableVectorType>(GV.getValueType()))
) { CheckFailed("Globals cannot contain scalable vectors", &
GV); return; } } while (false)
;
749
750 if (auto *STy = dyn_cast<StructType>(GV.getValueType()))
751 Assert(!STy->containsScalableVectorType(),do { if (!(!STy->containsScalableVectorType())) { CheckFailed
("Globals cannot contain scalable vectors", &GV); return;
} } while (false)
752 "Globals cannot contain scalable vectors", &GV)do { if (!(!STy->containsScalableVectorType())) { CheckFailed
("Globals cannot contain scalable vectors", &GV); return;
} } while (false)
;
753
754 if (!GV.hasInitializer()) {
755 visitGlobalValue(GV);
756 return;
757 }
758
759 // Walk any aggregate initializers looking for bitcasts between address spaces
760 visitConstantExprsRecursively(GV.getInitializer());
761
762 visitGlobalValue(GV);
763}
764
765void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
766 SmallPtrSet<const GlobalAlias*, 4> Visited;
767 Visited.insert(&GA);
768 visitAliaseeSubExpr(Visited, GA, C);
769}
770
771void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
772 const GlobalAlias &GA, const Constant &C) {
773 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
774 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",do { if (!(!GV->isDeclarationForLinker())) { CheckFailed("Alias must point to a definition"
, &GA); return; } } while (false)
775 &GA)do { if (!(!GV->isDeclarationForLinker())) { CheckFailed("Alias must point to a definition"
, &GA); return; } } while (false)
;
776
777 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
778 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA)do { if (!(Visited.insert(GA2).second)) { CheckFailed("Aliases cannot form a cycle"
, &GA); return; } } while (false)
;
779
780 Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",do { if (!(!GA2->isInterposable())) { CheckFailed("Alias cannot point to an interposable alias"
, &GA); return; } } while (false)
781 &GA)do { if (!(!GA2->isInterposable())) { CheckFailed("Alias cannot point to an interposable alias"
, &GA); return; } } while (false)
;
782 } else {
783 // Only continue verifying subexpressions of GlobalAliases.
784 // Do not recurse into global initializers.
785 return;
786 }
787 }
788
789 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
790 visitConstantExprsRecursively(CE);
791
792 for (const Use &U : C.operands()) {
793 Value *V = &*U;
794 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
795 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
796 else if (const auto *C2 = dyn_cast<Constant>(V))
797 visitAliaseeSubExpr(Visited, GA, *C2);
798 }
799}
800
801void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
802 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),do { if (!(GlobalAlias::isValidLinkage(GA.getLinkage()))) { CheckFailed
("Alias should have private, internal, linkonce, weak, linkonce_odr, "
"weak_odr, or external linkage!", &GA); return; } } while
(false)
803 "Alias should have private, internal, linkonce, weak, linkonce_odr, "do { if (!(GlobalAlias::isValidLinkage(GA.getLinkage()))) { CheckFailed
("Alias should have private, internal, linkonce, weak, linkonce_odr, "
"weak_odr, or external linkage!", &GA); return; } } while
(false)
804 "weak_odr, or external linkage!",do { if (!(GlobalAlias::isValidLinkage(GA.getLinkage()))) { CheckFailed
("Alias should have private, internal, linkonce, weak, linkonce_odr, "
"weak_odr, or external linkage!", &GA); return; } } while
(false)
805 &GA)do { if (!(GlobalAlias::isValidLinkage(GA.getLinkage()))) { CheckFailed
("Alias should have private, internal, linkonce, weak, linkonce_odr, "
"weak_odr, or external linkage!", &GA); return; } } while
(false)
;
806 const Constant *Aliasee = GA.getAliasee();
807 Assert(Aliasee, "Aliasee cannot be NULL!", &GA)do { if (!(Aliasee)) { CheckFailed("Aliasee cannot be NULL!",
&GA); return; } } while (false)
;
808 Assert(GA.getType() == Aliasee->getType(),do { if (!(GA.getType() == Aliasee->getType())) { CheckFailed
("Alias and aliasee types should match!", &GA); return; }
} while (false)
809 "Alias and aliasee types should match!", &GA)do { if (!(GA.getType() == Aliasee->getType())) { CheckFailed
("Alias and aliasee types should match!", &GA); return; }
} while (false)
;
810
811 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),do { if (!(isa<GlobalValue>(Aliasee) || isa<ConstantExpr
>(Aliasee))) { CheckFailed("Aliasee should be either GlobalValue or ConstantExpr"
, &GA); return; } } while (false)
812 "Aliasee should be either GlobalValue or ConstantExpr", &GA)do { if (!(isa<GlobalValue>(Aliasee) || isa<ConstantExpr
>(Aliasee))) { CheckFailed("Aliasee should be either GlobalValue or ConstantExpr"
, &GA); return; } } while (false)
;
813
814 visitAliaseeSubExpr(GA, *Aliasee);
815
816 visitGlobalValue(GA);
817}
818
819void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
820 // There used to be various other llvm.dbg.* nodes, but we don't support
821 // upgrading them and we want to reserve the namespace for future uses.
822 if (NMD.getName().startswith("llvm.dbg."))
823 AssertDI(NMD.getName() == "llvm.dbg.cu",do { if (!(NMD.getName() == "llvm.dbg.cu")) { DebugInfoCheckFailed
("unrecognized named metadata node in the llvm.dbg namespace"
, &NMD); return; } } while (false)
824 "unrecognized named metadata node in the llvm.dbg namespace",do { if (!(NMD.getName() == "llvm.dbg.cu")) { DebugInfoCheckFailed
("unrecognized named metadata node in the llvm.dbg namespace"
, &NMD); return; } } while (false)
825 &NMD)do { if (!(NMD.getName() == "llvm.dbg.cu")) { DebugInfoCheckFailed
("unrecognized named metadata node in the llvm.dbg namespace"
, &NMD); return; } } while (false)
;
826 for (const MDNode *MD : NMD.operands()) {
827 if (NMD.getName() == "llvm.dbg.cu")
828 AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD)do { if (!(MD && isa<DICompileUnit>(MD))) { DebugInfoCheckFailed
("invalid compile unit", &NMD, MD); return; } } while (false
)
;
829
830 if (!MD)
831 continue;
832
833 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
834 }
835}
836
837void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
838 // Only visit each node once. Metadata can be mutually recursive, so this
839 // avoids infinite recursion here, as well as being an optimization.
840 if (!MDNodes.insert(&MD).second)
841 return;
842
843 Assert(&MD.getContext() == &Context,do { if (!(&MD.getContext() == &Context)) { CheckFailed
("MDNode context does not match Module context!", &MD); return
; } } while (false)
844 "MDNode context does not match Module context!", &MD)do { if (!(&MD.getContext() == &Context)) { CheckFailed
("MDNode context does not match Module context!", &MD); return
; } } while (false)
;
845
846 switch (MD.getMetadataID()) {
847 default:
848 llvm_unreachable("Invalid MDNode subclass")__builtin_unreachable();
849 case Metadata::MDTupleKind:
850 break;
851#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
852 case Metadata::CLASS##Kind: \
853 visit##CLASS(cast<CLASS>(MD)); \
854 break;
855#include "llvm/IR/Metadata.def"
856 }
857
858 for (const Metadata *Op : MD.operands()) {
859 if (!Op)
860 continue;
861 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",do { if (!(!isa<LocalAsMetadata>(Op))) { CheckFailed("Invalid operand for global metadata!"
, &MD, Op); return; } } while (false)
862 &MD, Op)do { if (!(!isa<LocalAsMetadata>(Op))) { CheckFailed("Invalid operand for global metadata!"
, &MD, Op); return; } } while (false)
;
863 AssertDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,do { if (!(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed
::Yes)) { DebugInfoCheckFailed("DILocation not allowed within this metadata node"
, &MD, Op); return; } } while (false)
864 "DILocation not allowed within this metadata node", &MD, Op)do { if (!(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed
::Yes)) { DebugInfoCheckFailed("DILocation not allowed within this metadata node"
, &MD, Op); return; } } while (false)
;
865 if (auto *N = dyn_cast<MDNode>(Op)) {
866 visitMDNode(*N, AllowLocs);
867 continue;
868 }
869 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
870 visitValueAsMetadata(*V, nullptr);
871 continue;
872 }
873 }
874
875 // Check these last, so we diagnose problems in operands first.
876 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD)do { if (!(!MD.isTemporary())) { CheckFailed("Expected no forward declarations!"
, &MD); return; } } while (false)
;
877 Assert(MD.isResolved(), "All nodes should be resolved!", &MD)do { if (!(MD.isResolved())) { CheckFailed("All nodes should be resolved!"
, &MD); return; } } while (false)
;
878}
879
880void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
881 Assert(MD.getValue(), "Expected valid value", &MD)do { if (!(MD.getValue())) { CheckFailed("Expected valid value"
, &MD); return; } } while (false)
;
882 Assert(!MD.getValue()->getType()->isMetadataTy(),do { if (!(!MD.getValue()->getType()->isMetadataTy())) {
CheckFailed("Unexpected metadata round-trip through values",
&MD, MD.getValue()); return; } } while (false)
883 "Unexpected metadata round-trip through values", &MD, MD.getValue())do { if (!(!MD.getValue()->getType()->isMetadataTy())) {
CheckFailed("Unexpected metadata round-trip through values",
&MD, MD.getValue()); return; } } while (false)
;
884
885 auto *L = dyn_cast<LocalAsMetadata>(&MD);
886 if (!L)
887 return;
888
889 Assert(F, "function-local metadata used outside a function", L)do { if (!(F)) { CheckFailed("function-local metadata used outside a function"
, L); return; } } while (false)
;
890
891 // If this was an instruction, bb, or argument, verify that it is in the
892 // function that we expect.
893 Function *ActualF = nullptr;
894 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
895 Assert(I->getParent(), "function-local metadata not in basic block", L, I)do { if (!(I->getParent())) { CheckFailed("function-local metadata not in basic block"
, L, I); return; } } while (false)
;
896 ActualF = I->getParent()->getParent();
897 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
898 ActualF = BB->getParent();
899 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
900 ActualF = A->getParent();
901 assert(ActualF && "Unimplemented function local metadata case!")((void)0);
902
903 Assert(ActualF == F, "function-local metadata used in wrong function", L)do { if (!(ActualF == F)) { CheckFailed("function-local metadata used in wrong function"
, L); return; } } while (false)
;
904}
905
906void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
907 Metadata *MD = MDV.getMetadata();
908 if (auto *N = dyn_cast<MDNode>(MD)) {
909 visitMDNode(*N, AreDebugLocsAllowed::No);
910 return;
911 }
912
913 // Only visit each node once. Metadata can be mutually recursive, so this
914 // avoids infinite recursion here, as well as being an optimization.
915 if (!MDNodes.insert(MD).second)
916 return;
917
918 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
919 visitValueAsMetadata(*V, F);
920}
921
922static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
923static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
924static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
925
926void Verifier::visitDILocation(const DILocation &N) {
927 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),do { if (!(N.getRawScope() && isa<DILocalScope>
(N.getRawScope()))) { DebugInfoCheckFailed("location requires a valid scope"
, &N, N.getRawScope()); return; } } while (false)
928 "location requires a valid scope", &N, N.getRawScope())do { if (!(N.getRawScope() && isa<DILocalScope>
(N.getRawScope()))) { DebugInfoCheckFailed("location requires a valid scope"
, &N, N.getRawScope()); return; } } while (false)
;
929 if (auto *IA = N.getRawInlinedAt())
930 AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA)do { if (!(isa<DILocation>(IA))) { DebugInfoCheckFailed
("inlined-at should be a location", &N, IA); return; } } while
(false)
;
931 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
932 AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N)do { if (!(SP->isDefinition())) { DebugInfoCheckFailed("scope points into the type hierarchy"
, &N); return; } } while (false)
;
933}
934
935void Verifier::visitGenericDINode(const GenericDINode &N) {
936 AssertDI(N.getTag(), "invalid tag", &N)do { if (!(N.getTag())) { DebugInfoCheckFailed("invalid tag",
&N); return; } } while (false)
;
937}
938
939void Verifier::visitDIScope(const DIScope &N) {
940 if (auto *F = N.getRawFile())
941 AssertDI(isa<DIFile>(F), "invalid file", &N, F)do { if (!(isa<DIFile>(F))) { DebugInfoCheckFailed("invalid file"
, &N, F); return; } } while (false)
;
942}
943
944void Verifier::visitDISubrange(const DISubrange &N) {
945 AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_subrange_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
946 bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
947 AssertDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||do { if (!(HasAssumedSizedArraySupport || N.getRawCountNode()
|| N.getRawUpperBound())) { DebugInfoCheckFailed("Subrange must contain count or upperBound"
, &N); return; } } while (false)
948 N.getRawUpperBound(),do { if (!(HasAssumedSizedArraySupport || N.getRawCountNode()
|| N.getRawUpperBound())) { DebugInfoCheckFailed("Subrange must contain count or upperBound"
, &N); return; } } while (false)
949 "Subrange must contain count or upperBound", &N)do { if (!(HasAssumedSizedArraySupport || N.getRawCountNode()
|| N.getRawUpperBound())) { DebugInfoCheckFailed("Subrange must contain count or upperBound"
, &N); return; } } while (false)
;
950 AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(),do { if (!(!N.getRawCountNode() || !N.getRawUpperBound())) { DebugInfoCheckFailed
("Subrange can have any one of count or upperBound", &N);
return; } } while (false)
951 "Subrange can have any one of count or upperBound", &N)do { if (!(!N.getRawCountNode() || !N.getRawUpperBound())) { DebugInfoCheckFailed
("Subrange can have any one of count or upperBound", &N);
return; } } while (false)
;
952 auto *CBound = N.getRawCountNode();
953 AssertDI(!CBound || isa<ConstantAsMetadata>(CBound) ||do { if (!(!CBound || isa<ConstantAsMetadata>(CBound) ||
isa<DIVariable>(CBound) || isa<DIExpression>(CBound
))) { DebugInfoCheckFailed("Count must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
954 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),do { if (!(!CBound || isa<ConstantAsMetadata>(CBound) ||
isa<DIVariable>(CBound) || isa<DIExpression>(CBound
))) { DebugInfoCheckFailed("Count must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
955 "Count must be signed constant or DIVariable or DIExpression", &N)do { if (!(!CBound || isa<ConstantAsMetadata>(CBound) ||
isa<DIVariable>(CBound) || isa<DIExpression>(CBound
))) { DebugInfoCheckFailed("Count must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
;
956 auto Count = N.getCount();
957 AssertDI(!Count || !Count.is<ConstantInt *>() ||do { if (!(!Count || !Count.is<ConstantInt *>() || Count
.get<ConstantInt *>()->getSExtValue() >= -1)) { DebugInfoCheckFailed
("invalid subrange count", &N); return; } } while (false)
958 Count.get<ConstantInt *>()->getSExtValue() >= -1,do { if (!(!Count || !Count.is<ConstantInt *>() || Count
.get<ConstantInt *>()->getSExtValue() >= -1)) { DebugInfoCheckFailed
("invalid subrange count", &N); return; } } while (false)
959 "invalid subrange count", &N)do { if (!(!Count || !Count.is<ConstantInt *>() || Count
.get<ConstantInt *>()->getSExtValue() >= -1)) { DebugInfoCheckFailed
("invalid subrange count", &N); return; } } while (false)
;
960 auto *LBound = N.getRawLowerBound();
961 AssertDI(!LBound || isa<ConstantAsMetadata>(LBound) ||do { if (!(!LBound || isa<ConstantAsMetadata>(LBound) ||
isa<DIVariable>(LBound) || isa<DIExpression>(LBound
))) { DebugInfoCheckFailed("LowerBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
962 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),do { if (!(!LBound || isa<ConstantAsMetadata>(LBound) ||
isa<DIVariable>(LBound) || isa<DIExpression>(LBound
))) { DebugInfoCheckFailed("LowerBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
963 "LowerBound must be signed constant or DIVariable or DIExpression",do { if (!(!LBound || isa<ConstantAsMetadata>(LBound) ||
isa<DIVariable>(LBound) || isa<DIExpression>(LBound
))) { DebugInfoCheckFailed("LowerBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
964 &N)do { if (!(!LBound || isa<ConstantAsMetadata>(LBound) ||
isa<DIVariable>(LBound) || isa<DIExpression>(LBound
))) { DebugInfoCheckFailed("LowerBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
;
965 auto *UBound = N.getRawUpperBound();
966 AssertDI(!UBound || isa<ConstantAsMetadata>(UBound) ||do { if (!(!UBound || isa<ConstantAsMetadata>(UBound) ||
isa<DIVariable>(UBound) || isa<DIExpression>(UBound
))) { DebugInfoCheckFailed("UpperBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
967 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),do { if (!(!UBound || isa<ConstantAsMetadata>(UBound) ||
isa<DIVariable>(UBound) || isa<DIExpression>(UBound
))) { DebugInfoCheckFailed("UpperBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
968 "UpperBound must be signed constant or DIVariable or DIExpression",do { if (!(!UBound || isa<ConstantAsMetadata>(UBound) ||
isa<DIVariable>(UBound) || isa<DIExpression>(UBound
))) { DebugInfoCheckFailed("UpperBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
969 &N)do { if (!(!UBound || isa<ConstantAsMetadata>(UBound) ||
isa<DIVariable>(UBound) || isa<DIExpression>(UBound
))) { DebugInfoCheckFailed("UpperBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
;
970 auto *Stride = N.getRawStride();
971 AssertDI(!Stride || isa<ConstantAsMetadata>(Stride) ||do { if (!(!Stride || isa<ConstantAsMetadata>(Stride) ||
isa<DIVariable>(Stride) || isa<DIExpression>(Stride
))) { DebugInfoCheckFailed("Stride must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
972 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),do { if (!(!Stride || isa<ConstantAsMetadata>(Stride) ||
isa<DIVariable>(Stride) || isa<DIExpression>(Stride
))) { DebugInfoCheckFailed("Stride must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
973 "Stride must be signed constant or DIVariable or DIExpression", &N)do { if (!(!Stride || isa<ConstantAsMetadata>(Stride) ||
isa<DIVariable>(Stride) || isa<DIExpression>(Stride
))) { DebugInfoCheckFailed("Stride must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
;
974}
975
976void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
977 AssertDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_generic_subrange)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
978 AssertDI(N.getRawCountNode() || N.getRawUpperBound(),do { if (!(N.getRawCountNode() || N.getRawUpperBound())) { DebugInfoCheckFailed
("GenericSubrange must contain count or upperBound", &N);
return; } } while (false)
979 "GenericSubrange must contain count or upperBound", &N)do { if (!(N.getRawCountNode() || N.getRawUpperBound())) { DebugInfoCheckFailed
("GenericSubrange must contain count or upperBound", &N);
return; } } while (false)
;
980 AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(),do { if (!(!N.getRawCountNode() || !N.getRawUpperBound())) { DebugInfoCheckFailed
("GenericSubrange can have any one of count or upperBound", &
N); return; } } while (false)
981 "GenericSubrange can have any one of count or upperBound", &N)do { if (!(!N.getRawCountNode() || !N.getRawUpperBound())) { DebugInfoCheckFailed
("GenericSubrange can have any one of count or upperBound", &
N); return; } } while (false)
;
982 auto *CBound = N.getRawCountNode();
983 AssertDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),do { if (!(!CBound || isa<DIVariable>(CBound) || isa<
DIExpression>(CBound))) { DebugInfoCheckFailed("Count must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
984 "Count must be signed constant or DIVariable or DIExpression", &N)do { if (!(!CBound || isa<DIVariable>(CBound) || isa<
DIExpression>(CBound))) { DebugInfoCheckFailed("Count must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
;
985 auto *LBound = N.getRawLowerBound();
986 AssertDI(LBound, "GenericSubrange must contain lowerBound", &N)do { if (!(LBound)) { DebugInfoCheckFailed("GenericSubrange must contain lowerBound"
, &N); return; } } while (false)
;
987 AssertDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),do { if (!(isa<DIVariable>(LBound) || isa<DIExpression
>(LBound))) { DebugInfoCheckFailed("LowerBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
988 "LowerBound must be signed constant or DIVariable or DIExpression",do { if (!(isa<DIVariable>(LBound) || isa<DIExpression
>(LBound))) { DebugInfoCheckFailed("LowerBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
989 &N)do { if (!(isa<DIVariable>(LBound) || isa<DIExpression
>(LBound))) { DebugInfoCheckFailed("LowerBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
;
990 auto *UBound = N.getRawUpperBound();
991 AssertDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),do { if (!(!UBound || isa<DIVariable>(UBound) || isa<
DIExpression>(UBound))) { DebugInfoCheckFailed("UpperBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
992 "UpperBound must be signed constant or DIVariable or DIExpression",do { if (!(!UBound || isa<DIVariable>(UBound) || isa<
DIExpression>(UBound))) { DebugInfoCheckFailed("UpperBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
993 &N)do { if (!(!UBound || isa<DIVariable>(UBound) || isa<
DIExpression>(UBound))) { DebugInfoCheckFailed("UpperBound must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
;
994 auto *Stride = N.getRawStride();
995 AssertDI(Stride, "GenericSubrange must contain stride", &N)do { if (!(Stride)) { DebugInfoCheckFailed("GenericSubrange must contain stride"
, &N); return; } } while (false)
;
996 AssertDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),do { if (!(isa<DIVariable>(Stride) || isa<DIExpression
>(Stride))) { DebugInfoCheckFailed("Stride must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
997 "Stride must be signed constant or DIVariable or DIExpression", &N)do { if (!(isa<DIVariable>(Stride) || isa<DIExpression
>(Stride))) { DebugInfoCheckFailed("Stride must be signed constant or DIVariable or DIExpression"
, &N); return; } } while (false)
;
998}
999
1000void Verifier::visitDIEnumerator(const DIEnumerator &N) {
1001 AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_enumerator)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1002}
1003
1004void Verifier::visitDIBasicType(const DIBasicType &N) {
1005 AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||do { if (!(N.getTag() == dwarf::DW_TAG_base_type || N.getTag(
) == dwarf::DW_TAG_unspecified_type || N.getTag() == dwarf::DW_TAG_string_type
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1006 N.getTag() == dwarf::DW_TAG_unspecified_type ||do { if (!(N.getTag() == dwarf::DW_TAG_base_type || N.getTag(
) == dwarf::DW_TAG_unspecified_type || N.getTag() == dwarf::DW_TAG_string_type
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1007 N.getTag() == dwarf::DW_TAG_string_type,do { if (!(N.getTag() == dwarf::DW_TAG_base_type || N.getTag(
) == dwarf::DW_TAG_unspecified_type || N.getTag() == dwarf::DW_TAG_string_type
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1008 "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_base_type || N.getTag(
) == dwarf::DW_TAG_unspecified_type || N.getTag() == dwarf::DW_TAG_string_type
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
;
1009}
1010
1011void Verifier::visitDIStringType(const DIStringType &N) {
1012 AssertDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_string_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1013 AssertDI(!(N.isBigEndian() && N.isLittleEndian()) ,do { if (!(!(N.isBigEndian() && N.isLittleEndian())))
{ DebugInfoCheckFailed("has conflicting flags", &N); return
; } } while (false)
1014 "has conflicting flags", &N)do { if (!(!(N.isBigEndian() && N.isLittleEndian())))
{ DebugInfoCheckFailed("has conflicting flags", &N); return
; } } while (false)
;
1015}
1016
1017void Verifier::visitDIDerivedType(const DIDerivedType &N) {
1018 // Common scope checks.
1019 visitDIScope(N);
1020
1021 AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1022 N.getTag() == dwarf::DW_TAG_pointer_type ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1023 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1024 N.getTag() == dwarf::DW_TAG_reference_type ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1025 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1026 N.getTag() == dwarf::DW_TAG_const_type ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1027 N.getTag() == dwarf::DW_TAG_volatile_type ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1028 N.getTag() == dwarf::DW_TAG_restrict_type ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1029 N.getTag() == dwarf::DW_TAG_atomic_type ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1030 N.getTag() == dwarf::DW_TAG_member ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1031 N.getTag() == dwarf::DW_TAG_inheritance ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1032 N.getTag() == dwarf::DW_TAG_friend ||do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1033 N.getTag() == dwarf::DW_TAG_set_type,do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1034 "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_typedef || N.getTag() ==
dwarf::DW_TAG_pointer_type || N.getTag() == dwarf::DW_TAG_ptr_to_member_type
|| N.getTag() == dwarf::DW_TAG_reference_type || N.getTag() ==
dwarf::DW_TAG_rvalue_reference_type || N.getTag() == dwarf::
DW_TAG_const_type || N.getTag() == dwarf::DW_TAG_volatile_type
|| N.getTag() == dwarf::DW_TAG_restrict_type || N.getTag() ==
dwarf::DW_TAG_atomic_type || N.getTag() == dwarf::DW_TAG_member
|| N.getTag() == dwarf::DW_TAG_inheritance || N.getTag() == dwarf
::DW_TAG_friend || N.getTag() == dwarf::DW_TAG_set_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1035 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1036 AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,do { if (!(isType(N.getRawExtraData()))) { DebugInfoCheckFailed
("invalid pointer to member type", &N, N.getRawExtraData(
)); return; } } while (false)
1037 N.getRawExtraData())do { if (!(isType(N.getRawExtraData()))) { DebugInfoCheckFailed
("invalid pointer to member type", &N, N.getRawExtraData(
)); return; } } while (false)
;
1038 }
1039
1040 if (N.getTag() == dwarf::DW_TAG_set_type) {
1041 if (auto *T = N.getRawBaseType()) {
1042 auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1043 auto *Basic = dyn_cast_or_null<DIBasicType>(T);
1044 AssertDI(do { if (!((Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
) || (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned
|| Basic->getEncoding() == dwarf::DW_ATE_signed || Basic->
getEncoding() == dwarf::DW_ATE_unsigned_char || Basic->getEncoding
() == dwarf::DW_ATE_signed_char || Basic->getEncoding() ==
dwarf::DW_ATE_boolean)))) { DebugInfoCheckFailed("invalid set base type"
, &N, T); return; } } while (false)
1045 (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||do { if (!((Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
) || (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned
|| Basic->getEncoding() == dwarf::DW_ATE_signed || Basic->
getEncoding() == dwarf::DW_ATE_unsigned_char || Basic->getEncoding
() == dwarf::DW_ATE_signed_char || Basic->getEncoding() ==
dwarf::DW_ATE_boolean)))) { DebugInfoCheckFailed("invalid set base type"
, &N, T); return; } } while (false)
1046 (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||do { if (!((Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
) || (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned
|| Basic->getEncoding() == dwarf::DW_ATE_signed || Basic->
getEncoding() == dwarf::DW_ATE_unsigned_char || Basic->getEncoding
() == dwarf::DW_ATE_signed_char || Basic->getEncoding() ==
dwarf::DW_ATE_boolean)))) { DebugInfoCheckFailed("invalid set base type"
, &N, T); return; } } while (false)
1047 Basic->getEncoding() == dwarf::DW_ATE_signed ||do { if (!((Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
) || (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned
|| Basic->getEncoding() == dwarf::DW_ATE_signed || Basic->
getEncoding() == dwarf::DW_ATE_unsigned_char || Basic->getEncoding
() == dwarf::DW_ATE_signed_char || Basic->getEncoding() ==
dwarf::DW_ATE_boolean)))) { DebugInfoCheckFailed("invalid set base type"
, &N, T); return; } } while (false)
1048 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||do { if (!((Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
) || (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned
|| Basic->getEncoding() == dwarf::DW_ATE_signed || Basic->
getEncoding() == dwarf::DW_ATE_unsigned_char || Basic->getEncoding
() == dwarf::DW_ATE_signed_char || Basic->getEncoding() ==
dwarf::DW_ATE_boolean)))) { DebugInfoCheckFailed("invalid set base type"
, &N, T); return; } } while (false)
1049 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||do { if (!((Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
) || (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned
|| Basic->getEncoding() == dwarf::DW_ATE_signed || Basic->
getEncoding() == dwarf::DW_ATE_unsigned_char || Basic->getEncoding
() == dwarf::DW_ATE_signed_char || Basic->getEncoding() ==
dwarf::DW_ATE_boolean)))) { DebugInfoCheckFailed("invalid set base type"
, &N, T); return; } } while (false)
1050 Basic->getEncoding() == dwarf::DW_ATE_boolean)),do { if (!((Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
) || (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned
|| Basic->getEncoding() == dwarf::DW_ATE_signed || Basic->
getEncoding() == dwarf::DW_ATE_unsigned_char || Basic->getEncoding
() == dwarf::DW_ATE_signed_char || Basic->getEncoding() ==
dwarf::DW_ATE_boolean)))) { DebugInfoCheckFailed("invalid set base type"
, &N, T); return; } } while (false)
1051 "invalid set base type", &N, T)do { if (!((Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
) || (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned
|| Basic->getEncoding() == dwarf::DW_ATE_signed || Basic->
getEncoding() == dwarf::DW_ATE_unsigned_char || Basic->getEncoding
() == dwarf::DW_ATE_signed_char || Basic->getEncoding() ==
dwarf::DW_ATE_boolean)))) { DebugInfoCheckFailed("invalid set base type"
, &N, T); return; } } while (false)
;
1052 }
1053 }
1054
1055 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope())do { if (!(isScope(N.getRawScope()))) { DebugInfoCheckFailed(
"invalid scope", &N, N.getRawScope()); return; } } while (
false)
;
1056 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,do { if (!(isType(N.getRawBaseType()))) { DebugInfoCheckFailed
("invalid base type", &N, N.getRawBaseType()); return; } }
while (false)
1057 N.getRawBaseType())do { if (!(isType(N.getRawBaseType()))) { DebugInfoCheckFailed
("invalid base type", &N, N.getRawBaseType()); return; } }
while (false)
;
1058
1059 if (N.getDWARFAddressSpace()) {
1060 AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type ||do { if (!(N.getTag() == dwarf::DW_TAG_pointer_type || N.getTag
() == dwarf::DW_TAG_reference_type || N.getTag() == dwarf::DW_TAG_rvalue_reference_type
)) { DebugInfoCheckFailed("DWARF address space only applies to pointer or reference types"
, &N); return; } } while (false)
1061 N.getTag() == dwarf::DW_TAG_reference_type ||do { if (!(N.getTag() == dwarf::DW_TAG_pointer_type || N.getTag
() == dwarf::DW_TAG_reference_type || N.getTag() == dwarf::DW_TAG_rvalue_reference_type
)) { DebugInfoCheckFailed("DWARF address space only applies to pointer or reference types"
, &N); return; } } while (false)
1062 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,do { if (!(N.getTag() == dwarf::DW_TAG_pointer_type || N.getTag
() == dwarf::DW_TAG_reference_type || N.getTag() == dwarf::DW_TAG_rvalue_reference_type
)) { DebugInfoCheckFailed("DWARF address space only applies to pointer or reference types"
, &N); return; } } while (false)
1063 "DWARF address space only applies to pointer or reference types",do { if (!(N.getTag() == dwarf::DW_TAG_pointer_type || N.getTag
() == dwarf::DW_TAG_reference_type || N.getTag() == dwarf::DW_TAG_rvalue_reference_type
)) { DebugInfoCheckFailed("DWARF address space only applies to pointer or reference types"
, &N); return; } } while (false)
1064 &N)do { if (!(N.getTag() == dwarf::DW_TAG_pointer_type || N.getTag
() == dwarf::DW_TAG_reference_type || N.getTag() == dwarf::DW_TAG_rvalue_reference_type
)) { DebugInfoCheckFailed("DWARF address space only applies to pointer or reference types"
, &N); return; } } while (false)
;
1065 }
1066}
1067
1068/// Detect mutually exclusive flags.
1069static bool hasConflictingReferenceFlags(unsigned Flags) {
1070 return ((Flags & DINode::FlagLValueReference) &&
1071 (Flags & DINode::FlagRValueReference)) ||
1072 ((Flags & DINode::FlagTypePassByValue) &&
1073 (Flags & DINode::FlagTypePassByReference));
1074}
1075
1076void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
1077 auto *Params = dyn_cast<MDTuple>(&RawParams);
1078 AssertDI(Params, "invalid template params", &N, &RawParams)do { if (!(Params)) { DebugInfoCheckFailed("invalid template params"
, &N, &RawParams); return; } } while (false)
;
1079 for (Metadata *Op : Params->operands()) {
1080 AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",do { if (!(Op && isa<DITemplateParameter>(Op)))
{ DebugInfoCheckFailed("invalid template parameter", &N,
Params, Op); return; } } while (false)
1081 &N, Params, Op)do { if (!(Op && isa<DITemplateParameter>(Op)))
{ DebugInfoCheckFailed("invalid template parameter", &N,
Params, Op); return; } } while (false)
;
1082 }
1083}
1084
1085void Verifier::visitDICompositeType(const DICompositeType &N) {
1086 // Common scope checks.
1087 visitDIScope(N);
1088
1089 AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||do { if (!(N.getTag() == dwarf::DW_TAG_array_type || N.getTag
() == dwarf::DW_TAG_structure_type || N.getTag() == dwarf::DW_TAG_union_type
|| N.getTag() == dwarf::DW_TAG_enumeration_type || N.getTag(
) == dwarf::DW_TAG_class_type || N.getTag() == dwarf::DW_TAG_variant_part
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1090 N.getTag() == dwarf::DW_TAG_structure_type ||do { if (!(N.getTag() == dwarf::DW_TAG_array_type || N.getTag
() == dwarf::DW_TAG_structure_type || N.getTag() == dwarf::DW_TAG_union_type
|| N.getTag() == dwarf::DW_TAG_enumeration_type || N.getTag(
) == dwarf::DW_TAG_class_type || N.getTag() == dwarf::DW_TAG_variant_part
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1091 N.getTag() == dwarf::DW_TAG_union_type ||do { if (!(N.getTag() == dwarf::DW_TAG_array_type || N.getTag
() == dwarf::DW_TAG_structure_type || N.getTag() == dwarf::DW_TAG_union_type
|| N.getTag() == dwarf::DW_TAG_enumeration_type || N.getTag(
) == dwarf::DW_TAG_class_type || N.getTag() == dwarf::DW_TAG_variant_part
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1092 N.getTag() == dwarf::DW_TAG_enumeration_type ||do { if (!(N.getTag() == dwarf::DW_TAG_array_type || N.getTag
() == dwarf::DW_TAG_structure_type || N.getTag() == dwarf::DW_TAG_union_type
|| N.getTag() == dwarf::DW_TAG_enumeration_type || N.getTag(
) == dwarf::DW_TAG_class_type || N.getTag() == dwarf::DW_TAG_variant_part
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1093 N.getTag() == dwarf::DW_TAG_class_type ||do { if (!(N.getTag() == dwarf::DW_TAG_array_type || N.getTag
() == dwarf::DW_TAG_structure_type || N.getTag() == dwarf::DW_TAG_union_type
|| N.getTag() == dwarf::DW_TAG_enumeration_type || N.getTag(
) == dwarf::DW_TAG_class_type || N.getTag() == dwarf::DW_TAG_variant_part
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1094 N.getTag() == dwarf::DW_TAG_variant_part,do { if (!(N.getTag() == dwarf::DW_TAG_array_type || N.getTag
() == dwarf::DW_TAG_structure_type || N.getTag() == dwarf::DW_TAG_union_type
|| N.getTag() == dwarf::DW_TAG_enumeration_type || N.getTag(
) == dwarf::DW_TAG_class_type || N.getTag() == dwarf::DW_TAG_variant_part
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1095 "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_array_type || N.getTag
() == dwarf::DW_TAG_structure_type || N.getTag() == dwarf::DW_TAG_union_type
|| N.getTag() == dwarf::DW_TAG_enumeration_type || N.getTag(
) == dwarf::DW_TAG_class_type || N.getTag() == dwarf::DW_TAG_variant_part
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
;
1096
1097 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope())do { if (!(isScope(N.getRawScope()))) { DebugInfoCheckFailed(
"invalid scope", &N, N.getRawScope()); return; } } while (
false)
;
1098 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,do { if (!(isType(N.getRawBaseType()))) { DebugInfoCheckFailed
("invalid base type", &N, N.getRawBaseType()); return; } }
while (false)
1099 N.getRawBaseType())do { if (!(isType(N.getRawBaseType()))) { DebugInfoCheckFailed
("invalid base type", &N, N.getRawBaseType()); return; } }
while (false)
;
1100
1101 AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),do { if (!(!N.getRawElements() || isa<MDTuple>(N.getRawElements
()))) { DebugInfoCheckFailed("invalid composite elements", &
N, N.getRawElements()); return; } } while (false)
1102 "invalid composite elements", &N, N.getRawElements())do { if (!(!N.getRawElements() || isa<MDTuple>(N.getRawElements
()))) { DebugInfoCheckFailed("invalid composite elements", &
N, N.getRawElements()); return; } } while (false)
;
1103 AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,do { if (!(isType(N.getRawVTableHolder()))) { DebugInfoCheckFailed
("invalid vtable holder", &N, N.getRawVTableHolder()); return
; } } while (false)
1104 N.getRawVTableHolder())do { if (!(isType(N.getRawVTableHolder()))) { DebugInfoCheckFailed
("invalid vtable holder", &N, N.getRawVTableHolder()); return
; } } while (false)
;
1105 AssertDI(!hasConflictingReferenceFlags(N.getFlags()),do { if (!(!hasConflictingReferenceFlags(N.getFlags()))) { DebugInfoCheckFailed
("invalid reference flags", &N); return; } } while (false
)
1106 "invalid reference flags", &N)do { if (!(!hasConflictingReferenceFlags(N.getFlags()))) { DebugInfoCheckFailed
("invalid reference flags", &N); return; } } while (false
)
;
1107 unsigned DIBlockByRefStruct = 1 << 4;
1108 AssertDI((N.getFlags() & DIBlockByRefStruct) == 0,do { if (!((N.getFlags() & DIBlockByRefStruct) == 0)) { DebugInfoCheckFailed
("DIBlockByRefStruct on DICompositeType is no longer supported"
, &N); return; } } while (false)
1109 "DIBlockByRefStruct on DICompositeType is no longer supported", &N)do { if (!((N.getFlags() & DIBlockByRefStruct) == 0)) { DebugInfoCheckFailed
("DIBlockByRefStruct on DICompositeType is no longer supported"
, &N); return; } } while (false)
;
1110
1111 if (N.isVector()) {
1112 const DINodeArray Elements = N.getElements();
1113 AssertDI(Elements.size() == 1 &&do { if (!(Elements.size() == 1 && Elements[0]->getTag
() == dwarf::DW_TAG_subrange_type)) { DebugInfoCheckFailed("invalid vector, expected one element of type subrange"
, &N); return; } } while (false)
1114 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,do { if (!(Elements.size() == 1 && Elements[0]->getTag
() == dwarf::DW_TAG_subrange_type)) { DebugInfoCheckFailed("invalid vector, expected one element of type subrange"
, &N); return; } } while (false)
1115 "invalid vector, expected one element of type subrange", &N)do { if (!(Elements.size() == 1 && Elements[0]->getTag
() == dwarf::DW_TAG_subrange_type)) { DebugInfoCheckFailed("invalid vector, expected one element of type subrange"
, &N); return; } } while (false)
;
1116 }
1117
1118 if (auto *Params = N.getRawTemplateParams())
1119 visitTemplateParams(N, *Params);
1120
1121 if (auto *D = N.getRawDiscriminator()) {
1122 AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,do { if (!(isa<DIDerivedType>(D) && N.getTag() ==
dwarf::DW_TAG_variant_part)) { DebugInfoCheckFailed("discriminator can only appear on variant part"
); return; } } while (false)
1123 "discriminator can only appear on variant part")do { if (!(isa<DIDerivedType>(D) && N.getTag() ==
dwarf::DW_TAG_variant_part)) { DebugInfoCheckFailed("discriminator can only appear on variant part"
); return; } } while (false)
;
1124 }
1125
1126 if (N.getRawDataLocation()) {
1127 AssertDI(N.getTag() == dwarf::DW_TAG_array_type,do { if (!(N.getTag() == dwarf::DW_TAG_array_type)) { DebugInfoCheckFailed
("dataLocation can only appear in array type"); return; } } while
(false)
1128 "dataLocation can only appear in array type")do { if (!(N.getTag() == dwarf::DW_TAG_array_type)) { DebugInfoCheckFailed
("dataLocation can only appear in array type"); return; } } while
(false)
;
1129 }
1130
1131 if (N.getRawAssociated()) {
1132 AssertDI(N.getTag() == dwarf::DW_TAG_array_type,do { if (!(N.getTag() == dwarf::DW_TAG_array_type)) { DebugInfoCheckFailed
("associated can only appear in array type"); return; } } while
(false)
1133 "associated can only appear in array type")do { if (!(N.getTag() == dwarf::DW_TAG_array_type)) { DebugInfoCheckFailed
("associated can only appear in array type"); return; } } while
(false)
;
1134 }
1135
1136 if (N.getRawAllocated()) {
1137 AssertDI(N.getTag() == dwarf::DW_TAG_array_type,do { if (!(N.getTag() == dwarf::DW_TAG_array_type)) { DebugInfoCheckFailed
("allocated can only appear in array type"); return; } } while
(false)
1138 "allocated can only appear in array type")do { if (!(N.getTag() == dwarf::DW_TAG_array_type)) { DebugInfoCheckFailed
("allocated can only appear in array type"); return; } } while
(false)
;
1139 }
1140
1141 if (N.getRawRank()) {
1142 AssertDI(N.getTag() == dwarf::DW_TAG_array_type,do { if (!(N.getTag() == dwarf::DW_TAG_array_type)) { DebugInfoCheckFailed
("rank can only appear in array type"); return; } } while (false
)
1143 "rank can only appear in array type")do { if (!(N.getTag() == dwarf::DW_TAG_array_type)) { DebugInfoCheckFailed
("rank can only appear in array type"); return; } } while (false
)
;
1144 }
1145}
1146
1147void Verifier::visitDISubroutineType(const DISubroutineType &N) {
1148 AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_subroutine_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1149 if (auto *Types = N.getRawTypeArray()) {
1150 AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types)do { if (!(isa<MDTuple>(Types))) { DebugInfoCheckFailed
("invalid composite elements", &N, Types); return; } } while
(false)
;
1151 for (Metadata *Ty : N.getTypeArray()->operands()) {
1152 AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty)do { if (!(isType(Ty))) { DebugInfoCheckFailed("invalid subroutine type ref"
, &N, Types, Ty); return; } } while (false)
;
1153 }
1154 }
1155 AssertDI(!hasConflictingReferenceFlags(N.getFlags()),do { if (!(!hasConflictingReferenceFlags(N.getFlags()))) { DebugInfoCheckFailed
("invalid reference flags", &N); return; } } while (false
)
1156 "invalid reference flags", &N)do { if (!(!hasConflictingReferenceFlags(N.getFlags()))) { DebugInfoCheckFailed
("invalid reference flags", &N); return; } } while (false
)
;
1157}
1158
1159void Verifier::visitDIFile(const DIFile &N) {
1160 AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_file_type)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1161 Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1162 if (Checksum) {
1163 AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,do { if (!(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last
)) { DebugInfoCheckFailed("invalid checksum kind", &N); return
; } } while (false)
1164 "invalid checksum kind", &N)do { if (!(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last
)) { DebugInfoCheckFailed("invalid checksum kind", &N); return
; } } while (false)
;
1165 size_t Size;
1166 switch (Checksum->Kind) {
1167 case DIFile::CSK_MD5:
1168 Size = 32;
1169 break;
1170 case DIFile::CSK_SHA1:
1171 Size = 40;
1172 break;
1173 case DIFile::CSK_SHA256:
1174 Size = 64;
1175 break;
1176 }
1177 AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N)do { if (!(Checksum->Value.size() == Size)) { DebugInfoCheckFailed
("invalid checksum length", &N); return; } } while (false
)
;
1178 AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,do { if (!(Checksum->Value.find_if_not(llvm::isHexDigit) ==
StringRef::npos)) { DebugInfoCheckFailed("invalid checksum",
&N); return; } } while (false)
1179 "invalid checksum", &N)do { if (!(Checksum->Value.find_if_not(llvm::isHexDigit) ==
StringRef::npos)) { DebugInfoCheckFailed("invalid checksum",
&N); return; } } while (false)
;
1180 }
1181}
1182
1183void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1184 AssertDI(N.isDistinct(), "compile units must be distinct", &N)do { if (!(N.isDistinct())) { DebugInfoCheckFailed("compile units must be distinct"
, &N); return; } } while (false)
;
1185 AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_compile_unit)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1186
1187 // Don't bother verifying the compilation directory or producer string
1188 // as those could be empty.
1189 AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,do { if (!(N.getRawFile() && isa<DIFile>(N.getRawFile
()))) { DebugInfoCheckFailed("invalid file", &N, N.getRawFile
()); return; } } while (false)
1190 N.getRawFile())do { if (!(N.getRawFile() && isa<DIFile>(N.getRawFile
()))) { DebugInfoCheckFailed("invalid file", &N, N.getRawFile
()); return; } } while (false)
;
1191 AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,do { if (!(!N.getFile()->getFilename().empty())) { DebugInfoCheckFailed
("invalid filename", &N, N.getFile()); return; } } while (
false)
1192 N.getFile())do { if (!(!N.getFile()->getFilename().empty())) { DebugInfoCheckFailed
("invalid filename", &N, N.getFile()); return; } } while (
false)
;
1193
1194 CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
1195
1196 verifySourceDebugInfo(N, *N.getFile());
1197
1198 AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),do { if (!((N.getEmissionKind() <= DICompileUnit::LastEmissionKind
))) { DebugInfoCheckFailed("invalid emission kind", &N); return
; } } while (false)
1199 "invalid emission kind", &N)do { if (!((N.getEmissionKind() <= DICompileUnit::LastEmissionKind
))) { DebugInfoCheckFailed("invalid emission kind", &N); return
; } } while (false)
;
1200
1201 if (auto *Array = N.getRawEnumTypes()) {
1202 AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array)do { if (!(isa<MDTuple>(Array))) { DebugInfoCheckFailed
("invalid enum list", &N, Array); return; } } while (false
)
;
1203 for (Metadata *Op : N.getEnumTypes()->operands()) {
1204 auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
1205 AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,do { if (!(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
)) { DebugInfoCheckFailed("invalid enum type", &N, N.getEnumTypes
(), Op); return; } } while (false)
1206 "invalid enum type", &N, N.getEnumTypes(), Op)do { if (!(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type
)) { DebugInfoCheckFailed("invalid enum type", &N, N.getEnumTypes
(), Op); return; } } while (false)
;
1207 }
1208 }
1209 if (auto *Array = N.getRawRetainedTypes()) {
1210 AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array)do { if (!(isa<MDTuple>(Array))) { DebugInfoCheckFailed
("invalid retained type list", &N, Array); return; } } while
(false)
;
1211 for (Metadata *Op : N.getRetainedTypes()->operands()) {
1212 AssertDI(Op && (isa<DIType>(Op) ||do { if (!(Op && (isa<DIType>(Op) || (isa<DISubprogram
>(Op) && !cast<DISubprogram>(Op)->isDefinition
())))) { DebugInfoCheckFailed("invalid retained type", &N
, Op); return; } } while (false)
1213 (isa<DISubprogram>(Op) &&do { if (!(Op && (isa<DIType>(Op) || (isa<DISubprogram
>(Op) && !cast<DISubprogram>(Op)->isDefinition
())))) { DebugInfoCheckFailed("invalid retained type", &N
, Op); return; } } while (false)
1214 !cast<DISubprogram>(Op)->isDefinition())),do { if (!(Op && (isa<DIType>(Op) || (isa<DISubprogram
>(Op) && !cast<DISubprogram>(Op)->isDefinition
())))) { DebugInfoCheckFailed("invalid retained type", &N
, Op); return; } } while (false)
1215 "invalid retained type", &N, Op)do { if (!(Op && (isa<DIType>(Op) || (isa<DISubprogram
>(Op) && !cast<DISubprogram>(Op)->isDefinition
())))) { DebugInfoCheckFailed("invalid retained type", &N
, Op); return; } } while (false)
;
1216 }
1217 }
1218 if (auto *Array = N.getRawGlobalVariables()) {
1219 AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array)do { if (!(isa<MDTuple>(Array))) { DebugInfoCheckFailed
("invalid global variable list", &N, Array); return; } } while
(false)
;
1220 for (Metadata *Op : N.getGlobalVariables()->operands()) {
1221 AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)),do { if (!(Op && (isa<DIGlobalVariableExpression>
(Op)))) { DebugInfoCheckFailed("invalid global variable ref",
&N, Op); return; } } while (false)
1222 "invalid global variable ref", &N, Op)do { if (!(Op && (isa<DIGlobalVariableExpression>
(Op)))) { DebugInfoCheckFailed("invalid global variable ref",
&N, Op); return; } } while (false)
;
1223 }
1224 }
1225 if (auto *Array = N.getRawImportedEntities()) {
1226 AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array)do { if (!(isa<MDTuple>(Array))) { DebugInfoCheckFailed
("invalid imported entity list", &N, Array); return; } } while
(false)
;
1227 for (Metadata *Op : N.getImportedEntities()->operands()) {
1228 AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",do { if (!(Op && isa<DIImportedEntity>(Op))) { DebugInfoCheckFailed
("invalid imported entity ref", &N, Op); return; } } while
(false)
1229 &N, Op)do { if (!(Op && isa<DIImportedEntity>(Op))) { DebugInfoCheckFailed
("invalid imported entity ref", &N, Op); return; } } while
(false)
;
1230 }
1231 }
1232 if (auto *Array = N.getRawMacros()) {
1233 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array)do { if (!(isa<MDTuple>(Array))) { DebugInfoCheckFailed
("invalid macro list", &N, Array); return; } } while (false
)
;
1234 for (Metadata *Op : N.getMacros()->operands()) {
1235 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op)do { if (!(Op && isa<DIMacroNode>(Op))) { DebugInfoCheckFailed
("invalid macro ref", &N, Op); return; } } while (false)
;
1236 }
1237 }
1238 CUVisited.insert(&N);
1239}
1240
1241void Verifier::visitDISubprogram(const DISubprogram &N) {
1242 AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_subprogram)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1243 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope())do { if (!(isScope(N.getRawScope()))) { DebugInfoCheckFailed(
"invalid scope", &N, N.getRawScope()); return; } } while (
false)
;
1244 if (auto *F = N.getRawFile())
1245 AssertDI(isa<DIFile>(F), "invalid file", &N, F)do { if (!(isa<DIFile>(F))) { DebugInfoCheckFailed("invalid file"
, &N, F); return; } } while (false)
;
1246 else
1247 AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine())do { if (!(N.getLine() == 0)) { DebugInfoCheckFailed("line specified with no file"
, &N, N.getLine()); return; } } while (false)
;
1248 if (auto *T = N.getRawType())
1249 AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T)do { if (!(isa<DISubroutineType>(T))) { DebugInfoCheckFailed
("invalid subroutine type", &N, T); return; } } while (false
)
;
1250 AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,do { if (!(isType(N.getRawContainingType()))) { DebugInfoCheckFailed
("invalid containing type", &N, N.getRawContainingType())
; return; } } while (false)
1251 N.getRawContainingType())do { if (!(isType(N.getRawContainingType()))) { DebugInfoCheckFailed
("invalid containing type", &N, N.getRawContainingType())
; return; } } while (false)
;
1252 if (auto *Params = N.getRawTemplateParams())
1253 visitTemplateParams(N, *Params);
1254 if (auto *S = N.getRawDeclaration())
1255 AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),do { if (!(isa<DISubprogram>(S) && !cast<DISubprogram
>(S)->isDefinition())) { DebugInfoCheckFailed("invalid subprogram declaration"
, &N, S); return; } } while (false)
1256 "invalid subprogram declaration", &N, S)do { if (!(isa<DISubprogram>(S) && !cast<DISubprogram
>(S)->isDefinition())) { DebugInfoCheckFailed("invalid subprogram declaration"
, &N, S); return; } } while (false)
;
1257 if (auto *RawNode = N.getRawRetainedNodes()) {
1258 auto *Node = dyn_cast<MDTuple>(RawNode);
1259 AssertDI(Node, "invalid retained nodes list", &N, RawNode)do { if (!(Node)) { DebugInfoCheckFailed("invalid retained nodes list"
, &N, RawNode); return; } } while (false)
;
1260 for (Metadata *Op : Node->operands()) {
1261 AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),do { if (!(Op && (isa<DILocalVariable>(Op) || isa
<DILabel>(Op)))) { DebugInfoCheckFailed("invalid retained nodes, expected DILocalVariable or DILabel"
, &N, Node, Op); return; } } while (false)
1262 "invalid retained nodes, expected DILocalVariable or DILabel",do { if (!(Op && (isa<DILocalVariable>(Op) || isa
<DILabel>(Op)))) { DebugInfoCheckFailed("invalid retained nodes, expected DILocalVariable or DILabel"
, &N, Node, Op); return; } } while (false)
1263 &N, Node, Op)do { if (!(Op && (isa<DILocalVariable>(Op) || isa
<DILabel>(Op)))) { DebugInfoCheckFailed("invalid retained nodes, expected DILocalVariable or DILabel"
, &N, Node, Op); return; } } while (false)
;
1264 }
1265 }
1266 AssertDI(!hasConflictingReferenceFlags(N.getFlags()),do { if (!(!hasConflictingReferenceFlags(N.getFlags()))) { DebugInfoCheckFailed
("invalid reference flags", &N); return; } } while (false
)
1267 "invalid reference flags", &N)do { if (!(!hasConflictingReferenceFlags(N.getFlags()))) { DebugInfoCheckFailed
("invalid reference flags", &N); return; } } while (false
)
;
1268
1269 auto *Unit = N.getRawUnit();
1270 if (N.isDefinition()) {
1271 // Subprogram definitions (not part of the type hierarchy).
1272 AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N)do { if (!(N.isDistinct())) { DebugInfoCheckFailed("subprogram definitions must be distinct"
, &N); return; } } while (false)
;
1273 AssertDI(Unit, "subprogram definitions must have a compile unit", &N)do { if (!(Unit)) { DebugInfoCheckFailed("subprogram definitions must have a compile unit"
, &N); return; } } while (false)
;
1274 AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit)do { if (!(isa<DICompileUnit>(Unit))) { DebugInfoCheckFailed
("invalid unit type", &N, Unit); return; } } while (false
)
;
1275 if (N.getFile())
1276 verifySourceDebugInfo(*N.getUnit(), *N.getFile());
1277 } else {
1278 // Subprogram declarations (part of the type hierarchy).
1279 AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N)do { if (!(!Unit)) { DebugInfoCheckFailed("subprogram declarations must not have a compile unit"
, &N); return; } } while (false)
;
1280 }
1281
1282 if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1283 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1284 AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes)do { if (!(ThrownTypes)) { DebugInfoCheckFailed("invalid thrown types list"
, &N, RawThrownTypes); return; } } while (false)
;
1285 for (Metadata *Op : ThrownTypes->operands())
1286 AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,do { if (!(Op && isa<DIType>(Op))) { DebugInfoCheckFailed
("invalid thrown type", &N, ThrownTypes, Op); return; } }
while (false)
1287 Op)do { if (!(Op && isa<DIType>(Op))) { DebugInfoCheckFailed
("invalid thrown type", &N, ThrownTypes, Op); return; } }
while (false)
;
1288 }
1289
1290 if (N.areAllCallsDescribed())
1291 AssertDI(N.isDefinition(),do { if (!(N.isDefinition())) { DebugInfoCheckFailed("DIFlagAllCallsDescribed must be attached to a definition"
); return; } } while (false)
1292 "DIFlagAllCallsDescribed must be attached to a definition")do { if (!(N.isDefinition())) { DebugInfoCheckFailed("DIFlagAllCallsDescribed must be attached to a definition"
); return; } } while (false)
;
1293}
1294
1295void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1296 AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_lexical_block)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1297 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),do { if (!(N.getRawScope() && isa<DILocalScope>
(N.getRawScope()))) { DebugInfoCheckFailed("invalid local scope"
, &N, N.getRawScope()); return; } } while (false)
1298 "invalid local scope", &N, N.getRawScope())do { if (!(N.getRawScope() && isa<DILocalScope>
(N.getRawScope()))) { DebugInfoCheckFailed("invalid local scope"
, &N, N.getRawScope()); return; } } while (false)
;
1299 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1300 AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N)do { if (!(SP->isDefinition())) { DebugInfoCheckFailed("scope points into the type hierarchy"
, &N); return; } } while (false)
;
1301}
1302
1303void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1304 visitDILexicalBlockBase(N);
1305
1306 AssertDI(N.getLine() || !N.getColumn(),do { if (!(N.getLine() || !N.getColumn())) { DebugInfoCheckFailed
("cannot have column info without line info", &N); return
; } } while (false)
1307 "cannot have column info without line info", &N)do { if (!(N.getLine() || !N.getColumn())) { DebugInfoCheckFailed
("cannot have column info without line info", &N); return
; } } while (false)
;
1308}
1309
1310void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1311 visitDILexicalBlockBase(N);
1312}
1313
1314void Verifier::visitDICommonBlock(const DICommonBlock &N) {
1315 AssertDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_common_block)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1316 if (auto *S = N.getRawScope())
1317 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S)do { if (!(isa<DIScope>(S))) { DebugInfoCheckFailed("invalid scope ref"
, &N, S); return; } } while (false)
;
1318 if (auto *S = N.getRawDecl())
1319 AssertDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S)do { if (!(isa<DIGlobalVariable>(S))) { DebugInfoCheckFailed
("invalid declaration", &N, S); return; } } while (false)
;
1320}
1321
1322void Verifier::visitDINamespace(const DINamespace &N) {
1323 AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_namespace)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1324 if (auto *S = N.getRawScope())
1325 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S)do { if (!(isa<DIScope>(S))) { DebugInfoCheckFailed("invalid scope ref"
, &N, S); return; } } while (false)
;
1326}
1327
1328void Verifier::visitDIMacro(const DIMacro &N) {
1329 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||do { if (!(N.getMacinfoType() == dwarf::DW_MACINFO_define || N
.getMacinfoType() == dwarf::DW_MACINFO_undef)) { DebugInfoCheckFailed
("invalid macinfo type", &N); return; } } while (false)
1330 N.getMacinfoType() == dwarf::DW_MACINFO_undef,do { if (!(N.getMacinfoType() == dwarf::DW_MACINFO_define || N
.getMacinfoType() == dwarf::DW_MACINFO_undef)) { DebugInfoCheckFailed
("invalid macinfo type", &N); return; } } while (false)
1331 "invalid macinfo type", &N)do { if (!(N.getMacinfoType() == dwarf::DW_MACINFO_define || N
.getMacinfoType() == dwarf::DW_MACINFO_undef)) { DebugInfoCheckFailed
("invalid macinfo type", &N); return; } } while (false)
;
1332 AssertDI(!N.getName().empty(), "anonymous macro", &N)do { if (!(!N.getName().empty())) { DebugInfoCheckFailed("anonymous macro"
, &N); return; } } while (false)
;
1333 if (!N.getValue().empty()) {
1334 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix")((void)0);
1335 }
1336}
1337
1338void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1339 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,do { if (!(N.getMacinfoType() == dwarf::DW_MACINFO_start_file
)) { DebugInfoCheckFailed("invalid macinfo type", &N); return
; } } while (false)
1340 "invalid macinfo type", &N)do { if (!(N.getMacinfoType() == dwarf::DW_MACINFO_start_file
)) { DebugInfoCheckFailed("invalid macinfo type", &N); return
; } } while (false)
;
1341 if (auto *F = N.getRawFile())
1342 AssertDI(isa<DIFile>(F), "invalid file", &N, F)do { if (!(isa<DIFile>(F))) { DebugInfoCheckFailed("invalid file"
, &N, F); return; } } while (false)
;
1343
1344 if (auto *Array = N.getRawElements()) {
1345 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array)do { if (!(isa<MDTuple>(Array))) { DebugInfoCheckFailed
("invalid macro list", &N, Array); return; } } while (false
)
;
1346 for (Metadata *Op : N.getElements()->operands()) {
1347 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op)do { if (!(Op && isa<DIMacroNode>(Op))) { DebugInfoCheckFailed
("invalid macro ref", &N, Op); return; } } while (false)
;
1348 }
1349 }
1350}
1351
1352void Verifier::visitDIArgList(const DIArgList &N) {
1353 AssertDI(!N.getNumOperands(),do { if (!(!N.getNumOperands())) { DebugInfoCheckFailed("DIArgList should have no operands other than a list of "
"ValueAsMetadata", &N); return; } } while (false)
1354 "DIArgList should have no operands other than a list of "do { if (!(!N.getNumOperands())) { DebugInfoCheckFailed("DIArgList should have no operands other than a list of "
"ValueAsMetadata", &N); return; } } while (false)
1355 "ValueAsMetadata",do { if (!(!N.getNumOperands())) { DebugInfoCheckFailed("DIArgList should have no operands other than a list of "
"ValueAsMetadata", &N); return; } } while (false)
1356 &N)do { if (!(!N.getNumOperands())) { DebugInfoCheckFailed("DIArgList should have no operands other than a list of "
"ValueAsMetadata", &N); return; } } while (false)
;
1357}
1358
1359void Verifier::visitDIModule(const DIModule &N) {
1360 AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_module)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1361 AssertDI(!N.getName().empty(), "anonymous module", &N)do { if (!(!N.getName().empty())) { DebugInfoCheckFailed("anonymous module"
, &N); return; } } while (false)
;
1362}
1363
1364void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1365 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType())do { if (!(isType(N.getRawType()))) { DebugInfoCheckFailed("invalid type ref"
, &N, N.getRawType()); return; } } while (false)
;
1366}
1367
1368void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1369 visitDITemplateParameter(N);
1370
1371 AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",do { if (!(N.getTag() == dwarf::DW_TAG_template_type_parameter
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
1372 &N)do { if (!(N.getTag() == dwarf::DW_TAG_template_type_parameter
)) { DebugInfoCheckFailed("invalid tag", &N); return; } }
while (false)
;
1373}
1374
1375void Verifier::visitDITemplateValueParameter(
1376 const DITemplateValueParameter &N) {
1377 visitDITemplateParameter(N);
1378
1379 AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||do { if (!(N.getTag() == dwarf::DW_TAG_template_value_parameter
|| N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1380 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||do { if (!(N.getTag() == dwarf::DW_TAG_template_value_parameter
|| N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1381 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,do { if (!(N.getTag() == dwarf::DW_TAG_template_value_parameter
|| N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1382 "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_template_value_parameter
|| N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1383}
1384
1385void Verifier::visitDIVariable(const DIVariable &N) {
1386 if (auto *S = N.getRawScope())
1387 AssertDI(isa<DIScope>(S), "invalid scope", &N, S)do { if (!(isa<DIScope>(S))) { DebugInfoCheckFailed("invalid scope"
, &N, S); return; } } while (false)
;
1388 if (auto *F = N.getRawFile())
1389 AssertDI(isa<DIFile>(F), "invalid file", &N, F)do { if (!(isa<DIFile>(F))) { DebugInfoCheckFailed("invalid file"
, &N, F); return; } } while (false)
;
1390}
1391
1392void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1393 // Checks common to all variables.
1394 visitDIVariable(N);
1395
1396 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_variable)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1397 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType())do { if (!(isType(N.getRawType()))) { DebugInfoCheckFailed("invalid type ref"
, &N, N.getRawType()); return; } } while (false)
;
1398 // Assert only if the global variable is not an extern
1399 if (N.isDefinition())
1400 AssertDI(N.getType(), "missing global variable type", &N)do { if (!(N.getType())) { DebugInfoCheckFailed("missing global variable type"
, &N); return; } } while (false)
;
1401 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1402 AssertDI(isa<DIDerivedType>(Member),do { if (!(isa<DIDerivedType>(Member))) { DebugInfoCheckFailed
("invalid static data member declaration", &N, Member); return
; } } while (false)
1403 "invalid static data member declaration", &N, Member)do { if (!(isa<DIDerivedType>(Member))) { DebugInfoCheckFailed
("invalid static data member declaration", &N, Member); return
; } } while (false)
;
1404 }
1405}
1406
1407void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1408 // Checks common to all variables.
1409 visitDIVariable(N);
1410
1411 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType())do { if (!(isType(N.getRawType()))) { DebugInfoCheckFailed("invalid type ref"
, &N, N.getRawType()); return; } } while (false)
;
1412 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_variable)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1413 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),do { if (!(N.getRawScope() && isa<DILocalScope>
(N.getRawScope()))) { DebugInfoCheckFailed("local variable requires a valid scope"
, &N, N.getRawScope()); return; } } while (false)
1414 "local variable requires a valid scope", &N, N.getRawScope())do { if (!(N.getRawScope() && isa<DILocalScope>
(N.getRawScope()))) { DebugInfoCheckFailed("local variable requires a valid scope"
, &N, N.getRawScope()); return; } } while (false)
;
1415 if (auto Ty = N.getType())
1416 AssertDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType())do { if (!(!isa<DISubroutineType>(Ty))) { DebugInfoCheckFailed
("invalid type", &N, N.getType()); return; } } while (false
)
;
1417}
1418
1419void Verifier::visitDILabel(const DILabel &N) {
1420 if (auto *S = N.getRawScope())
1421 AssertDI(isa<DIScope>(S), "invalid scope", &N, S)do { if (!(isa<DIScope>(S))) { DebugInfoCheckFailed("invalid scope"
, &N, S); return; } } while (false)
;
1422 if (auto *F = N.getRawFile())
1423 AssertDI(isa<DIFile>(F), "invalid file", &N, F)do { if (!(isa<DIFile>(F))) { DebugInfoCheckFailed("invalid file"
, &N, F); return; } } while (false)
;
1424
1425 AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_label)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1426 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),do { if (!(N.getRawScope() && isa<DILocalScope>
(N.getRawScope()))) { DebugInfoCheckFailed("label requires a valid scope"
, &N, N.getRawScope()); return; } } while (false)
1427 "label requires a valid scope", &N, N.getRawScope())do { if (!(N.getRawScope() && isa<DILocalScope>
(N.getRawScope()))) { DebugInfoCheckFailed("label requires a valid scope"
, &N, N.getRawScope()); return; } } while (false)
;
1428}
1429
1430void Verifier::visitDIExpression(const DIExpression &N) {
1431 AssertDI(N.isValid(), "invalid expression", &N)do { if (!(N.isValid())) { DebugInfoCheckFailed("invalid expression"
, &N); return; } } while (false)
;
1432}
1433
1434void Verifier::visitDIGlobalVariableExpression(
1435 const DIGlobalVariableExpression &GVE) {
1436 AssertDI(GVE.getVariable(), "missing variable")do { if (!(GVE.getVariable())) { DebugInfoCheckFailed("missing variable"
); return; } } while (false)
;
1437 if (auto *Var = GVE.getVariable())
1438 visitDIGlobalVariable(*Var);
1439 if (auto *Expr = GVE.getExpression()) {
1440 visitDIExpression(*Expr);
1441 if (auto Fragment = Expr->getFragmentInfo())
1442 verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1443 }
1444}
1445
1446void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1447 AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_APPLE_property)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1448 if (auto *T = N.getRawType())
1449 AssertDI(isType(T), "invalid type ref", &N, T)do { if (!(isType(T))) { DebugInfoCheckFailed("invalid type ref"
, &N, T); return; } } while (false)
;
1450 if (auto *F = N.getRawFile())
1451 AssertDI(isa<DIFile>(F), "invalid file", &N, F)do { if (!(isa<DIFile>(F))) { DebugInfoCheckFailed("invalid file"
, &N, F); return; } } while (false)
;
1452}
1453
1454void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1455 AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||do { if (!(N.getTag() == dwarf::DW_TAG_imported_module || N.getTag
() == dwarf::DW_TAG_imported_declaration)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1456 N.getTag() == dwarf::DW_TAG_imported_declaration,do { if (!(N.getTag() == dwarf::DW_TAG_imported_module || N.getTag
() == dwarf::DW_TAG_imported_declaration)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
1457 "invalid tag", &N)do { if (!(N.getTag() == dwarf::DW_TAG_imported_module || N.getTag
() == dwarf::DW_TAG_imported_declaration)) { DebugInfoCheckFailed
("invalid tag", &N); return; } } while (false)
;
1458 if (auto *S = N.getRawScope())
1459 AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S)do { if (!(isa<DIScope>(S))) { DebugInfoCheckFailed("invalid scope for imported entity"
, &N, S); return; } } while (false)
;
1460 AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,do { if (!(isDINode(N.getRawEntity()))) { DebugInfoCheckFailed
("invalid imported entity", &N, N.getRawEntity()); return
; } } while (false)
1461 N.getRawEntity())do { if (!(isDINode(N.getRawEntity()))) { DebugInfoCheckFailed
("invalid imported entity", &N, N.getRawEntity()); return
; } } while (false)
;
1462}
1463
1464void Verifier::visitComdat(const Comdat &C) {
1465 // In COFF the Module is invalid if the GlobalValue has private linkage.
1466 // Entities with private linkage don't have entries in the symbol table.
1467 if (TT.isOSBinFormatCOFF())
1468 if (const GlobalValue *GV = M.getNamedValue(C.getName()))
1469 Assert(!GV->hasPrivateLinkage(),do { if (!(!GV->hasPrivateLinkage())) { CheckFailed("comdat global value has private linkage"
, GV); return; } } while (false)
1470 "comdat global value has private linkage", GV)do { if (!(!GV->hasPrivateLinkage())) { CheckFailed("comdat global value has private linkage"
, GV); return; } } while (false)
;
1471}
1472
1473void Verifier::visitModuleIdents(const Module &M) {
1474 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1475 if (!Idents)
1476 return;
1477
1478 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1479 // Scan each llvm.ident entry and make sure that this requirement is met.
1480 for (const MDNode *N : Idents->operands()) {
1481 Assert(N->getNumOperands() == 1,do { if (!(N->getNumOperands() == 1)) { CheckFailed("incorrect number of operands in llvm.ident metadata"
, N); return; } } while (false)
1482 "incorrect number of operands in llvm.ident metadata", N)do { if (!(N->getNumOperands() == 1)) { CheckFailed("incorrect number of operands in llvm.ident metadata"
, N); return; } } while (false)
;
1483 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),do { if (!(dyn_cast_or_null<MDString>(N->getOperand(
0)))) { CheckFailed(("invalid value for llvm.ident metadata entry operand"
"(the operand should be a string)"), N->getOperand(0)); return
; } } while (false)
1484 ("invalid value for llvm.ident metadata entry operand"do { if (!(dyn_cast_or_null<MDString>(N->getOperand(
0)))) { CheckFailed(("invalid value for llvm.ident metadata entry operand"
"(the operand should be a string)"), N->getOperand(0)); return
; } } while (false)
1485 "(the operand should be a string)"),do { if (!(dyn_cast_or_null<MDString>(N->getOperand(
0)))) { CheckFailed(("invalid value for llvm.ident metadata entry operand"
"(the operand should be a string)"), N->getOperand(0)); return
; } } while (false)
1486 N->getOperand(0))do { if (!(dyn_cast_or_null<MDString>(N->getOperand(
0)))) { CheckFailed(("invalid value for llvm.ident metadata entry operand"
"(the operand should be a string)"), N->getOperand(0)); return
; } } while (false)
;
1487 }
1488}
1489
1490void Verifier::visitModuleCommandLines(const Module &M) {
1491 const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
1492 if (!CommandLines)
1493 return;
1494
1495 // llvm.commandline takes a list of metadata entry. Each entry has only one
1496 // string. Scan each llvm.commandline entry and make sure that this
1497 // requirement is met.
1498 for (const MDNode *N : CommandLines->operands()) {
1499 Assert(N->getNumOperands() == 1,do { if (!(N->getNumOperands() == 1)) { CheckFailed("incorrect number of operands in llvm.commandline metadata"
, N); return; } } while (false)
1500 "incorrect number of operands in llvm.commandline metadata", N)do { if (!(N->getNumOperands() == 1)) { CheckFailed("incorrect number of operands in llvm.commandline metadata"
, N); return; } } while (false)
;
1501 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),do { if (!(dyn_cast_or_null<MDString>(N->getOperand(
0)))) { CheckFailed(("invalid value for llvm.commandline metadata entry operand"
"(the operand should be a string)"), N->getOperand(0)); return
; } } while (false)
1502 ("invalid value for llvm.commandline metadata entry operand"do { if (!(dyn_cast_or_null<MDString>(N->getOperand(
0)))) { CheckFailed(("invalid value for llvm.commandline metadata entry operand"
"(the operand should be a string)"), N->getOperand(0)); return
; } } while (false)
1503 "(the operand should be a string)"),do { if (!(dyn_cast_or_null<MDString>(N->getOperand(
0)))) { CheckFailed(("invalid value for llvm.commandline metadata entry operand"
"(the operand should be a string)"), N->getOperand(0)); return
; } } while (false)
1504 N->getOperand(0))do { if (!(dyn_cast_or_null<MDString>(N->getOperand(
0)))) { CheckFailed(("invalid value for llvm.commandline metadata entry operand"
"(the operand should be a string)"), N->getOperand(0)); return
; } } while (false)
;
1505 }
1506}
1507
1508void Verifier::visitModuleFlags(const Module &M) {
1509 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1510 if (!Flags) return;
1511
1512 // Scan each flag, and track the flags and requirements.
1513 DenseMap<const MDString*, const MDNode*> SeenIDs;
1514 SmallVector<const MDNode*, 16> Requirements;
1515 for (const MDNode *MDN : Flags->operands())
1516 visitModuleFlag(MDN, SeenIDs, Requirements);
1517
1518 // Validate that the requirements in the module are valid.
1519 for (const MDNode *Requirement : Requirements) {
1520 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1521 const Metadata *ReqValue = Requirement->getOperand(1);
1522
1523 const MDNode *Op = SeenIDs.lookup(Flag);
1524 if (!Op) {
1525 CheckFailed("invalid requirement on flag, flag is not present in module",
1526 Flag);
1527 continue;
1528 }
1529
1530 if (Op->getOperand(2) != ReqValue) {
1531 CheckFailed(("invalid requirement on flag, "
1532 "flag does not have the required value"),
1533 Flag);
1534 continue;
1535 }
1536 }
1537}
1538
1539void
1540Verifier::visitModuleFlag(const MDNode *Op,
1541 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1542 SmallVectorImpl<const MDNode *> &Requirements) {
1543 // Each module flag should have three arguments, the merge behavior (a
1544 // constant int), the flag ID (an MDString), and the value.
1545 Assert(Op->getNumOperands() == 3,do { if (!(Op->getNumOperands() == 3)) { CheckFailed("incorrect number of operands in module flag"
, Op); return; } } while (false)
1546 "incorrect number of operands in module flag", Op)do { if (!(Op->getNumOperands() == 3)) { CheckFailed("incorrect number of operands in module flag"
, Op); return; } } while (false)
;
1547 Module::ModFlagBehavior MFB;
1548 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1549 Assert(do { if (!(mdconst::dyn_extract_or_null<ConstantInt>(Op
->getOperand(0)))) { CheckFailed("invalid behavior operand in module flag (expected constant integer)"
, Op->getOperand(0)); return; } } while (false)
1550 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),do { if (!(mdconst::dyn_extract_or_null<ConstantInt>(Op
->getOperand(0)))) { CheckFailed("invalid behavior operand in module flag (expected constant integer)"
, Op->getOperand(0)); return; } } while (false)
1551 "invalid behavior operand in module flag (expected constant integer)",do { if (!(mdconst::dyn_extract_or_null<ConstantInt>(Op
->getOperand(0)))) { CheckFailed("invalid behavior operand in module flag (expected constant integer)"
, Op->getOperand(0)); return; } } while (false)
1552 Op->getOperand(0))do { if (!(mdconst::dyn_extract_or_null<ConstantInt>(Op
->getOperand(0)))) { CheckFailed("invalid behavior operand in module flag (expected constant integer)"
, Op->getOperand(0)); return; } } while (false)
;
1553 Assert(false,do { if (!(false)) { CheckFailed("invalid behavior operand in module flag (unexpected constant)"
, Op->getOperand(0)); return; } } while (false)
1554 "invalid behavior operand in module flag (unexpected constant)",do { if (!(false)) { CheckFailed("invalid behavior operand in module flag (unexpected constant)"
, Op->getOperand(0)); return; } } while (false)
1555 Op->getOperand(0))do { if (!(false)) { CheckFailed("invalid behavior operand in module flag (unexpected constant)"
, Op->getOperand(0)); return; } } while (false)
;
1556 }
1557 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1558 Assert(ID, "invalid ID operand in module flag (expected metadata string)",do { if (!(ID)) { CheckFailed("invalid ID operand in module flag (expected metadata string)"
, Op->getOperand(1)); return; } } while (false)
1559 Op->getOperand(1))do { if (!(ID)) { CheckFailed("invalid ID operand in module flag (expected metadata string)"
, Op->getOperand(1)); return; } } while (false)
;
1560
1561 // Sanity check the values for behaviors with additional requirements.
1562 switch (MFB) {
1563 case Module::Error:
1564 case Module::Warning:
1565 case Module::Override:
1566 // These behavior types accept any value.
1567 break;
1568
1569 case Module::Max: {
1570 Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),do { if (!(mdconst::dyn_extract_or_null<ConstantInt>(Op
->getOperand(2)))) { CheckFailed("invalid value for 'max' module flag (expected constant integer)"
, Op->getOperand(2)); return; } } while (false)
1571 "invalid value for 'max' module flag (expected constant integer)",do { if (!(mdconst::dyn_extract_or_null<ConstantInt>(Op
->getOperand(2)))) { CheckFailed("invalid value for 'max' module flag (expected constant integer)"
, Op->getOperand(2)); return; } } while (false)
1572 Op->getOperand(2))do { if (!(mdconst::dyn_extract_or_null<ConstantInt>(Op
->getOperand(2)))) { CheckFailed("invalid value for 'max' module flag (expected constant integer)"
, Op->getOperand(2)); return; } } while (false)
;
1573 break;
1574 }
1575
1576 case Module::Require: {
1577 // The value should itself be an MDNode with two operands, a flag ID (an
1578 // MDString), and a value.
1579 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1580 Assert(Value && Value->getNumOperands() == 2,do { if (!(Value && Value->getNumOperands() == 2))
{ CheckFailed("invalid value for 'require' module flag (expected metadata pair)"
, Op->getOperand(2)); return; } } while (false)
1581 "invalid value for 'require' module flag (expected metadata pair)",do { if (!(Value && Value->getNumOperands() == 2))
{ CheckFailed("invalid value for 'require' module flag (expected metadata pair)"
, Op->getOperand(2)); return; } } while (false)
1582 Op->getOperand(2))do { if (!(Value && Value->getNumOperands() == 2))
{ CheckFailed("invalid value for 'require' module flag (expected metadata pair)"
, Op->getOperand(2)); return; } } while (false)
;
1583 Assert(isa<MDString>(Value->getOperand(0)),do { if (!(isa<MDString>(Value->getOperand(0)))) { CheckFailed
(("invalid value for 'require' module flag " "(first value operand should be a string)"
), Value->getOperand(0)); return; } } while (false)
1584 ("invalid value for 'require' module flag "do { if (!(isa<MDString>(Value->getOperand(0)))) { CheckFailed
(("invalid value for 'require' module flag " "(first value operand should be a string)"
), Value->getOperand(0)); return; } } while (false)
1585 "(first value operand should be a string)"),do { if (!(isa<MDString>(Value->getOperand(0)))) { CheckFailed
(("invalid value for 'require' module flag " "(first value operand should be a string)"
), Value->getOperand(0)); return; } } while (false)
1586 Value->getOperand(0))do { if (!(isa<MDString>(Value->getOperand(0)))) { CheckFailed
(("invalid value for 'require' module flag " "(first value operand should be a string)"
), Value->getOperand(0)); return; } } while (false)
;
1587
1588 // Append it to the list of requirements, to check once all module flags are
1589 // scanned.
1590 Requirements.push_back(Value);
1591 break;
1592 }
1593
1594 case Module::Append:
1595 case Module::AppendUnique: {
1596 // These behavior types require the operand be an MDNode.
1597 Assert(isa<MDNode>(Op->getOperand(2)),do { if (!(isa<MDNode>(Op->getOperand(2)))) { CheckFailed
("invalid value for 'append'-type module flag " "(expected a metadata node)"
, Op->getOperand(2)); return; } } while (false)
1598 "invalid value for 'append'-type module flag "do { if (!(isa<MDNode>(Op->getOperand(2)))) { CheckFailed
("invalid value for 'append'-type module flag " "(expected a metadata node)"
, Op->getOperand(2)); return; } } while (false)
1599 "(expected a metadata node)",do { if (!(isa<MDNode>(Op->getOperand(2)))) { CheckFailed
("invalid value for 'append'-type module flag " "(expected a metadata node)"
, Op->getOperand(2)); return; } } while (false)
1600 Op->getOperand(2))do { if (!(isa<MDNode>(Op->getOperand(2)))) { CheckFailed
("invalid value for 'append'-type module flag " "(expected a metadata node)"
, Op->getOperand(2)); return; } } while (false)
;
1601 break;
1602 }
1603 }
1604
1605 // Unless this is a "requires" flag, check the ID is unique.
1606 if (MFB != Module::Require) {
1607 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1608 Assert(Inserted,do { if (!(Inserted)) { CheckFailed("module flag identifiers must be unique (or of 'require' type)"
, ID); return; } } while (false)
1609 "module flag identifiers must be unique (or of 'require' type)", ID)do { if (!(Inserted)) { CheckFailed("module flag identifiers must be unique (or of 'require' type)"
, ID); return; } } while (false)
;
1610 }
1611
1612 if (ID->getString() == "wchar_size") {
1613 ConstantInt *Value
1614 = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1615 Assert(Value, "wchar_size metadata requires constant integer argument")do { if (!(Value)) { CheckFailed("wchar_size metadata requires constant integer argument"
); return; } } while (false)
;
1616 }
1617
1618 if (ID->getString() == "Linker Options") {
1619 // If the llvm.linker.options named metadata exists, we assume that the
1620 // bitcode reader has upgraded the module flag. Otherwise the flag might
1621 // have been created by a client directly.
1622 Assert(M.getNamedMetadata("llvm.linker.options"),do { if (!(M.getNamedMetadata("llvm.linker.options"))) { CheckFailed
("'Linker Options' named metadata no longer supported"); return
; } } while (false)
1623 "'Linker Options' named metadata no longer supported")do { if (!(M.getNamedMetadata("llvm.linker.options"))) { CheckFailed
("'Linker Options' named metadata no longer supported"); return
; } } while (false)
;
1624 }
1625
1626 if (ID->getString() == "SemanticInterposition") {
1627 ConstantInt *Value =
1628 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1629 Assert(Value,do { if (!(Value)) { CheckFailed("SemanticInterposition metadata requires constant integer argument"
); return; } } while (false)
1630 "SemanticInterposition metadata requires constant integer argument")do { if (!(Value)) { CheckFailed("SemanticInterposition metadata requires constant integer argument"
); return; } } while (false)
;
1631 }
1632
1633 if (ID->getString() == "CG Profile") {
1634 for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
1635 visitModuleFlagCGProfileEntry(MDO);
1636 }
1637}
1638
1639void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
1640 auto CheckFunction = [&](const MDOperand &FuncMDO) {
1641 if (!FuncMDO)
1642 return;
1643 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1644 Assert(F && isa<Function>(F->getValue()->stripPointerCasts()),do { if (!(F && isa<Function>(F->getValue()->
stripPointerCasts()))) { CheckFailed("expected a Function or null"
, FuncMDO); return; } } while (false)
1645 "expected a Function or null", FuncMDO)do { if (!(F && isa<Function>(F->getValue()->
stripPointerCasts()))) { CheckFailed("expected a Function or null"
, FuncMDO); return; } } while (false)
;
1646 };
1647 auto Node = dyn_cast_or_null<MDNode>(MDO);
1648 Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO)do { if (!(Node && Node->getNumOperands() == 3)) {
CheckFailed("expected a MDNode triple", MDO); return; } } while
(false)
;
1649 CheckFunction(Node->getOperand(0));
1650 CheckFunction(Node->getOperand(1));
1651 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
1652 Assert(Count && Count->getType()->isIntegerTy(),do { if (!(Count && Count->getType()->isIntegerTy
())) { CheckFailed("expected an integer constant", Node->getOperand
(2)); return; } } while (false)
1653 "expected an integer constant", Node->getOperand(2))do { if (!(Count && Count->getType()->isIntegerTy
())) { CheckFailed("expected an integer constant", Node->getOperand
(2)); return; } } while (false)
;
1654}
1655
1656void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
1657 for (Attribute A : Attrs) {
1658
1659 if (A.isStringAttribute()) {
1660#define GET_ATTR_NAMES
1661#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1662#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
1663 if (A.getKindAsString() == #DISPLAY_NAME) { \
1664 auto V = A.getValueAsString(); \
1665 if (!(V.empty() || V == "true" || V == "false")) \
1666 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
1667 ""); \
1668 }
1669
1670#include "llvm/IR/Attributes.inc"
1671 continue;
1672 }
1673
1674 if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
1675 CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
1676 V);
1677 return;
1678 }
1679 }
1680}
1681
1682// VerifyParameterAttrs - Check the given attributes for an argument or return
1683// value of the specified type. The value V is printed in error messages.
1684void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
1685 const Value *V) {
1686 if (!Attrs.hasAttributes())
1687 return;
1688
1689 verifyAttributeTypes(Attrs, V);
1690
1691 for (Attribute Attr : Attrs)
1692 Assert(Attr.isStringAttribute() ||do { if (!(Attr.isStringAttribute() || Attribute::canUseAsParamAttr
(Attr.getKindAsEnum()))) { CheckFailed("Attribute '" + Attr.getAsString
() + "' does not apply to parameters", V); return; } } while (
false)
1693 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),do { if (!(Attr.isStringAttribute() || Attribute::canUseAsParamAttr
(Attr.getKindAsEnum()))) { CheckFailed("Attribute '" + Attr.getAsString
() + "' does not apply to parameters", V); return; } } while (
false)
1694 "Attribute '" + Attr.getAsString() +do { if (!(Attr.isStringAttribute() || Attribute::canUseAsParamAttr
(Attr.getKindAsEnum()))) { CheckFailed("Attribute '" + Attr.getAsString
() + "' does not apply to parameters", V); return; } } while (
false)
1695 "' does not apply to parameters",do { if (!(Attr.isStringAttribute() || Attribute::canUseAsParamAttr
(Attr.getKindAsEnum()))) { CheckFailed("Attribute '" + Attr.getAsString
() + "' does not apply to parameters", V); return; } } while (
false)
1696 V)do { if (!(Attr.isStringAttribute() || Attribute::canUseAsParamAttr
(Attr.getKindAsEnum()))) { CheckFailed("Attribute '" + Attr.getAsString
() + "' does not apply to parameters", V); return; } } while (
false)
;
1697
1698 if (Attrs.hasAttribute(Attribute::ImmArg)) {
1699 Assert(Attrs.getNumAttributes() == 1,do { if (!(Attrs.getNumAttributes() == 1)) { CheckFailed("Attribute 'immarg' is incompatible with other attributes"
, V); return; } } while (false)
1700 "Attribute 'immarg' is incompatible with other attributes", V)do { if (!(Attrs.getNumAttributes() == 1)) { CheckFailed("Attribute 'immarg' is incompatible with other attributes"
, V); return; } } while (false)
;
1701 }
1702
1703 // Check for mutually incompatible attributes. Only inreg is compatible with
1704 // sret.
1705 unsigned AttrCount = 0;
1706 AttrCount += Attrs.hasAttribute(Attribute::ByVal);
1707 AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
1708 AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
1709 AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
1710 Attrs.hasAttribute(Attribute::InReg);
1711 AttrCount += Attrs.hasAttribute(Attribute::Nest);
1712 AttrCount += Attrs.hasAttribute(Attribute::ByRef);
1713 Assert(AttrCount <= 1,do { if (!(AttrCount <= 1)) { CheckFailed("Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
"'byref', and 'sret' are incompatible!", V); return; } } while
(false)
1714 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "do { if (!(AttrCount <= 1)) { CheckFailed("Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
"'byref', and 'sret' are incompatible!", V); return; } } while
(false)
1715 "'byref', and 'sret' are incompatible!",do { if (!(AttrCount <= 1)) { CheckFailed("Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
"'byref', and 'sret' are incompatible!", V); return; } } while
(false)
1716 V)do { if (!(AttrCount <= 1)) { CheckFailed("Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
"'byref', and 'sret' are incompatible!", V); return; } } while
(false)
;
1717
1718 Assert(!(Attrs.hasAttribute(Attribute::InAlloca) &&do { if (!(!(Attrs.hasAttribute(Attribute::InAlloca) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'inalloca and readonly' are incompatible!", V); return; } }
while (false)
1719 Attrs.hasAttribute(Attribute::ReadOnly)),do { if (!(!(Attrs.hasAttribute(Attribute::InAlloca) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'inalloca and readonly' are incompatible!", V); return; } }
while (false)
1720 "Attributes "do { if (!(!(Attrs.hasAttribute(Attribute::InAlloca) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'inalloca and readonly' are incompatible!", V); return; } }
while (false)
1721 "'inalloca and readonly' are incompatible!",do { if (!(!(Attrs.hasAttribute(Attribute::InAlloca) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'inalloca and readonly' are incompatible!", V); return; } }
while (false)
1722 V)do { if (!(!(Attrs.hasAttribute(Attribute::InAlloca) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'inalloca and readonly' are incompatible!", V); return; } }
while (false)
;
1723
1724 Assert(!(Attrs.hasAttribute(Attribute::StructRet) &&do { if (!(!(Attrs.hasAttribute(Attribute::StructRet) &&
Attrs.hasAttribute(Attribute::Returned)))) { CheckFailed("Attributes "
"'sret and returned' are incompatible!", V); return; } } while
(false)
1725 Attrs.hasAttribute(Attribute::Returned)),do { if (!(!(Attrs.hasAttribute(Attribute::StructRet) &&
Attrs.hasAttribute(Attribute::Returned)))) { CheckFailed("Attributes "
"'sret and returned' are incompatible!", V); return; } } while
(false)
1726 "Attributes "do { if (!(!(Attrs.hasAttribute(Attribute::StructRet) &&
Attrs.hasAttribute(Attribute::Returned)))) { CheckFailed("Attributes "
"'sret and returned' are incompatible!", V); return; } } while
(false)
1727 "'sret and returned' are incompatible!",do { if (!(!(Attrs.hasAttribute(Attribute::StructRet) &&
Attrs.hasAttribute(Attribute::Returned)))) { CheckFailed("Attributes "
"'sret and returned' are incompatible!", V); return; } } while
(false)
1728 V)do { if (!(!(Attrs.hasAttribute(Attribute::StructRet) &&
Attrs.hasAttribute(Attribute::Returned)))) { CheckFailed("Attributes "
"'sret and returned' are incompatible!", V); return; } } while
(false)
;
1729
1730 Assert(!(Attrs.hasAttribute(Attribute::ZExt) &&do { if (!(!(Attrs.hasAttribute(Attribute::ZExt) && Attrs
.hasAttribute(Attribute::SExt)))) { CheckFailed("Attributes "
"'zeroext and signext' are incompatible!", V); return; } } while
(false)
1731 Attrs.hasAttribute(Attribute::SExt)),do { if (!(!(Attrs.hasAttribute(Attribute::ZExt) && Attrs
.hasAttribute(Attribute::SExt)))) { CheckFailed("Attributes "
"'zeroext and signext' are incompatible!", V); return; } } while
(false)
1732 "Attributes "do { if (!(!(Attrs.hasAttribute(Attribute::ZExt) && Attrs
.hasAttribute(Attribute::SExt)))) { CheckFailed("Attributes "
"'zeroext and signext' are incompatible!", V); return; } } while
(false)
1733 "'zeroext and signext' are incompatible!",do { if (!(!(Attrs.hasAttribute(Attribute::ZExt) && Attrs
.hasAttribute(Attribute::SExt)))) { CheckFailed("Attributes "
"'zeroext and signext' are incompatible!", V); return; } } while
(false)
1734 V)do { if (!(!(Attrs.hasAttribute(Attribute::ZExt) && Attrs
.hasAttribute(Attribute::SExt)))) { CheckFailed("Attributes "
"'zeroext and signext' are incompatible!", V); return; } } while
(false)
;
1735
1736 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'readnone and readonly' are incompatible!", V); return; } }
while (false)
1737 Attrs.hasAttribute(Attribute::ReadOnly)),do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'readnone and readonly' are incompatible!", V); return; } }
while (false)
1738 "Attributes "do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'readnone and readonly' are incompatible!", V); return; } }
while (false)
1739 "'readnone and readonly' are incompatible!",do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'readnone and readonly' are incompatible!", V); return; } }
while (false)
1740 V)do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes "
"'readnone and readonly' are incompatible!", V); return; } }
while (false)
;
1741
1742 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readnone and writeonly' are incompatible!", V); return; } }
while (false)
1743 Attrs.hasAttribute(Attribute::WriteOnly)),do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readnone and writeonly' are incompatible!", V); return; } }
while (false)
1744 "Attributes "do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readnone and writeonly' are incompatible!", V); return; } }
while (false)
1745 "'readnone and writeonly' are incompatible!",do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readnone and writeonly' are incompatible!", V); return; } }
while (false)
1746 V)do { if (!(!(Attrs.hasAttribute(Attribute::ReadNone) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readnone and writeonly' are incompatible!", V); return; } }
while (false)
;
1747
1748 Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) &&do { if (!(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readonly and writeonly' are incompatible!", V); return; } }
while (false)
1749 Attrs.hasAttribute(Attribute::WriteOnly)),do { if (!(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readonly and writeonly' are incompatible!", V); return; } }
while (false)
1750 "Attributes "do { if (!(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readonly and writeonly' are incompatible!", V); return; } }
while (false)
1751 "'readonly and writeonly' are incompatible!",do { if (!(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readonly and writeonly' are incompatible!", V); return; } }
while (false)
1752 V)do { if (!(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
Attrs.hasAttribute(Attribute::WriteOnly)))) { CheckFailed("Attributes "
"'readonly and writeonly' are incompatible!", V); return; } }
while (false)
;
1753
1754 Assert(!(Attrs.hasAttribute(Attribute::NoInline) &&do { if (!(!(Attrs.hasAttribute(Attribute::NoInline) &&
Attrs.hasAttribute(Attribute::AlwaysInline)))) { CheckFailed
("Attributes " "'noinline and alwaysinline' are incompatible!"
, V); return; } } while (false)
1755 Attrs.hasAttribute(Attribute::AlwaysInline)),do { if (!(!(Attrs.hasAttribute(Attribute::NoInline) &&
Attrs.hasAttribute(Attribute::AlwaysInline)))) { CheckFailed
("Attributes " "'noinline and alwaysinline' are incompatible!"
, V); return; } } while (false)
1756 "Attributes "do { if (!(!(Attrs.hasAttribute(Attribute::NoInline) &&
Attrs.hasAttribute(Attribute::AlwaysInline)))) { CheckFailed
("Attributes " "'noinline and alwaysinline' are incompatible!"
, V); return; } } while (false)
1757 "'noinline and alwaysinline' are incompatible!",do { if (!(!(Attrs.hasAttribute(Attribute::NoInline) &&
Attrs.hasAttribute(Attribute::AlwaysInline)))) { CheckFailed
("Attributes " "'noinline and alwaysinline' are incompatible!"
, V); return; } } while (false)
1758 V)do { if (!(!(Attrs.hasAttribute(Attribute::NoInline) &&
Attrs.hasAttribute(Attribute::AlwaysInline)))) { CheckFailed
("Attributes " "'noinline and alwaysinline' are incompatible!"
, V); return; } } while (false)
;
1759
1760 AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1761 for (Attribute Attr : Attrs) {
1762 if (!Attr.isStringAttribute() &&
1763 IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
1764 CheckFailed("Attribute '" + Attr.getAsString() +
1765 "' applied to incompatible type!", V);
1766 return;
1767 }
1768 }
1769
1770 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1771 if (Attrs.hasAttribute(Attribute::ByVal)) {
1772 SmallPtrSet<Type *, 4> Visited;
1773 Assert(Attrs.getByValType()->isSized(&Visited),do { if (!(Attrs.getByValType()->isSized(&Visited))) {
CheckFailed("Attribute 'byval' does not support unsized types!"
, V); return; } } while (false)
1774 "Attribute 'byval' does not support unsized types!", V)do { if (!(Attrs.getByValType()->isSized(&Visited))) {
CheckFailed("Attribute 'byval' does not support unsized types!"
, V); return; } } while (false)
;
1775 }
1776 if (Attrs.hasAttribute(Attribute::ByRef)) {
1777 SmallPtrSet<Type *, 4> Visited;
1778 Assert(Attrs.getByRefType()->isSized(&Visited),do { if (!(Attrs.getByRefType()->isSized(&Visited))) {
CheckFailed("Attribute 'byref' does not support unsized types!"
, V); return; } } while (false)
1779 "Attribute 'byref' does not support unsized types!", V)do { if (!(Attrs.getByRefType()->isSized(&Visited))) {
CheckFailed("Attribute 'byref' does not support unsized types!"
, V); return; } } while (false)
;
1780 }
1781 if (Attrs.hasAttribute(Attribute::InAlloca)) {
1782 SmallPtrSet<Type *, 4> Visited;
1783 Assert(Attrs.getInAllocaType()->isSized(&Visited),do { if (!(Attrs.getInAllocaType()->isSized(&Visited))
) { CheckFailed("Attribute 'inalloca' does not support unsized types!"
, V); return; } } while (false)
1784 "Attribute 'inalloca' does not support unsized types!", V)do { if (!(Attrs.getInAllocaType()->isSized(&Visited))
) { CheckFailed("Attribute 'inalloca' does not support unsized types!"
, V); return; } } while (false)
;
1785 }
1786 if (Attrs.hasAttribute(Attribute::Preallocated)) {
1787 SmallPtrSet<Type *, 4> Visited;
1788 Assert(Attrs.getPreallocatedType()->isSized(&Visited),do { if (!(Attrs.getPreallocatedType()->isSized(&Visited
))) { CheckFailed("Attribute 'preallocated' does not support unsized types!"
, V); return; } } while (false)
1789 "Attribute 'preallocated' does not support unsized types!", V)do { if (!(Attrs.getPreallocatedType()->isSized(&Visited
))) { CheckFailed("Attribute 'preallocated' does not support unsized types!"
, V); return; } } while (false)
;
1790 }
1791 if (!PTy->isOpaque()) {
1792 if (!isa<PointerType>(PTy->getElementType()))
1793 Assert(!Attrs.hasAttribute(Attribute::SwiftError),do { if (!(!Attrs.hasAttribute(Attribute::SwiftError))) { CheckFailed
("Attribute 'swifterror' only applies to parameters " "with pointer to pointer type!"
, V); return; } } while (false)
1794 "Attribute 'swifterror' only applies to parameters "do { if (!(!Attrs.hasAttribute(Attribute::SwiftError))) { CheckFailed
("Attribute 'swifterror' only applies to parameters " "with pointer to pointer type!"
, V); return; } } while (false)
1795 "with pointer to pointer type!",do { if (!(!Attrs.hasAttribute(Attribute::SwiftError))) { CheckFailed
("Attribute 'swifterror' only applies to parameters " "with pointer to pointer type!"
, V); return; } } while (false)
1796 V)do { if (!(!Attrs.hasAttribute(Attribute::SwiftError))) { CheckFailed
("Attribute 'swifterror' only applies to parameters " "with pointer to pointer type!"
, V); return; } } while (false)
;
1797 if (Attrs.hasAttribute(Attribute::ByRef)) {
1798 Assert(Attrs.getByRefType() == PTy->getElementType(),do { if (!(Attrs.getByRefType() == PTy->getElementType()))
{ CheckFailed("Attribute 'byref' type does not match parameter!"
, V); return; } } while (false)
1799 "Attribute 'byref' type does not match parameter!", V)do { if (!(Attrs.getByRefType() == PTy->getElementType()))
{ CheckFailed("Attribute 'byref' type does not match parameter!"
, V); return; } } while (false)
;
1800 }
1801
1802 if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
1803 Assert(Attrs.getByValType() == PTy->getElementType(),do { if (!(Attrs.getByValType() == PTy->getElementType()))
{ CheckFailed("Attribute 'byval' type does not match parameter!"
, V); return; } } while (false)
1804 "Attribute 'byval' type does not match parameter!", V)do { if (!(Attrs.getByValType() == PTy->getElementType()))
{ CheckFailed("Attribute 'byval' type does not match parameter!"
, V); return; } } while (false)
;
1805 }
1806
1807 if (Attrs.hasAttribute(Attribute::Preallocated)) {
1808 Assert(Attrs.getPreallocatedType() == PTy->getElementType(),do { if (!(Attrs.getPreallocatedType() == PTy->getElementType
())) { CheckFailed("Attribute 'preallocated' type does not match parameter!"
, V); return; } } while (false)
1809 "Attribute 'preallocated' type does not match parameter!", V)do { if (!(Attrs.getPreallocatedType() == PTy->getElementType
())) { CheckFailed("Attribute 'preallocated' type does not match parameter!"
, V); return; } } while (false)
;
1810 }
1811
1812 if (Attrs.hasAttribute(Attribute::InAlloca)) {
1813 Assert(Attrs.getInAllocaType() == PTy->getElementType(),do { if (!(Attrs.getInAllocaType() == PTy->getElementType(
))) { CheckFailed("Attribute 'inalloca' type does not match parameter!"
, V); return; } } while (false)
1814 "Attribute 'inalloca' type does not match parameter!", V)do { if (!(Attrs.getInAllocaType() == PTy->getElementType(
))) { CheckFailed("Attribute 'inalloca' type does not match parameter!"
, V); return; } } while (false)
;
1815 }
1816
1817 if (Attrs.hasAttribute(Attribute::ElementType)) {
1818 Assert(Attrs.getElementType() == PTy->getElementType(),do { if (!(Attrs.getElementType() == PTy->getElementType()
)) { CheckFailed("Attribute 'elementtype' type does not match parameter!"
, V); return; } } while (false)
1819 "Attribute 'elementtype' type does not match parameter!", V)do { if (!(Attrs.getElementType() == PTy->getElementType()
)) { CheckFailed("Attribute 'elementtype' type does not match parameter!"
, V); return; } } while (false)
;
1820 }
1821 }
1822 }
1823}
1824
1825void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
1826 const Value *V) {
1827 if (Attrs.hasFnAttribute(Attr)) {
1828 StringRef S = Attrs.getAttribute(AttributeList::FunctionIndex, Attr)
1829 .getValueAsString();
1830 unsigned N;
1831 if (S.getAsInteger(10, N))
1832 CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
1833 }
1834}
1835
1836// Check parameter attributes against a function type.
1837// The value V is printed in error messages.
1838void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
1839 const Value *V, bool IsIntrinsic) {
1840 if (Attrs.isEmpty())
1841 return;
1842
1843 if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
1844 Assert(Attrs.hasParentContext(Context),do { if (!(Attrs.hasParentContext(Context))) { CheckFailed("Attribute list does not match Module context!"
, &Attrs, V); return; } } while (false)
1845 "Attribute list does not match Module context!", &Attrs, V)do { if (!(Attrs.hasParentContext(Context))) { CheckFailed("Attribute list does not match Module context!"
, &Attrs, V); return; } } while (false)
;
1846 for (const auto &AttrSet : Attrs) {
1847 Assert(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),do { if (!(!AttrSet.hasAttributes() || AttrSet.hasParentContext
(Context))) { CheckFailed("Attribute set does not match Module context!"
, &AttrSet, V); return; } } while (false)
1848 "Attribute set does not match Module context!", &AttrSet, V)do { if (!(!AttrSet.hasAttributes() || AttrSet.hasParentContext
(Context))) { CheckFailed("Attribute set does not match Module context!"
, &AttrSet, V); return; } } while (false)
;
1849 for (const auto &A : AttrSet) {
1850 Assert(A.hasParentContext(Context),do { if (!(A.hasParentContext(Context))) { CheckFailed("Attribute does not match Module context!"
, &A, V); return; } } while (false)
1851 "Attribute does not match Module context!", &A, V)do { if (!(A.hasParentContext(Context))) { CheckFailed("Attribute does not match Module context!"
, &A, V); return; } } while (false)
;
1852 }
1853 }
1854 }
1855
1856 bool SawNest = false;
1857 bool SawReturned = false;
1858 bool SawSRet = false;
1859 bool SawSwiftSelf = false;
1860 bool SawSwiftAsync = false;
1861 bool SawSwiftError = false;
1862
1863 // Verify return value attributes.
1864 AttributeSet RetAttrs = Attrs.getRetAttributes();
1865 for (Attribute RetAttr : RetAttrs)
1866 Assert(RetAttr.isStringAttribute() ||do { if (!(RetAttr.isStringAttribute() || Attribute::canUseAsRetAttr
(RetAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + RetAttr
.getAsString() + "' does not apply to function return values"
, V); return; } } while (false)
1867 Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),do { if (!(RetAttr.isStringAttribute() || Attribute::canUseAsRetAttr
(RetAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + RetAttr
.getAsString() + "' does not apply to function return values"
, V); return; } } while (false)
1868 "Attribute '" + RetAttr.getAsString() +do { if (!(RetAttr.isStringAttribute() || Attribute::canUseAsRetAttr
(RetAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + RetAttr
.getAsString() + "' does not apply to function return values"
, V); return; } } while (false)
1869 "' does not apply to function return values",do { if (!(RetAttr.isStringAttribute() || Attribute::canUseAsRetAttr
(RetAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + RetAttr
.getAsString() + "' does not apply to function return values"
, V); return; } } while (false)
1870 V)do { if (!(RetAttr.isStringAttribute() || Attribute::canUseAsRetAttr
(RetAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + RetAttr
.getAsString() + "' does not apply to function return values"
, V); return; } } while (false)
;
1871
1872 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
1873
1874 // Verify parameter attributes.
1875 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1876 Type *Ty = FT->getParamType(i);
1877 AttributeSet ArgAttrs = Attrs.getParamAttributes(i);
1878
1879 if (!IsIntrinsic) {
1880 Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg),do { if (!(!ArgAttrs.hasAttribute(Attribute::ImmArg))) { CheckFailed
("immarg attribute only applies to intrinsics",V); return; } }
while (false)
1881 "immarg attribute only applies to intrinsics",V)do { if (!(!ArgAttrs.hasAttribute(Attribute::ImmArg))) { CheckFailed
("immarg attribute only applies to intrinsics",V); return; } }
while (false)
;
1882 Assert(!ArgAttrs.hasAttribute(Attribute::ElementType),do { if (!(!ArgAttrs.hasAttribute(Attribute::ElementType))) {
CheckFailed("Attribute 'elementtype' can only be applied to intrinsics."
, V); return; } } while (false)
1883 "Attribute 'elementtype' can only be applied to intrinsics.", V)do { if (!(!ArgAttrs.hasAttribute(Attribute::ElementType))) {
CheckFailed("Attribute 'elementtype' can only be applied to intrinsics."
, V); return; } } while (false)
;
1884 }
1885
1886 verifyParameterAttrs(ArgAttrs, Ty, V);
1887
1888 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
1889 Assert(!SawNest, "More than one parameter has attribute nest!", V)do { if (!(!SawNest)) { CheckFailed("More than one parameter has attribute nest!"
, V); return; } } while (false)
;
1890 SawNest = true;
1891 }
1892
1893 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
1894 Assert(!SawReturned, "More than one parameter has attribute returned!",do { if (!(!SawReturned)) { CheckFailed("More than one parameter has attribute returned!"
, V); return; } } while (false)
1895 V)do { if (!(!SawReturned)) { CheckFailed("More than one parameter has attribute returned!"
, V); return; } } while (false)
;
1896 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),do { if (!(Ty->canLosslesslyBitCastTo(FT->getReturnType
()))) { CheckFailed("Incompatible argument and return types for 'returned' attribute"
, V); return; } } while (false)
1897 "Incompatible argument and return types for 'returned' attribute",do { if (!(Ty->canLosslesslyBitCastTo(FT->getReturnType
()))) { CheckFailed("Incompatible argument and return types for 'returned' attribute"
, V); return; } } while (false)
1898 V)do { if (!(Ty->canLosslesslyBitCastTo(FT->getReturnType
()))) { CheckFailed("Incompatible argument and return types for 'returned' attribute"
, V); return; } } while (false)
;
1899 SawReturned = true;
1900 }
1901
1902 if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
1903 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V)do { if (!(!SawSRet)) { CheckFailed("Cannot have multiple 'sret' parameters!"
, V); return; } } while (false)
;
1904 Assert(i == 0 || i == 1,do { if (!(i == 0 || i == 1)) { CheckFailed("Attribute 'sret' is not on first or second parameter!"
, V); return; } } while (false)
1905 "Attribute 'sret' is not on first or second parameter!", V)do { if (!(i == 0 || i == 1)) { CheckFailed("Attribute 'sret' is not on first or second parameter!"
, V); return; } } while (false)
;
1906 SawSRet = true;
1907 }
1908
1909 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
1910 Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V)do { if (!(!SawSwiftSelf)) { CheckFailed("Cannot have multiple 'swiftself' parameters!"
, V); return; } } while (false)
;
1911 SawSwiftSelf = true;
1912 }
1913
1914 if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
1915 Assert(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V)do { if (!(!SawSwiftAsync)) { CheckFailed("Cannot have multiple 'swiftasync' parameters!"
, V); return; } } while (false)
;
1916 SawSwiftAsync = true;
1917 }
1918
1919 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
1920 Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",do { if (!(!SawSwiftError)) { CheckFailed("Cannot have multiple 'swifterror' parameters!"
, V); return; } } while (false)
1921 V)do { if (!(!SawSwiftError)) { CheckFailed("Cannot have multiple 'swifterror' parameters!"
, V); return; } } while (false)
;
1922 SawSwiftError = true;
1923 }
1924
1925 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
1926 Assert(i == FT->getNumParams() - 1,do { if (!(i == FT->getNumParams() - 1)) { CheckFailed("inalloca isn't on the last parameter!"
, V); return; } } while (false)
1927 "inalloca isn't on the last parameter!", V)do { if (!(i == FT->getNumParams() - 1)) { CheckFailed("inalloca isn't on the last parameter!"
, V); return; } } while (false)
;
1928 }
1929 }
1930
1931 if (!Attrs.hasAttributes(AttributeList::FunctionIndex))
1932 return;
1933
1934 verifyAttributeTypes(Attrs.getFnAttributes(), V);
1935 for (Attribute FnAttr : Attrs.getFnAttributes())
1936 Assert(FnAttr.isStringAttribute() ||do { if (!(FnAttr.isStringAttribute() || Attribute::canUseAsFnAttr
(FnAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + FnAttr
.getAsString() + "' does not apply to functions!", V); return
; } } while (false)
1937 Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),do { if (!(FnAttr.isStringAttribute() || Attribute::canUseAsFnAttr
(FnAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + FnAttr
.getAsString() + "' does not apply to functions!", V); return
; } } while (false)
1938 "Attribute '" + FnAttr.getAsString() +do { if (!(FnAttr.isStringAttribute() || Attribute::canUseAsFnAttr
(FnAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + FnAttr
.getAsString() + "' does not apply to functions!", V); return
; } } while (false)
1939 "' does not apply to functions!",do { if (!(FnAttr.isStringAttribute() || Attribute::canUseAsFnAttr
(FnAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + FnAttr
.getAsString() + "' does not apply to functions!", V); return
; } } while (false)
1940 V)do { if (!(FnAttr.isStringAttribute() || Attribute::canUseAsFnAttr
(FnAttr.getKindAsEnum()))) { CheckFailed("Attribute '" + FnAttr
.getAsString() + "' does not apply to functions!", V); return
; } } while (false)
;
1941
1942 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes 'readnone and readonly' are incompatible!"
, V); return; } } while (false)
1943 Attrs.hasFnAttribute(Attribute::ReadOnly)),do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes 'readnone and readonly' are incompatible!"
, V); return; } } while (false)
1944 "Attributes 'readnone and readonly' are incompatible!", V)do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::ReadOnly)))) { CheckFailed("Attributes 'readnone and readonly' are incompatible!"
, V); return; } } while (false)
;
1945
1946 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::WriteOnly)))) { CheckFailed(
"Attributes 'readnone and writeonly' are incompatible!", V); return
; } } while (false)
1947 Attrs.hasFnAttribute(Attribute::WriteOnly)),do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::WriteOnly)))) { CheckFailed(
"Attributes 'readnone and writeonly' are incompatible!", V); return
; } } while (false)
1948 "Attributes 'readnone and writeonly' are incompatible!", V)do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::WriteOnly)))) { CheckFailed(
"Attributes 'readnone and writeonly' are incompatible!", V); return
; } } while (false)
;
1949
1950 Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) &&do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadOnly) &&
Attrs.hasFnAttribute(Attribute::WriteOnly)))) { CheckFailed(
"Attributes 'readonly and writeonly' are incompatible!", V); return
; } } while (false)
1951 Attrs.hasFnAttribute(Attribute::WriteOnly)),do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadOnly) &&
Attrs.hasFnAttribute(Attribute::WriteOnly)))) { CheckFailed(
"Attributes 'readonly and writeonly' are incompatible!", V); return
; } } while (false)
1952 "Attributes 'readonly and writeonly' are incompatible!", V)do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadOnly) &&
Attrs.hasFnAttribute(Attribute::WriteOnly)))) { CheckFailed(
"Attributes 'readonly and writeonly' are incompatible!", V); return
; } } while (false)
;
1953
1954 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)
))) { CheckFailed("Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
"incompatible!", V); return; } } while (false)
1955 Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)),do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)
))) { CheckFailed("Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
"incompatible!", V); return; } } while (false)
1956 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)
))) { CheckFailed("Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
"incompatible!", V); return; } } while (false)
1957 "incompatible!",do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)
))) { CheckFailed("Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
"incompatible!", V); return; } } while (false)
1958 V)do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)
))) { CheckFailed("Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
"incompatible!", V); return; } } while (false)
;
1959
1960 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)))) { CheckFailed
("Attributes 'readnone and inaccessiblememonly' are incompatible!"
, V); return; } } while (false)
1961 Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)),do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)))) { CheckFailed
("Attributes 'readnone and inaccessiblememonly' are incompatible!"
, V); return; } } while (false)
1962 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V)do { if (!(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)))) { CheckFailed
("Attributes 'readnone and inaccessiblememonly' are incompatible!"
, V); return; } } while (false)
;
1963
1964 Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) &&do { if (!(!(Attrs.hasFnAttribute(Attribute::NoInline) &&
Attrs.hasFnAttribute(Attribute::AlwaysInline)))) { CheckFailed
("Attributes 'noinline and alwaysinline' are incompatible!", V
); return; } } while (false)
1965 Attrs.hasFnAttribute(Attribute::AlwaysInline)),do { if (!(!(Attrs.hasFnAttribute(Attribute::NoInline) &&
Attrs.hasFnAttribute(Attribute::AlwaysInline)))) { CheckFailed
("Attributes 'noinline and alwaysinline' are incompatible!", V
); return; } } while (false)
1966 "Attributes 'noinline and alwaysinline' are incompatible!", V)do { if (!(!(Attrs.hasFnAttribute(Attribute::NoInline) &&
Attrs.hasFnAttribute(Attribute::AlwaysInline)))) { CheckFailed
("Attributes 'noinline and alwaysinline' are incompatible!", V
); return; } } while (false)
;
1967
1968 if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) {
1969 Assert(Attrs.hasFnAttribute(Attribute::NoInline),do { if (!(Attrs.hasFnAttribute(Attribute::NoInline))) { CheckFailed
("Attribute 'optnone' requires 'noinline'!", V); return; } } while
(false)
1970 "Attribute 'optnone' requires 'noinline'!", V)do { if (!(Attrs.hasFnAttribute(Attribute::NoInline))) { CheckFailed
("Attribute 'optnone' requires 'noinline'!", V); return; } } while
(false)
;
1971
1972 Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize),do { if (!(!Attrs.hasFnAttribute(Attribute::OptimizeForSize))
) { CheckFailed("Attributes 'optsize and optnone' are incompatible!"
, V); return; } } while (false)
1973 "Attributes 'optsize and optnone' are incompatible!", V)do { if (!(!Attrs.hasFnAttribute(Attribute::OptimizeForSize))
) { CheckFailed("Attributes 'optsize and optnone' are incompatible!"
, V); return; } } while (false)
;
1974
1975 Assert(!Attrs.hasFnAttribute(Attribute::MinSize),do { if (!(!Attrs.hasFnAttribute(Attribute::MinSize))) { CheckFailed
("Attributes 'minsize and optnone' are incompatible!", V); return
; } } while (false)
1976 "Attributes 'minsize and optnone' are incompatible!", V)do { if (!(!Attrs.hasFnAttribute(Attribute::MinSize))) { CheckFailed
("Attributes 'minsize and optnone' are incompatible!", V); return
; } } while (false)
;
1977 }
1978
1979 if (Attrs.hasFnAttribute(Attribute::JumpTable)) {
1980 const GlobalValue *GV = cast<GlobalValue>(V);
1981 Assert(GV->hasGlobalUnnamedAddr(),do { if (!(GV->hasGlobalUnnamedAddr())) { CheckFailed("Attribute 'jumptable' requires 'unnamed_addr'"
, V); return; } } while (false)
1982 "Attribute 'jumptable' requires 'unnamed_addr'", V)do { if (!(GV->hasGlobalUnnamedAddr())) { CheckFailed("Attribute 'jumptable' requires 'unnamed_addr'"
, V); return; } } while (false)
;
1983 }
1984
1985 if (Attrs.hasFnAttribute(Attribute::AllocSize)) {
1986 std::pair<unsigned, Optional<unsigned>> Args =
1987 Attrs.getAllocSizeArgs(AttributeList::FunctionIndex);
1988
1989 auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
1990 if (ParamNo >= FT->getNumParams()) {
1991 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
1992 return false;
1993 }
1994
1995 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
1996 CheckFailed("'allocsize' " + Name +
1997 " argument must refer to an integer parameter",
1998 V);
1999 return false;
2000 }
2001
2002 return true;
2003 };
2004
2005 if (!CheckParam("element size", Args.first))
2006 return;
2007
2008 if (Args.second && !CheckParam("number of elements", *Args.second))
2009 return;
2010 }
2011
2012 if (Attrs.hasFnAttribute(Attribute::VScaleRange)) {
2013 std::pair<unsigned, unsigned> Args =
2014 Attrs.getVScaleRangeArgs(AttributeList::FunctionIndex);
2015
2016 if (Args.first > Args.second && Args.second != 0)
2017 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2018 }
2019
2020 if (Attrs.hasFnAttribute("frame-pointer")) {
2021 StringRef FP = Attrs.getAttribute(AttributeList::FunctionIndex,
2022 "frame-pointer").getValueAsString();
2023 if (FP != "all" && FP != "non-leaf" && FP != "none")
2024 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2025 }
2026
2027 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2028 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2029 checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2030}
2031
2032void Verifier::verifyFunctionMetadata(
2033 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2034 for (const auto &Pair : MDs) {
2035 if (Pair.first == LLVMContext::MD_prof) {
2036 MDNode *MD = Pair.second;
2037 Assert(MD->getNumOperands() >= 2,do { if (!(MD->getNumOperands() >= 2)) { CheckFailed("!prof annotations should have no less than 2 operands"
, MD); return; } } while (false)
2038 "!prof annotations should have no less than 2 operands", MD)do { if (!(MD->getNumOperands() >= 2)) { CheckFailed("!prof annotations should have no less than 2 operands"
, MD); return; } } while (false)
;
2039
2040 // Check first operand.
2041 Assert(MD->getOperand(0) != nullptr, "first operand should not be null",do { if (!(MD->getOperand(0) != nullptr)) { CheckFailed("first operand should not be null"
, MD); return; } } while (false)
2042 MD)do { if (!(MD->getOperand(0) != nullptr)) { CheckFailed("first operand should not be null"
, MD); return; } } while (false)
;
2043 Assert(isa<MDString>(MD->getOperand(0)),do { if (!(isa<MDString>(MD->getOperand(0)))) { CheckFailed
("expected string with name of the !prof annotation", MD); return
; } } while (false)
2044 "expected string with name of the !prof annotation", MD)do { if (!(isa<MDString>(MD->getOperand(0)))) { CheckFailed
("expected string with name of the !prof annotation", MD); return
; } } while (false)
;
2045 MDString *MDS = cast<MDString>(MD->getOperand(0));
2046 StringRef ProfName = MDS->getString();
2047 Assert(ProfName.equals("function_entry_count") ||do { if (!(ProfName.equals("function_entry_count") || ProfName
.equals("synthetic_function_entry_count"))) { CheckFailed("first operand should be 'function_entry_count'"
" or 'synthetic_function_entry_count'", MD); return; } } while
(false)
2048 ProfName.equals("synthetic_function_entry_count"),do { if (!(ProfName.equals("function_entry_count") || ProfName
.equals("synthetic_function_entry_count"))) { CheckFailed("first operand should be 'function_entry_count'"
" or 'synthetic_function_entry_count'", MD); return; } } while
(false)
2049 "first operand should be 'function_entry_count'"do { if (!(ProfName.equals("function_entry_count") || ProfName
.equals("synthetic_function_entry_count"))) { CheckFailed("first operand should be 'function_entry_count'"
" or 'synthetic_function_entry_count'", MD); return; } } while
(false)
2050 " or 'synthetic_function_entry_count'",do { if (!(ProfName.equals("function_entry_count") || ProfName
.equals("synthetic_function_entry_count"))) { CheckFailed("first operand should be 'function_entry_count'"
" or 'synthetic_function_entry_count'", MD); return; } } while
(false)
2051 MD)do { if (!(ProfName.equals("function_entry_count") || ProfName
.equals("synthetic_function_entry_count"))) { CheckFailed("first operand should be 'function_entry_count'"
" or 'synthetic_function_entry_count'", MD); return; } } while
(false)
;
2052
2053 // Check second operand.
2054 Assert(MD->getOperand(1) != nullptr, "second operand should not be null",do { if (!(MD->getOperand(1) != nullptr)) { CheckFailed("second operand should not be null"
, MD); return; } } while (false)
2055 MD)do { if (!(MD->getOperand(1) != nullptr)) { CheckFailed("second operand should not be null"
, MD); return; } } while (false)
;
2056 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),do { if (!(isa<ConstantAsMetadata>(MD->getOperand(1)
))) { CheckFailed("expected integer argument to function_entry_count"
, MD); return; } } while (false)
2057 "expected integer argument to function_entry_count", MD)do { if (!(isa<ConstantAsMetadata>(MD->getOperand(1)
))) { CheckFailed("expected integer argument to function_entry_count"
, MD); return; } } while (false)
;
2058 }
2059 }
2060}
2061
2062void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2063 if (!ConstantExprVisited.insert(EntryC).second)
2064 return;
2065
2066 SmallVector<const Constant *, 16> Stack;
2067 Stack.push_back(EntryC);
2068
2069 while (!Stack.empty()) {
2070 const Constant *C = Stack.pop_back_val();
2071
2072 // Check this constant expression.
2073 if (const auto *CE = dyn_cast<ConstantExpr>(C))
2074 visitConstantExpr(CE);
2075
2076 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2077 // Global Values get visited separately, but we do need to make sure
2078 // that the global value is in the correct module
2079 Assert(GV->getParent() == &M, "Referencing global in another module!",do { if (!(GV->getParent() == &M)) { CheckFailed("Referencing global in another module!"
, EntryC, &M, GV, GV->getParent()); return; } } while (
false)
2080 EntryC, &M, GV, GV->getParent())do { if (!(GV->getParent() == &M)) { CheckFailed("Referencing global in another module!"
, EntryC, &M, GV, GV->getParent()); return; } } while (
false)
;
2081 continue;
2082 }
2083
2084 // Visit all sub-expressions.
2085 for (const Use &U : C->operands()) {
2086 const auto *OpC = dyn_cast<Constant>(U);
2087 if (!OpC)
2088 continue;
2089 if (!ConstantExprVisited.insert(OpC).second)
2090 continue;
2091 Stack.push_back(OpC);
2092 }
2093 }
2094}
2095
2096void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2097 if (CE->getOpcode() == Instruction::BitCast)
2098 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),do { if (!(CastInst::castIsValid(Instruction::BitCast, CE->
getOperand(0), CE->getType()))) { CheckFailed("Invalid bitcast"
, CE); return; } } while (false)
2099 CE->getType()),do { if (!(CastInst::castIsValid(Instruction::BitCast, CE->
getOperand(0), CE->getType()))) { CheckFailed("Invalid bitcast"
, CE); return; } } while (false)
2100 "Invalid bitcast", CE)do { if (!(CastInst::castIsValid(Instruction::BitCast, CE->
getOperand(0), CE->getType()))) { CheckFailed("Invalid bitcast"
, CE); return; } } while (false)
;
2101}
2102
2103bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2104 // There shouldn't be more attribute sets than there are parameters plus the
2105 // function and return value.
2106 return Attrs.getNumAttrSets() <= Params + 2;
2107}
2108
2109/// Verify that statepoint intrinsic is well formed.
2110void Verifier::verifyStatepoint(const CallBase &Call) {
2111 assert(Call.getCalledFunction() &&((void)0)
2112 Call.getCalledFunction()->getIntrinsicID() ==((void)0)
2113 Intrinsic::experimental_gc_statepoint)((void)0);
2114
2115 Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&do { if (!(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory
() && !Call.onlyAccessesArgMemory())) { CheckFailed("gc.statepoint must read and write all memory to preserve "
"reordering restrictions required by safepoint semantics", Call
); return; } } while (false)
2116 !Call.onlyAccessesArgMemory(),do { if (!(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory
() && !Call.onlyAccessesArgMemory())) { CheckFailed("gc.statepoint must read and write all memory to preserve "
"reordering restrictions required by safepoint semantics", Call
); return; } } while (false)
2117 "gc.statepoint must read and write all memory to preserve "do { if (!(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory
() && !Call.onlyAccessesArgMemory())) { CheckFailed("gc.statepoint must read and write all memory to preserve "
"reordering restrictions required by safepoint semantics", Call
); return; } } while (false)
2118 "reordering restrictions required by safepoint semantics",do { if (!(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory
() && !Call.onlyAccessesArgMemory())) { CheckFailed("gc.statepoint must read and write all memory to preserve "
"reordering restrictions required by safepoint semantics", Call
); return; } } while (false)
2119 Call)do { if (!(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory
() && !Call.onlyAccessesArgMemory())) { CheckFailed("gc.statepoint must read and write all memory to preserve "
"reordering restrictions required by safepoint semantics", Call
); return; } } while (false)
;
2120
2121 const int64_t NumPatchBytes =
2122 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2123 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!")((void)0);
2124 Assert(NumPatchBytes >= 0,do { if (!(NumPatchBytes >= 0)) { CheckFailed("gc.statepoint number of patchable bytes must be "
"positive", Call); return; } } while (false)
2125 "gc.statepoint number of patchable bytes must be "do { if (!(NumPatchBytes >= 0)) { CheckFailed("gc.statepoint number of patchable bytes must be "
"positive", Call); return; } } while (false)
2126 "positive",do { if (!(NumPatchBytes >= 0)) { CheckFailed("gc.statepoint number of patchable bytes must be "
"positive", Call); return; } } while (false)
2127 Call)do { if (!(NumPatchBytes >= 0)) { CheckFailed("gc.statepoint number of patchable bytes must be "
"positive", Call); return; } } while (false)
;
2128
2129 const Value *Target = Call.getArgOperand(2);
2130 auto *PT = dyn_cast<PointerType>(Target->getType());
2131 Assert(PT && PT->getElementType()->isFunctionTy(),do { if (!(PT && PT->getElementType()->isFunctionTy
())) { CheckFailed("gc.statepoint callee must be of function pointer type"
, Call, Target); return; } } while (false)
2132 "gc.statepoint callee must be of function pointer type", Call, Target)do { if (!(PT && PT->getElementType()->isFunctionTy
())) { CheckFailed("gc.statepoint callee must be of function pointer type"
, Call, Target); return; } } while (false)
;
2133 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
2134
2135 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2136 Assert(NumCallArgs >= 0,do { if (!(NumCallArgs >= 0)) { CheckFailed("gc.statepoint number of arguments to underlying call "
"must be positive", Call); return; } } while (false)
2137 "gc.statepoint number of arguments to underlying call "do { if (!(NumCallArgs >= 0)) { CheckFailed("gc.statepoint number of arguments to underlying call "
"must be positive", Call); return; } } while (false)
2138 "must be positive",do { if (!(NumCallArgs >= 0)) { CheckFailed("gc.statepoint number of arguments to underlying call "
"must be positive", Call); return; } } while (false)
2139 Call)do { if (!(NumCallArgs >= 0)) { CheckFailed("gc.statepoint number of arguments to underlying call "
"must be positive", Call); return; } } while (false)
;
2140 const int NumParams = (int)TargetFuncType->getNumParams();
2141 if (TargetFuncType->isVarArg()) {
2142 Assert(NumCallArgs >= NumParams,do { if (!(NumCallArgs >= NumParams)) { CheckFailed("gc.statepoint mismatch in number of vararg call args"
, Call); return; } } while (false)
2143 "gc.statepoint mismatch in number of vararg call args", Call)do { if (!(NumCallArgs >= NumParams)) { CheckFailed("gc.statepoint mismatch in number of vararg call args"
, Call); return; } } while (false)
;
2144
2145 // TODO: Remove this limitation
2146 Assert(TargetFuncType->getReturnType()->isVoidTy(),do { if (!(TargetFuncType->getReturnType()->isVoidTy())
) { CheckFailed("gc.statepoint doesn't support wrapping non-void "
"vararg functions yet", Call); return; } } while (false)
2147 "gc.statepoint doesn't support wrapping non-void "do { if (!(TargetFuncType->getReturnType()->isVoidTy())
) { CheckFailed("gc.statepoint doesn't support wrapping non-void "
"vararg functions yet", Call); return; } } while (false)
2148 "vararg functions yet",do { if (!(TargetFuncType->getReturnType()->isVoidTy())
) { CheckFailed("gc.statepoint doesn't support wrapping non-void "
"vararg functions yet", Call); return; } } while (false)
2149 Call)do { if (!(TargetFuncType->getReturnType()->isVoidTy())
) { CheckFailed("gc.statepoint doesn't support wrapping non-void "
"vararg functions yet", Call); return; } } while (false)
;
2150 } else
2151 Assert(NumCallArgs == NumParams,do { if (!(NumCallArgs == NumParams)) { CheckFailed("gc.statepoint mismatch in number of call args"
, Call); return; } } while (false)
2152 "gc.statepoint mismatch in number of call args", Call)do { if (!(NumCallArgs == NumParams)) { CheckFailed("gc.statepoint mismatch in number of call args"
, Call); return; } } while (false)
;
2153
2154 const uint64_t Flags
2155 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
2156 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,do { if (!((Flags & ~(uint64_t)StatepointFlags::MaskAll) ==
0)) { CheckFailed("unknown flag used in gc.statepoint flags argument"
, Call); return; } } while (false)
2157 "unknown flag used in gc.statepoint flags argument", Call)do { if (!((Flags & ~(uint64_t)StatepointFlags::MaskAll) ==
0)) { CheckFailed("unknown flag used in gc.statepoint flags argument"
, Call); return; } } while (false)
;
2158
2159 // Verify that the types of the call parameter arguments match
2160 // the type of the wrapped callee.
2161 AttributeList Attrs = Call.getAttributes();
2162 for (int i = 0; i < NumParams; i++) {
2163 Type *ParamType = TargetFuncType->getParamType(i);
2164 Type *ArgType = Call.getArgOperand(5 + i)->getType();
2165 Assert(ArgType == ParamType,do { if (!(ArgType == ParamType)) { CheckFailed("gc.statepoint call argument does not match wrapped "
"function type", Call); return; } } while (false)
2166 "gc.statepoint call argument does not match wrapped "do { if (!(ArgType == ParamType)) { CheckFailed("gc.statepoint call argument does not match wrapped "
"function type", Call); return; } } while (false)
2167 "function type",do { if (!(ArgType == ParamType)) { CheckFailed("gc.statepoint call argument does not match wrapped "
"function type", Call); return; } } while (false)
2168 Call)do { if (!(ArgType == ParamType)) { CheckFailed("gc.statepoint call argument does not match wrapped "
"function type", Call); return; } } while (false)
;
2169
2170 if (TargetFuncType->isVarArg()) {
2171 AttributeSet ArgAttrs = Attrs.getParamAttributes(5 + i);
2172 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),do { if (!(!ArgAttrs.hasAttribute(Attribute::StructRet))) { CheckFailed
("Attribute 'sret' cannot be used for vararg call arguments!"
, Call); return; } } while (false)
2173 "Attribute 'sret' cannot be used for vararg call arguments!",do { if (!(!ArgAttrs.hasAttribute(Attribute::StructRet))) { CheckFailed
("Attribute 'sret' cannot be used for vararg call arguments!"
, Call); return; } } while (false)
2174 Call)do { if (!(!ArgAttrs.hasAttribute(Attribute::StructRet))) { CheckFailed
("Attribute 'sret' cannot be used for vararg call arguments!"
, Call); return; } } while (false)
;
2175 }
2176 }
2177
2178 const int EndCallArgsInx = 4 + NumCallArgs;
2179
2180 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
2181 Assert(isa<ConstantInt>(NumTransitionArgsV),do { if (!(isa<ConstantInt>(NumTransitionArgsV))) { CheckFailed
("gc.statepoint number of transition arguments " "must be constant integer"
, Call); return; } } while (false)
2182 "gc.statepoint number of transition arguments "do { if (!(isa<ConstantInt>(NumTransitionArgsV))) { CheckFailed
("gc.statepoint number of transition arguments " "must be constant integer"
, Call); return; } } while (false)
2183 "must be constant integer",do { if (!(isa<ConstantInt>(NumTransitionArgsV))) { CheckFailed
("gc.statepoint number of transition arguments " "must be constant integer"
, Call); return; } } while (false)
2184 Call)do { if (!(isa<ConstantInt>(NumTransitionArgsV))) { CheckFailed
("gc.statepoint number of transition arguments " "must be constant integer"
, Call); return; } } while (false)
;
2185 const int NumTransitionArgs =
2186 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2187 Assert(NumTransitionArgs == 0,do { if (!(NumTransitionArgs == 0)) { CheckFailed("gc.statepoint w/inline transition bundle is deprecated"
, Call); return; } } while (false)
2188 "gc.statepoint w/inline transition bundle is deprecated", Call)do { if (!(NumTransitionArgs == 0)) { CheckFailed("gc.statepoint w/inline transition bundle is deprecated"
, Call); return; } } while (false)
;
2189 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2190
2191 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
2192 Assert(isa<ConstantInt>(NumDeoptArgsV),do { if (!(isa<ConstantInt>(NumDeoptArgsV))) { CheckFailed
("gc.statepoint number of deoptimization arguments " "must be constant integer"
, Call); return; } } while (false)
2193 "gc.statepoint number of deoptimization arguments "do { if (!(isa<ConstantInt>(NumDeoptArgsV))) { CheckFailed
("gc.statepoint number of deoptimization arguments " "must be constant integer"
, Call); return; } } while (false)
2194 "must be constant integer",do { if (!(isa<ConstantInt>(NumDeoptArgsV))) { CheckFailed
("gc.statepoint number of deoptimization arguments " "must be constant integer"
, Call); return; } } while (false)
2195 Call)do { if (!(isa<ConstantInt>(NumDeoptArgsV))) { CheckFailed
("gc.statepoint number of deoptimization arguments " "must be constant integer"
, Call); return; } } while (false)
;
2196 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2197 Assert(NumDeoptArgs == 0,do { if (!(NumDeoptArgs == 0)) { CheckFailed("gc.statepoint w/inline deopt operands is deprecated"
, Call); return; } } while (false)
2198 "gc.statepoint w/inline deopt operands is deprecated", Call)do { if (!(NumDeoptArgs == 0)) { CheckFailed("gc.statepoint w/inline deopt operands is deprecated"
, Call); return; } } while (false)
;
2199
2200 const int ExpectedNumArgs = 7 + NumCallArgs;
2201 Assert(ExpectedNumArgs == (int)Call.arg_size(),do { if (!(ExpectedNumArgs == (int)Call.arg_size())) { CheckFailed
("gc.statepoint too many arguments", Call); return; } } while
(false)
2202 "gc.statepoint too many arguments", Call)do { if (!(ExpectedNumArgs == (int)Call.arg_size())) { CheckFailed
("gc.statepoint too many arguments", Call); return; } } while
(false)
;
2203
2204 // Check that the only uses of this gc.statepoint are gc.result or
2205 // gc.relocate calls which are tied to this statepoint and thus part
2206 // of the same statepoint sequence
2207 for (const User *U : Call.users()) {
2208 const CallInst *UserCall = dyn_cast<const CallInst>(U);
2209 Assert(UserCall, "illegal use of statepoint token", Call, U)do { if (!(UserCall)) { CheckFailed("illegal use of statepoint token"
, Call, U); return; } } while (false)
;
2210 if (!UserCall)
2211 continue;
2212 Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),do { if (!(isa<GCRelocateInst>(UserCall) || isa<GCResultInst
>(UserCall))) { CheckFailed("gc.result or gc.relocate are the only value uses "
"of a gc.statepoint", Call, U); return; } } while (false)
2213 "gc.result or gc.relocate are the only value uses "do { if (!(isa<GCRelocateInst>(UserCall) || isa<GCResultInst
>(UserCall))) { CheckFailed("gc.result or gc.relocate are the only value uses "
"of a gc.statepoint", Call, U); return; } } while (false)
2214 "of a gc.statepoint",do { if (!(isa<GCRelocateInst>(UserCall) || isa<GCResultInst
>(UserCall))) { CheckFailed("gc.result or gc.relocate are the only value uses "
"of a gc.statepoint", Call, U); return; } } while (false)
2215 Call, U)do { if (!(isa<GCRelocateInst>(UserCall) || isa<GCResultInst
>(UserCall))) { CheckFailed("gc.result or gc.relocate are the only value uses "
"of a gc.statepoint", Call, U); return; } } while (false)
;
2216 if (isa<GCResultInst>(UserCall)) {
2217 Assert(UserCall->getArgOperand(0) == &Call,do { if (!(UserCall->getArgOperand(0) == &Call)) { CheckFailed
("gc.result connected to wrong gc.statepoint", Call, UserCall
); return; } } while (false)
2218 "gc.result connected to wrong gc.statepoint", Call, UserCall)do { if (!(UserCall->getArgOperand(0) == &Call)) { CheckFailed
("gc.result connected to wrong gc.statepoint", Call, UserCall
); return; } } while (false)
;
2219 } else if (isa<GCRelocateInst>(Call)) {
2220 Assert(UserCall->getArgOperand(0) == &Call,do { if (!(UserCall->getArgOperand(0) == &Call)) { CheckFailed
("gc.relocate connected to wrong gc.statepoint", Call, UserCall
); return; } } while (false)
2221 "gc.relocate connected to wrong gc.statepoint", Call, UserCall)do { if (!(UserCall->getArgOperand(0) == &Call)) { CheckFailed
("gc.relocate connected to wrong gc.statepoint", Call, UserCall
); return; } } while (false)
;
2222 }
2223 }
2224
2225 // Note: It is legal for a single derived pointer to be listed multiple
2226 // times. It's non-optimal, but it is legal. It can also happen after
2227 // insertion if we strip a bitcast away.
2228 // Note: It is really tempting to check that each base is relocated and
2229 // that a derived pointer is never reused as a base pointer. This turns
2230 // out to be problematic since optimizations run after safepoint insertion
2231 // can recognize equality properties that the insertion logic doesn't know
2232 // about. See example statepoint.ll in the verifier subdirectory
2233}
2234
2235void Verifier::verifyFrameRecoverIndices() {
2236 for (auto &Counts : FrameEscapeInfo) {
2237 Function *F = Counts.first;
2238 unsigned EscapedObjectCount = Counts.second.first;
2239 unsigned MaxRecoveredIndex = Counts.second.second;
2240 Assert(MaxRecoveredIndex <= EscapedObjectCount,do { if (!(MaxRecoveredIndex <= EscapedObjectCount)) { CheckFailed
("all indices passed to llvm.localrecover must be less than the "
"number of arguments passed to llvm.localescape in the parent "
"function", F); return; } } while (false)
2241 "all indices passed to llvm.localrecover must be less than the "do { if (!(MaxRecoveredIndex <= EscapedObjectCount)) { CheckFailed
("all indices passed to llvm.localrecover must be less than the "
"number of arguments passed to llvm.localescape in the parent "
"function", F); return; } } while (false)
2242 "number of arguments passed to llvm.localescape in the parent "do { if (!(MaxRecoveredIndex <= EscapedObjectCount)) { CheckFailed
("all indices passed to llvm.localrecover must be less than the "
"number of arguments passed to llvm.localescape in the parent "
"function", F); return; } } while (false)
2243 "function",do { if (!(MaxRecoveredIndex <= EscapedObjectCount)) { CheckFailed
("all indices passed to llvm.localrecover must be less than the "
"number of arguments passed to llvm.localescape in the parent "
"function", F); return; } } while (false)
2244 F)do { if (!(MaxRecoveredIndex <= EscapedObjectCount)) { CheckFailed
("all indices passed to llvm.localrecover must be less than the "
"number of arguments passed to llvm.localescape in the parent "
"function", F); return; } } while (false)
;
2245 }
2246}
2247
2248static Instruction *getSuccPad(Instruction *Terminator) {
2249 BasicBlock *UnwindDest;
2250 if (auto *II = dyn_cast<InvokeInst>(Terminator))
2251 UnwindDest = II->getUnwindDest();
2252 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2253 UnwindDest = CSI->getUnwindDest();
2254 else
2255 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2256 return UnwindDest->getFirstNonPHI();
2257}
2258
2259void Verifier::verifySiblingFuncletUnwinds() {
2260 SmallPtrSet<Instruction *, 8> Visited;
2261 SmallPtrSet<Instruction *, 8> Active;
2262 for (const auto &Pair : SiblingFuncletInfo) {
2263 Instruction *PredPad = Pair.first;
2264 if (Visited.count(PredPad))
2265 continue;
2266 Active.insert(PredPad);
2267 Instruction *Terminator = Pair.second;
2268 do {
2269 Instruction *SuccPad = getSuccPad(Terminator);
2270 if (Active.count(SuccPad)) {
2271 // Found a cycle; report error
2272 Instruction *CyclePad = SuccPad;
2273 SmallVector<Instruction *, 8> CycleNodes;
2274 do {
2275 CycleNodes.push_back(CyclePad);
2276 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2277 if (CycleTerminator != CyclePad)
2278 CycleNodes.push_back(CycleTerminator);
2279 CyclePad = getSuccPad(CycleTerminator);
2280 } while (CyclePad != SuccPad);
2281 Assert(false, "EH pads can't handle each other's exceptions",do { if (!(false)) { CheckFailed("EH pads can't handle each other's exceptions"
, ArrayRef<Instruction *>(CycleNodes)); return; } } while
(false)
2282 ArrayRef<Instruction *>(CycleNodes))do { if (!(false)) { CheckFailed("EH pads can't handle each other's exceptions"
, ArrayRef<Instruction *>(CycleNodes)); return; } } while
(false)
;
2283 }
2284 // Don't re-walk a node we've already checked
2285 if (!Visited.insert(SuccPad).second)
2286 break;
2287 // Walk to this successor if it has a map entry.
2288 PredPad = SuccPad;
2289 auto TermI = SiblingFuncletInfo.find(PredPad);
2290 if (TermI == SiblingFuncletInfo.end())
2291 break;
2292 Terminator = TermI->second;
2293 Active.insert(PredPad);
2294 } while (true);
2295 // Each node only has one successor, so we've walked all the active
2296 // nodes' successors.
2297 Active.clear();
2298 }
2299}
2300
2301// visitFunction - Verify that a function is ok.
2302//
2303void Verifier::visitFunction(const Function &F) {
2304 visitGlobalValue(F);
2305
2306 // Check function arguments.
2307 FunctionType *FT = F.getFunctionType();
2308 unsigned NumArgs = F.arg_size();
2309
2310 Assert(&Context == &F.getContext(),do { if (!(&Context == &F.getContext())) { CheckFailed
("Function context does not match Module context!", &F); return
; } } while (false)
2311 "Function context does not match Module context!", &F)do { if (!(&Context == &F.getContext())) { CheckFailed
("Function context does not match Module context!", &F); return
; } } while (false)
;
2312
2313 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F)do { if (!(!F.hasCommonLinkage())) { CheckFailed("Functions may not have common linkage"
, &F); return; } } while (false)
;
2314 Assert(FT->getNumParams() == NumArgs,do { if (!(FT->getNumParams() == NumArgs)) { CheckFailed("# formal arguments must match # of arguments for function type!"
, &F, FT); return; } } while (false)
2315 "# formal arguments must match # of arguments for function type!", &F,do { if (!(FT->getNumParams() == NumArgs)) { CheckFailed("# formal arguments must match # of arguments for function type!"
, &F, FT); return; } } while (false)
2316 FT)do { if (!(FT->getNumParams() == NumArgs)) { CheckFailed("# formal arguments must match # of arguments for function type!"
, &F, FT); return; } } while (false)
;
2317 Assert(F.getReturnType()->isFirstClassType() ||do { if (!(F.getReturnType()->isFirstClassType() || F.getReturnType
()->isVoidTy() || F.getReturnType()->isStructTy())) { CheckFailed
("Functions cannot return aggregate values!", &F); return
; } } while (false)
2318 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),do { if (!(F.getReturnType()->isFirstClassType() || F.getReturnType
()->isVoidTy() || F.getReturnType()->isStructTy())) { CheckFailed
("Functions cannot return aggregate values!", &F); return
; } } while (false)
2319 "Functions cannot return aggregate values!", &F)do { if (!(F.getReturnType()->isFirstClassType() || F.getReturnType
()->isVoidTy() || F.getReturnType()->isStructTy())) { CheckFailed
("Functions cannot return aggregate values!", &F); return
; } } while (false)
;
2320
2321 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),do { if (!(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy
())) { CheckFailed("Invalid struct return type!", &F); return
; } } while (false)
2322 "Invalid struct return type!", &F)do { if (!(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy
())) { CheckFailed("Invalid struct return type!", &F); return
; } } while (false)
;
2323
2324 AttributeList Attrs = F.getAttributes();
2325
2326 Assert(verifyAttributeCount(Attrs, FT->getNumParams()),do { if (!(verifyAttributeCount(Attrs, FT->getNumParams())
)) { CheckFailed("Attribute after last parameter!", &F); return
; } } while (false)
2327 "Attribute after last parameter!", &F)do { if (!(verifyAttributeCount(Attrs, FT->getNumParams())
)) { CheckFailed("Attribute after last parameter!", &F); return
; } } while (false)
;
2328
2329 bool IsIntrinsic = F.isIntrinsic();
2330
2331 // Check function attributes.
2332 verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic);
2333
2334 // On function declarations/definitions, we do not support the builtin
2335 // attribute. We do not check this in VerifyFunctionAttrs since that is
2336 // checking for Attributes that can/can not ever be on functions.
2337 Assert(!Attrs.hasFnAttribute(Attribute::Builtin),do { if (!(!Attrs.hasFnAttribute(Attribute::Builtin))) { CheckFailed
("Attribute 'builtin' can only be applied to a callsite.", &
F); return; } } while (false)
2338 "Attribute 'builtin' can only be applied to a callsite.", &F)do { if (!(!Attrs.hasFnAttribute(Attribute::Builtin))) { CheckFailed
("Attribute 'builtin' can only be applied to a callsite.", &
F); return; } } while (false)
;
2339
2340 Assert(!Attrs.hasAttrSomewhere(Attribute::ElementType),do { if (!(!Attrs.hasAttrSomewhere(Attribute::ElementType))) {
CheckFailed("Attribute 'elementtype' can only be applied to a callsite."
, &F); return; } } while (false)
2341 "Attribute 'elementtype' can only be applied to a callsite.", &F)do { if (!(!Attrs.hasAttrSomewhere(Attribute::ElementType))) {
CheckFailed("Attribute 'elementtype' can only be applied to a callsite."
, &F); return; } } while (false)
;
2342
2343 // Check that this function meets the restrictions on this calling convention.
2344 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2345 // restrictions can be lifted.
2346 switch (F.getCallingConv()) {
2347 default:
2348 case CallingConv::C:
2349 break;
2350 case CallingConv::X86_INTR: {
2351 Assert(F.arg_empty() || Attrs.hasParamAttribute(0, Attribute::ByVal),do { if (!(F.arg_empty() || Attrs.hasParamAttribute(0, Attribute
::ByVal))) { CheckFailed("Calling convention parameter requires byval"
, &F); return; } } while (false)
2352 "Calling convention parameter requires byval", &F)do { if (!(F.arg_empty() || Attrs.hasParamAttribute(0, Attribute
::ByVal))) { CheckFailed("Calling convention parameter requires byval"
, &F); return; } } while (false)
;
2353 break;
2354 }
2355 case CallingConv::AMDGPU_KERNEL:
2356 case CallingConv::SPIR_KERNEL:
2357 Assert(F.getReturnType()->isVoidTy(),do { if (!(F.getReturnType()->isVoidTy())) { CheckFailed("Calling convention requires void return type"
, &F); return; } } while (false)
2358 "Calling convention requires void return type", &F)do { if (!(F.getReturnType()->isVoidTy())) { CheckFailed("Calling convention requires void return type"
, &F); return; } } while (false)
;
2359 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2360 case CallingConv::AMDGPU_VS:
2361 case CallingConv::AMDGPU_HS:
2362 case CallingConv::AMDGPU_GS:
2363 case CallingConv::AMDGPU_PS:
2364 case CallingConv::AMDGPU_CS:
2365 Assert(!F.hasStructRetAttr(),do { if (!(!F.hasStructRetAttr())) { CheckFailed("Calling convention does not allow sret"
, &F); return; } } while (false)
2366 "Calling convention does not allow sret", &F)do { if (!(!F.hasStructRetAttr())) { CheckFailed("Calling convention does not allow sret"
, &F); return; } } while (false)
;
2367 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2368 const unsigned StackAS = DL.getAllocaAddrSpace();
2369 unsigned i = 0;
2370 for (const Argument &Arg : F.args()) {
2371 Assert(!Attrs.hasParamAttribute(i, Attribute::ByVal),do { if (!(!Attrs.hasParamAttribute(i, Attribute::ByVal))) { CheckFailed
("Calling convention disallows byval", &F); return; } } while
(false)
2372 "Calling convention disallows byval", &F)do { if (!(!Attrs.hasParamAttribute(i, Attribute::ByVal))) { CheckFailed
("Calling convention disallows byval", &F); return; } } while
(false)
;
2373 Assert(!Attrs.hasParamAttribute(i, Attribute::Preallocated),do { if (!(!Attrs.hasParamAttribute(i, Attribute::Preallocated
))) { CheckFailed("Calling convention disallows preallocated"
, &F); return; } } while (false)
2374 "Calling convention disallows preallocated", &F)do { if (!(!Attrs.hasParamAttribute(i, Attribute::Preallocated
))) { CheckFailed("Calling convention disallows preallocated"
, &F); return; } } while (false)
;
2375 Assert(!Attrs.hasParamAttribute(i, Attribute::InAlloca),do { if (!(!Attrs.hasParamAttribute(i, Attribute::InAlloca)))
{ CheckFailed("Calling convention disallows inalloca", &
F); return; } } while (false)
2376 "Calling convention disallows inalloca", &F)do { if (!(!Attrs.hasParamAttribute(i, Attribute::InAlloca)))
{ CheckFailed("Calling convention disallows inalloca", &
F); return; } } while (false)
;
2377
2378 if (Attrs.hasParamAttribute(i, Attribute::ByRef)) {
2379 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2380 // value here.
2381 Assert(Arg.getType()->getPointerAddressSpace() != StackAS,do { if (!(Arg.getType()->getPointerAddressSpace() != StackAS
)) { CheckFailed("Calling convention disallows stack byref", &
F); return; } } while (false)
2382 "Calling convention disallows stack byref", &F)do { if (!(Arg.getType()->getPointerAddressSpace() != StackAS
)) { CheckFailed("Calling convention disallows stack byref", &
F); return; } } while (false)
;
2383 }
2384
2385 ++i;
2386 }
2387 }
2388
2389 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2390 case CallingConv::Fast:
2391 case CallingConv::Cold:
2392 case CallingConv::Intel_OCL_BI:
2393 case CallingConv::PTX_Kernel:
2394 case CallingConv::PTX_Device:
2395 Assert(!F.isVarArg(), "Calling convention does not support varargs or "do { if (!(!F.isVarArg())) { CheckFailed("Calling convention does not support varargs or "
"perfect forwarding!", &F); return; } } while (false)
2396 "perfect forwarding!",do { if (!(!F.isVarArg())) { CheckFailed("Calling convention does not support varargs or "
"perfect forwarding!", &F); return; } } while (false)
2397 &F)do { if (!(!F.isVarArg())) { CheckFailed("Calling convention does not support varargs or "
"perfect forwarding!", &F); return; } } while (false)
;
2398 break;
2399 }
2400
2401 // Check that the argument values match the function type for this function...
2402 unsigned i = 0;
2403 for (const Argument &Arg : F.args()) {
2404 Assert(Arg.getType() == FT->getParamType(i),do { if (!(Arg.getType() == FT->getParamType(i))) { CheckFailed
("Argument value does not match function argument type!", &
Arg, FT->getParamType(i)); return; } } while (false)
2405 "Argument value does not match function argument type!", &Arg,do { if (!(Arg.getType() == FT->getParamType(i))) { CheckFailed
("Argument value does not match function argument type!", &
Arg, FT->getParamType(i)); return; } } while (false)
2406 FT->getParamType(i))do { if (!(Arg.getType() == FT->getParamType(i))) { CheckFailed
("Argument value does not match function argument type!", &
Arg, FT->getParamType(i)); return; } } while (false)
;
2407 Assert(Arg.getType()->isFirstClassType(),do { if (!(Arg.getType()->isFirstClassType())) { CheckFailed
("Function arguments must have first-class types!", &Arg)
; return; } } while (false)
2408 "Function arguments must have first-class types!", &Arg)do { if (!(Arg.getType()->isFirstClassType())) { CheckFailed
("Function arguments must have first-class types!", &Arg)
; return; } } while (false)
;
2409 if (!IsIntrinsic) {
2410 Assert(!Arg.getType()->isMetadataTy(),do { if (!(!Arg.getType()->isMetadataTy())) { CheckFailed(
"Function takes metadata but isn't an intrinsic", &Arg, &
F); return; } } while (false)
2411 "Function takes metadata but isn't an intrinsic", &Arg, &F)do { if (!(!Arg.getType()->isMetadataTy())) { CheckFailed(
"Function takes metadata but isn't an intrinsic", &Arg, &
F); return; } } while (false)
;
2412 Assert(!Arg.getType()->isTokenTy(),do { if (!(!Arg.getType()->isTokenTy())) { CheckFailed("Function takes token but isn't an intrinsic"
, &Arg, &F); return; } } while (false)
2413 "Function takes token but isn't an intrinsic", &Arg, &F)do { if (!(!Arg.getType()->isTokenTy())) { CheckFailed("Function takes token but isn't an intrinsic"
, &Arg, &F); return; } } while (false)
;
2414 Assert(!Arg.getType()->isX86_AMXTy(),do { if (!(!Arg.getType()->isX86_AMXTy())) { CheckFailed("Function takes x86_amx but isn't an intrinsic"
, &Arg, &F); return; } } while (false)
2415 "Function takes x86_amx but isn't an intrinsic", &Arg, &F)do { if (!(!Arg.getType()->isX86_AMXTy())) { CheckFailed("Function takes x86_amx but isn't an intrinsic"
, &Arg, &F); return; } } while (false)
;
2416 }
2417
2418 // Check that swifterror argument is only used by loads and stores.
2419 if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) {
2420 verifySwiftErrorValue(&Arg);
2421 }
2422 ++i;
2423 }
2424
2425 if (!IsIntrinsic) {
2426 Assert(!F.getReturnType()->isTokenTy(),do { if (!(!F.getReturnType()->isTokenTy())) { CheckFailed
("Function returns a token but isn't an intrinsic", &F); return
; } } while (false)
2427 "Function returns a token but isn't an intrinsic", &F)do { if (!(!F.getReturnType()->isTokenTy())) { CheckFailed
("Function returns a token but isn't an intrinsic", &F); return
; } } while (false)
;
2428 Assert(!F.getReturnType()->isX86_AMXTy(),do { if (!(!F.getReturnType()->isX86_AMXTy())) { CheckFailed
("Function returns a x86_amx but isn't an intrinsic", &F)
; return; } } while (false)
2429 "Function returns a x86_amx but isn't an intrinsic", &F)do { if (!(!F.getReturnType()->isX86_AMXTy())) { CheckFailed
("Function returns a x86_amx but isn't an intrinsic", &F)
; return; } } while (false)
;
2430 }
2431
2432 // Get the function metadata attachments.
2433 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2434 F.getAllMetadata(MDs);
2435 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync")((void)0);
2436 verifyFunctionMetadata(MDs);
2437
2438 // Check validity of the personality function
2439 if (F.hasPersonalityFn()) {
2440 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2441 if (Per)
2442 Assert(Per->getParent() == F.getParent(),do { if (!(Per->getParent() == F.getParent())) { CheckFailed
("Referencing personality function in another module!", &
F, F.getParent(), Per, Per->getParent()); return; } } while
(false)
2443 "Referencing personality function in another module!",do { if (!(Per->getParent() == F.getParent())) { CheckFailed
("Referencing personality function in another module!", &
F, F.getParent(), Per, Per->getParent()); return; } } while
(false)
2444 &F, F.getParent(), Per, Per->getParent())do { if (!(Per->getParent() == F.getParent())) { CheckFailed
("Referencing personality function in another module!", &
F, F.getParent(), Per, Per->getParent()); return; } } while
(false)
;
2445 }
2446
2447 if (F.isMaterializable()) {
2448 // Function has a body somewhere we can't see.
2449 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,do { if (!(MDs.empty())) { CheckFailed("unmaterialized function cannot have metadata"
, &F, MDs.empty() ? nullptr : MDs.front().second); return
; } } while (false)
2450 MDs.empty() ? nullptr : MDs.front().second)do { if (!(MDs.empty())) { CheckFailed("unmaterialized function cannot have metadata"
, &F, MDs.empty() ? nullptr : MDs.front().second); return
; } } while (false)
;
2451 } else if (F.isDeclaration()) {
2452 for (const auto &I : MDs) {
2453 // This is used for call site debug information.
2454 AssertDI(I.first != LLVMContext::MD_dbg ||do { if (!(I.first != LLVMContext::MD_dbg || !cast<DISubprogram
>(I.second)->isDistinct())) { DebugInfoCheckFailed("function declaration may only have a unique !dbg attachment"
, &F); return; } } while (false)
2455 !cast<DISubprogram>(I.second)->isDistinct(),do { if (!(I.first != LLVMContext::MD_dbg || !cast<DISubprogram
>(I.second)->isDistinct())) { DebugInfoCheckFailed("function declaration may only have a unique !dbg attachment"
, &F); return; } } while (false)
2456 "function declaration may only have a unique !dbg attachment",do { if (!(I.first != LLVMContext::MD_dbg || !cast<DISubprogram
>(I.second)->isDistinct())) { DebugInfoCheckFailed("function declaration may only have a unique !dbg attachment"
, &F); return; } } while (false)
2457 &F)do { if (!(I.first != LLVMContext::MD_dbg || !cast<DISubprogram
>(I.second)->isDistinct())) { DebugInfoCheckFailed("function declaration may only have a unique !dbg attachment"
, &F); return; } } while (false)
;
2458 Assert(I.first != LLVMContext::MD_prof,do { if (!(I.first != LLVMContext::MD_prof)) { CheckFailed("function declaration may not have a !prof attachment"
, &F); return; } } while (false)
2459 "function declaration may not have a !prof attachment", &F)do { if (!(I.first != LLVMContext::MD_prof)) { CheckFailed("function declaration may not have a !prof attachment"
, &F); return; } } while (false)
;
2460
2461 // Verify the metadata itself.
2462 visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
2463 }
2464 Assert(!F.hasPersonalityFn(),do { if (!(!F.hasPersonalityFn())) { CheckFailed("Function declaration shouldn't have a personality routine"
, &F); return; } } while (false)
2465 "Function declaration shouldn't have a personality routine", &F)do { if (!(!F.hasPersonalityFn())) { CheckFailed("Function declaration shouldn't have a personality routine"
, &F); return; } } while (false)
;
2466 } else {
2467 // Verify that this function (which has a body) is not named "llvm.*". It
2468 // is not legal to define intrinsics.
2469 Assert(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F)do { if (!(!IsIntrinsic)) { CheckFailed("llvm intrinsics cannot be defined!"
, &F); return; } } while (false)
;
2470
2471 // Check the entry node
2472 const BasicBlock *Entry = &F.getEntryBlock();
2473 Assert(pred_empty(Entry),do { if (!(pred_empty(Entry))) { CheckFailed("Entry block to function must not have predecessors!"
, Entry); return; } } while (false)
2474 "Entry block to function must not have predecessors!", Entry)do { if (!(pred_empty(Entry))) { CheckFailed("Entry block to function must not have predecessors!"
, Entry); return; } } while (false)
;
2475
2476 // The address of the entry block cannot be taken, unless it is dead.
2477 if (Entry->hasAddressTaken()) {
2478 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),do { if (!(!BlockAddress::lookup(Entry)->isConstantUsed())
) { CheckFailed("blockaddress may not be used with the entry block!"
, Entry); return; } } while (false)
2479 "blockaddress may not be used with the entry block!", Entry)do { if (!(!BlockAddress::lookup(Entry)->isConstantUsed())
) { CheckFailed("blockaddress may not be used with the entry block!"
, Entry); return; } } while (false)
;
2480 }
2481
2482 unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
2483 // Visit metadata attachments.
2484 for (const auto &I : MDs) {
2485 // Verify that the attachment is legal.
2486 auto AllowLocs = AreDebugLocsAllowed::No;
2487 switch (I.first) {
2488 default:
2489 break;
2490 case LLVMContext::MD_dbg: {
2491 ++NumDebugAttachments;
2492 AssertDI(NumDebugAttachments == 1,do { if (!(NumDebugAttachments == 1)) { DebugInfoCheckFailed(
"function must have a single !dbg attachment", &F, I.second
); return; } } while (false)
2493 "function must have a single !dbg attachment", &F, I.second)do { if (!(NumDebugAttachments == 1)) { DebugInfoCheckFailed(
"function must have a single !dbg attachment", &F, I.second
); return; } } while (false)
;
2494 AssertDI(isa<DISubprogram>(I.second),do { if (!(isa<DISubprogram>(I.second))) { DebugInfoCheckFailed
("function !dbg attachment must be a subprogram", &F, I.second
); return; } } while (false)
2495 "function !dbg attachment must be a subprogram", &F, I.second)do { if (!(isa<DISubprogram>(I.second))) { DebugInfoCheckFailed
("function !dbg attachment must be a subprogram", &F, I.second
); return; } } while (false)
;
2496 AssertDI(cast<DISubprogram>(I.second)->isDistinct(),do { if (!(cast<DISubprogram>(I.second)->isDistinct(
))) { DebugInfoCheckFailed("function definition may only have a distinct !dbg attachment"
, &F); return; } } while (false)
2497 "function definition may only have a distinct !dbg attachment",do { if (!(cast<DISubprogram>(I.second)->isDistinct(
))) { DebugInfoCheckFailed("function definition may only have a distinct !dbg attachment"
, &F); return; } } while (false)
2498 &F)do { if (!(cast<DISubprogram>(I.second)->isDistinct(
))) { DebugInfoCheckFailed("function definition may only have a distinct !dbg attachment"
, &F); return; } } while (false)
;
2499
2500 auto *SP = cast<DISubprogram>(I.second);
2501 const Function *&AttachedTo = DISubprogramAttachments[SP];
2502 AssertDI(!AttachedTo || AttachedTo == &F,do { if (!(!AttachedTo || AttachedTo == &F)) { DebugInfoCheckFailed
("DISubprogram attached to more than one function", SP, &
F); return; } } while (false)
2503 "DISubprogram attached to more than one function", SP, &F)do { if (!(!AttachedTo || AttachedTo == &F)) { DebugInfoCheckFailed
("DISubprogram attached to more than one function", SP, &
F); return; } } while (false)
;
2504 AttachedTo = &F;
2505 AllowLocs = AreDebugLocsAllowed::Yes;
2506 break;
2507 }
2508 case LLVMContext::MD_prof:
2509 ++NumProfAttachments;
2510 Assert(NumProfAttachments == 1,do { if (!(NumProfAttachments == 1)) { CheckFailed("function must have a single !prof attachment"
, &F, I.second); return; } } while (false)
2511 "function must have a single !prof attachment", &F, I.second)do { if (!(NumProfAttachments == 1)) { CheckFailed("function must have a single !prof attachment"
, &F, I.second); return; } } while (false)
;
2512 break;
2513 }
2514
2515 // Verify the metadata itself.
2516 visitMDNode(*I.second, AllowLocs);
2517 }
2518 }
2519
2520 // If this function is actually an intrinsic, verify that it is only used in
2521 // direct call/invokes, never having its "address taken".
2522 // Only do this if the module is materialized, otherwise we don't have all the
2523 // uses.
2524 if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
2525 const User *U;
2526 if (F.hasAddressTaken(&U))
2527 Assert(false, "Invalid user of intrinsic instruction!", U)do { if (!(false)) { CheckFailed("Invalid user of intrinsic instruction!"
, U); return; } } while (false)
;
2528 }
2529
2530 // Check intrinsics' signatures.
2531 switch (F.getIntrinsicID()) {
2532 case Intrinsic::experimental_gc_get_pointer_base: {
2533 FunctionType *FT = F.getFunctionType();
2534 Assert(FT->getNumParams() == 1, "wrong number of parameters", F)do { if (!(FT->getNumParams() == 1)) { CheckFailed("wrong number of parameters"
, F); return; } } while (false)
;
2535 Assert(isa<PointerType>(F.getReturnType()),do { if (!(isa<PointerType>(F.getReturnType()))) { CheckFailed
("gc.get.pointer.base must return a pointer", F); return; } }
while (false)
2536 "gc.get.pointer.base must return a pointer", F)do { if (!(isa<PointerType>(F.getReturnType()))) { CheckFailed
("gc.get.pointer.base must return a pointer", F); return; } }
while (false)
;
2537 Assert(FT->getParamType(0) == F.getReturnType(),do { if (!(FT->getParamType(0) == F.getReturnType())) { CheckFailed
("gc.get.pointer.base operand and result must be of the same type"
, F); return; } } while (false)
2538 "gc.get.pointer.base operand and result must be of the same type",do { if (!(FT->getParamType(0) == F.getReturnType())) { CheckFailed
("gc.get.pointer.base operand and result must be of the same type"
, F); return; } } while (false)
2539 F)do { if (!(FT->getParamType(0) == F.getReturnType())) { CheckFailed
("gc.get.pointer.base operand and result must be of the same type"
, F); return; } } while (false)
;
2540 break;
2541 }
2542 case Intrinsic::experimental_gc_get_pointer_offset: {
2543 FunctionType *FT = F.getFunctionType();
2544 Assert(FT->getNumParams() == 1, "wrong number of parameters", F)do { if (!(FT->getNumParams() == 1)) { CheckFailed("wrong number of parameters"
, F); return; } } while (false)
;
2545 Assert(isa<PointerType>(FT->getParamType(0)),do { if (!(isa<PointerType>(FT->getParamType(0)))) {
CheckFailed("gc.get.pointer.offset operand must be a pointer"
, F); return; } } while (false)
2546 "gc.get.pointer.offset operand must be a pointer", F)do { if (!(isa<PointerType>(FT->getParamType(0)))) {
CheckFailed("gc.get.pointer.offset operand must be a pointer"
, F); return; } } while (false)
;
2547 Assert(F.getReturnType()->isIntegerTy(),do { if (!(F.getReturnType()->isIntegerTy())) { CheckFailed
("gc.get.pointer.offset must return integer", F); return; } }
while (false)
2548 "gc.get.pointer.offset must return integer", F)do { if (!(F.getReturnType()->isIntegerTy())) { CheckFailed
("gc.get.pointer.offset must return integer", F); return; } }
while (false)
;
2549 break;
2550 }
2551 }
2552
2553 auto *N = F.getSubprogram();
2554 HasDebugInfo = (N != nullptr);
2555 if (!HasDebugInfo)
2556 return;
2557
2558 // Check that all !dbg attachments lead to back to N.
2559 //
2560 // FIXME: Check this incrementally while visiting !dbg attachments.
2561 // FIXME: Only check when N is the canonical subprogram for F.
2562 SmallPtrSet<const MDNode *, 32> Seen;
2563 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
2564 // Be careful about using DILocation here since we might be dealing with
2565 // broken code (this is the Verifier after all).
2566 const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
2567 if (!DL)
2568 return;
2569 if (!Seen.insert(DL).second)
2570 return;
2571
2572 Metadata *Parent = DL->getRawScope();
2573 AssertDI(Parent && isa<DILocalScope>(Parent),do { if (!(Parent && isa<DILocalScope>(Parent))
) { DebugInfoCheckFailed("DILocation's scope must be a DILocalScope"
, N, &F, &I, DL, Parent); return; } } while (false)
2574 "DILocation's scope must be a DILocalScope", N, &F, &I, DL,do { if (!(Parent && isa<DILocalScope>(Parent))
) { DebugInfoCheckFailed("DILocation's scope must be a DILocalScope"
, N, &F, &I, DL, Parent); return; } } while (false)
2575 Parent)do { if (!(Parent && isa<DILocalScope>(Parent))
) { DebugInfoCheckFailed("DILocation's scope must be a DILocalScope"
, N, &F, &I, DL, Parent); return; } } while (false)
;
2576
2577 DILocalScope *Scope = DL->getInlinedAtScope();
2578 Assert(Scope, "Failed to find DILocalScope", DL)do { if (!(Scope)) { CheckFailed("Failed to find DILocalScope"
, DL); return; } } while (false)
;
2579
2580 if (!Seen.insert(Scope).second)
2581 return;
2582
2583 DISubprogram *SP = Scope->getSubprogram();
2584
2585 // Scope and SP could be the same MDNode and we don't want to skip
2586 // validation in that case
2587 if (SP && ((Scope != SP) && !Seen.insert(SP).second))
2588 return;
2589
2590 AssertDI(SP->describes(&F),do { if (!(SP->describes(&F))) { DebugInfoCheckFailed(
"!dbg attachment points at wrong subprogram for function", N,
&F, &I, DL, Scope, SP); return; } } while (false)
2591 "!dbg attachment points at wrong subprogram for function", N, &F,do { if (!(SP->describes(&F))) { DebugInfoCheckFailed(
"!dbg attachment points at wrong subprogram for function", N,
&F, &I, DL, Scope, SP); return; } } while (false)
2592 &I, DL, Scope, SP)do { if (!(SP->describes(&F))) { DebugInfoCheckFailed(
"!dbg attachment points at wrong subprogram for function", N,
&F, &I, DL, Scope, SP); return; } } while (false)
;
2593 };
2594 for (auto &BB : F)
2595 for (auto &I : BB) {
2596 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
2597 // The llvm.loop annotations also contain two DILocations.
2598 if (auto MD = I.getMetadata(LLVMContext::MD_loop))
2599 for (unsigned i = 1; i < MD->getNumOperands(); ++i)
2600 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
2601 if (BrokenDebugInfo)
2602 return;
2603 }
2604}
2605
2606// verifyBasicBlock - Verify that a basic block is well formed...
2607//
2608void Verifier::visitBasicBlock(BasicBlock &BB) {
2609 InstsInThisBlock.clear();
2610
2611 // Ensure that basic blocks have terminators!
2612 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB)do { if (!(BB.getTerminator())) { CheckFailed("Basic Block does not have terminator!"
, &BB); return; } } while (false)
;
2613
2614 // Check constraints that this basic block imposes on all of the PHI nodes in
2615 // it.
2616 if (isa<PHINode>(BB.front())) {
2617 SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
2618 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
2619 llvm::sort(Preds);
2620 for (const PHINode &PN : BB.phis()) {
2621 Assert(PN.getNumIncomingValues() == Preds.size(),do { if (!(PN.getNumIncomingValues() == Preds.size())) { CheckFailed
("PHINode should have one entry for each predecessor of its "
"parent basic block!", &PN); return; } } while (false)
2622 "PHINode should have one entry for each predecessor of its "do { if (!(PN.getNumIncomingValues() == Preds.size())) { CheckFailed
("PHINode should have one entry for each predecessor of its "
"parent basic block!", &PN); return; } } while (false)
2623 "parent basic block!",do { if (!(PN.getNumIncomingValues() == Preds.size())) { CheckFailed
("PHINode should have one entry for each predecessor of its "
"parent basic block!", &PN); return; } } while (false)
2624 &PN)do { if (!(PN.getNumIncomingValues() == Preds.size())) { CheckFailed
("PHINode should have one entry for each predecessor of its "
"parent basic block!", &PN); return; } } while (false)
;
2625
2626 // Get and sort all incoming values in the PHI node...
2627 Values.clear();
2628 Values.reserve(PN.getNumIncomingValues());
2629 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2630 Values.push_back(
2631 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2632 llvm::sort(Values);
2633
2634 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2635 // Check to make sure that if there is more than one entry for a
2636 // particular basic block in this PHI node, that the incoming values are
2637 // all identical.
2638 //
2639 Assert(i == 0 || Values[i].first != Values[i - 1].first ||do { if (!(i == 0 || Values[i].first != Values[i - 1].first ||
Values[i].second == Values[i - 1].second)) { CheckFailed("PHI node has multiple entries for the same basic block with "
"different incoming values!", &PN, Values[i].first, Values
[i].second, Values[i - 1].second); return; } } while (false)
2640 Values[i].second == Values[i - 1].second,do { if (!(i == 0 || Values[i].first != Values[i - 1].first ||
Values[i].second == Values[i - 1].second)) { CheckFailed("PHI node has multiple entries for the same basic block with "
"different incoming values!", &PN, Values[i].first, Values
[i].second, Values[i - 1].second); return; } } while (false)
2641 "PHI node has multiple entries for the same basic block with "do { if (!(i == 0 || Values[i].first != Values[i - 1].first ||
Values[i].second == Values[i - 1].second)) { CheckFailed("PHI node has multiple entries for the same basic block with "
"different incoming values!", &PN, Values[i].first, Values
[i].second, Values[i - 1].second); return; } } while (false)
2642 "different incoming values!",do { if (!(i == 0 || Values[i].first != Values[i - 1].first ||
Values[i].second == Values[i - 1].second)) { CheckFailed("PHI node has multiple entries for the same basic block with "
"different incoming values!", &PN, Values[i].first, Values
[i].second, Values[i - 1].second); return; } } while (false)
2643 &PN, Values[i].first, Values[i].second, Values[i - 1].second)do { if (!(i == 0 || Values[i].first != Values[i - 1].first ||
Values[i].second == Values[i - 1].second)) { CheckFailed("PHI node has multiple entries for the same basic block with "
"different incoming values!", &PN, Values[i].first, Values
[i].second, Values[i - 1].second); return; } } while (false)
;
2644
2645 // Check to make sure that the predecessors and PHI node entries are
2646 // matched up.
2647 Assert(Values[i].first == Preds[i],do { if (!(Values[i].first == Preds[i])) { CheckFailed("PHI node entries do not match predecessors!"
, &PN, Values[i].first, Preds[i]); return; } } while (false
)
2648 "PHI node entries do not match predecessors!", &PN,do { if (!(Values[i].first == Preds[i])) { CheckFailed("PHI node entries do not match predecessors!"
, &PN, Values[i].first, Preds[i]); return; } } while (false
)
2649 Values[i].first, Preds[i])do { if (!(Values[i].first == Preds[i])) { CheckFailed("PHI node entries do not match predecessors!"
, &PN, Values[i].first, Preds[i]); return; } } while (false
)
;
2650 }
2651 }
2652 }
2653
2654 // Check that all instructions have their parent pointers set up correctly.
2655 for (auto &I : BB)
2656 {
2657 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!")do { if (!(I.getParent() == &BB)) { CheckFailed("Instruction has bogus parent pointer!"
); return; } } while (false)
;
2658 }
2659}
2660
2661void Verifier::visitTerminator(Instruction &I) {
2662 // Ensure that terminators only exist at the end of the basic block.
2663 Assert(&I == I.getParent()->getTerminator(),do { if (!(&I == I.getParent()->getTerminator())) { CheckFailed
("Terminator found in the middle of a basic block!", I.getParent
()); return; } } while (false)
2664 "Terminator found in the middle of a basic block!", I.getParent())do { if (!(&I == I.getParent()->getTerminator())) { CheckFailed
("Terminator found in the middle of a basic block!", I.getParent
()); return; } } while (false)
;
2665 visitInstruction(I);
2666}
2667
2668void Verifier::visitBranchInst(BranchInst &BI) {
2669 if (BI.isConditional()) {
2670 Assert(BI.getCondition()->getType()->isIntegerTy(1),do { if (!(BI.getCondition()->getType()->isIntegerTy(1)
)) { CheckFailed("Branch condition is not 'i1' type!", &BI
, BI.getCondition()); return; } } while (false)
2671 "Branch condition is not 'i1' type!", &BI, BI.getCondition())do { if (!(BI.getCondition()->getType()->isIntegerTy(1)
)) { CheckFailed("Branch condition is not 'i1' type!", &BI
, BI.getCondition()); return; } } while (false)
;
2672 }
2673 visitTerminator(BI);
2674}
2675
2676void Verifier::visitReturnInst(ReturnInst &RI) {
2677 Function *F = RI.getParent()->getParent();
2678 unsigned N = RI.getNumOperands();
2679 if (F->getReturnType()->isVoidTy())
2680 Assert(N == 0,do { if (!(N == 0)) { CheckFailed("Found return instr that returns non-void in Function of void "
"return type!", &RI, F->getReturnType()); return; } }
while (false)
2681 "Found return instr that returns non-void in Function of void "do { if (!(N == 0)) { CheckFailed("Found return instr that returns non-void in Function of void "
"return type!", &RI, F->getReturnType()); return; } }
while (false)
2682 "return type!",do { if (!(N == 0)) { CheckFailed("Found return instr that returns non-void in Function of void "
"return type!", &RI, F->getReturnType()); return; } }
while (false)
2683 &RI, F->getReturnType())do { if (!(N == 0)) { CheckFailed("Found return instr that returns non-void in Function of void "
"return type!", &RI, F->getReturnType()); return; } }
while (false)
;
2684 else
2685 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),do { if (!(N == 1 && F->getReturnType() == RI.getOperand
(0)->getType())) { CheckFailed("Function return type does not match operand "
"type of return inst!", &RI, F->getReturnType()); return
; } } while (false)
2686 "Function return type does not match operand "do { if (!(N == 1 && F->getReturnType() == RI.getOperand
(0)->getType())) { CheckFailed("Function return type does not match operand "
"type of return inst!", &RI, F->getReturnType()); return
; } } while (false)
2687 "type of return inst!",do { if (!(N == 1 && F->getReturnType() == RI.getOperand
(0)->getType())) { CheckFailed("Function return type does not match operand "
"type of return inst!", &RI, F->getReturnType()); return
; } } while (false)
2688 &RI, F->getReturnType())do { if (!(N == 1 && F->getReturnType() == RI.getOperand
(0)->getType())) { CheckFailed("Function return type does not match operand "
"type of return inst!", &RI, F->getReturnType()); return
; } } while (false)
;
2689
2690 // Check to make sure that the return value has necessary properties for
2691 // terminators...
2692 visitTerminator(RI);
2693}
2694
2695void Verifier::visitSwitchInst(SwitchInst &SI) {
2696 // Check to make sure that all of the constants in the switch instruction
2697 // have the same type as the switched-on value.
2698 Type *SwitchTy = SI.getCondition()->getType();
2699 SmallPtrSet<ConstantInt*, 32> Constants;
2700 for (auto &Case : SI.cases()) {
2701 Assert(Case.getCaseValue()->getType() == SwitchTy,do { if (!(Case.getCaseValue()->getType() == SwitchTy)) { CheckFailed
("Switch constants must all be same type as switch value!", &
SI); return; } } while (false)
2702 "Switch constants must all be same type as switch value!", &SI)do { if (!(Case.getCaseValue()->getType() == SwitchTy)) { CheckFailed
("Switch constants must all be same type as switch value!", &
SI); return; } } while (false)
;
2703 Assert(Constants.insert(Case.getCaseValue()).second,do { if (!(Constants.insert(Case.getCaseValue()).second)) { CheckFailed
("Duplicate integer as switch case", &SI, Case.getCaseValue
()); return; } } while (false)
2704 "Duplicate integer as switch case", &SI, Case.getCaseValue())do { if (!(Constants.insert(Case.getCaseValue()).second)) { CheckFailed
("Duplicate integer as switch case", &SI, Case.getCaseValue
()); return; } } while (false)
;
2705 }
2706
2707 visitTerminator(SI);
2708}
2709
2710void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2711 Assert(BI.getAddress()->getType()->isPointerTy(),do { if (!(BI.getAddress()->getType()->isPointerTy())) {
CheckFailed("Indirectbr operand must have pointer type!", &
BI); return; } } while (false)
2712 "Indirectbr operand must have pointer type!", &BI)do { if (!(BI.getAddress()->getType()->isPointerTy())) {
CheckFailed("Indirectbr operand must have pointer type!", &
BI); return; } } while (false)
;
2713 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2714 Assert(BI.getDestination(i)->getType()->isLabelTy(),do { if (!(BI.getDestination(i)->getType()->isLabelTy()
)) { CheckFailed("Indirectbr destinations must all have pointer type!"
, &BI); return; } } while (false)
2715 "Indirectbr destinations must all have pointer type!", &BI)do { if (!(BI.getDestination(i)->getType()->isLabelTy()
)) { CheckFailed("Indirectbr destinations must all have pointer type!"
, &BI); return; } } while (false)
;
2716
2717 visitTerminator(BI);
2718}
2719
2720void Verifier::visitCallBrInst(CallBrInst &CBI) {
2721 Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!",do { if (!(CBI.isInlineAsm())) { CheckFailed("Callbr is currently only used for asm-goto!"
, &CBI); return; } } while (false)
2722 &CBI)do { if (!(CBI.isInlineAsm())) { CheckFailed("Callbr is currently only used for asm-goto!"
, &CBI); return; } } while (false)
;
2723 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
2724 Assert(!IA->canThrow(), "Unwinding from Callbr is not allowed")do { if (!(!IA->canThrow())) { CheckFailed("Unwinding from Callbr is not allowed"
); return; } } while (false)
;
2725 for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i)
2726 Assert(CBI.getSuccessor(i)->getType()->isLabelTy(),do { if (!(CBI.getSuccessor(i)->getType()->isLabelTy())
) { CheckFailed("Callbr successors must all have pointer type!"
, &CBI); return; } } while (false)
2727 "Callbr successors must all have pointer type!", &CBI)do { if (!(CBI.getSuccessor(i)->getType()->isLabelTy())
) { CheckFailed("Callbr successors must all have pointer type!"
, &CBI); return; } } while (false)
;
2728 for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) {
2729 Assert(i >= CBI.getNumArgOperands() || !isa<BasicBlock>(CBI.getOperand(i)),do { if (!(i >= CBI.getNumArgOperands() || !isa<BasicBlock
>(CBI.getOperand(i)))) { CheckFailed("Using an unescaped label as a callbr argument!"
, &CBI); return; } } while (false)
2730 "Using an unescaped label as a callbr argument!", &CBI)do { if (!(i >= CBI.getNumArgOperands() || !isa<BasicBlock
>(CBI.getOperand(i)))) { CheckFailed("Using an unescaped label as a callbr argument!"
, &CBI); return; } } while (false)
;
2731 if (isa<BasicBlock>(CBI.getOperand(i)))
2732 for (unsigned j = i + 1; j != e; ++j)
2733 Assert(CBI.getOperand(i) != CBI.getOperand(j),do { if (!(CBI.getOperand(i) != CBI.getOperand(j))) { CheckFailed
("Duplicate callbr destination!", &CBI); return; } } while
(false)
2734 "Duplicate callbr destination!", &CBI)do { if (!(CBI.getOperand(i) != CBI.getOperand(j))) { CheckFailed
("Duplicate callbr destination!", &CBI); return; } } while
(false)
;
2735 }
2736 {
2737 SmallPtrSet<BasicBlock *, 4> ArgBBs;
2738 for (Value *V : CBI.args())
2739 if (auto *BA = dyn_cast<BlockAddress>(V))
2740 ArgBBs.insert(BA->getBasicBlock());
2741 for (BasicBlock *BB : CBI.getIndirectDests())
2742 Assert(ArgBBs.count(BB), "Indirect label missing from arglist.", &CBI)do { if (!(ArgBBs.count(BB))) { CheckFailed("Indirect label missing from arglist."
, &CBI); return; } } while (false)
;
2743 }
2744
2745 visitTerminator(CBI);
2746}
2747
2748void Verifier::visitSelectInst(SelectInst &SI) {
2749 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),do { if (!(!SelectInst::areInvalidOperands(SI.getOperand(0), SI
.getOperand(1), SI.getOperand(2)))) { CheckFailed("Invalid operands for select instruction!"
, &SI); return; } } while (false)
2750 SI.getOperand(2)),do { if (!(!SelectInst::areInvalidOperands(SI.getOperand(0), SI
.getOperand(1), SI.getOperand(2)))) { CheckFailed("Invalid operands for select instruction!"
, &SI); return; } } while (false)
2751 "Invalid operands for select instruction!", &SI)do { if (!(!SelectInst::areInvalidOperands(SI.getOperand(0), SI
.getOperand(1), SI.getOperand(2)))) { CheckFailed("Invalid operands for select instruction!"
, &SI); return; } } while (false)
;
2752
2753 Assert(SI.getTrueValue()->getType() == SI.getType(),do { if (!(SI.getTrueValue()->getType() == SI.getType())) {
CheckFailed("Select values must have same type as select instruction!"
, &SI); return; } } while (false)
2754 "Select values must have same type as select instruction!", &SI)do { if (!(SI.getTrueValue()->getType() == SI.getType())) {
CheckFailed("Select values must have same type as select instruction!"
, &SI); return; } } while (false)
;
2755 visitInstruction(SI);
2756}
2757
2758/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2759/// a pass, if any exist, it's an error.
2760///
2761void Verifier::visitUserOp1(Instruction &I) {
2762 Assert(false, "User-defined operators should not live outside of a pass!", &I)do { if (!(false)) { CheckFailed("User-defined operators should not live outside of a pass!"
, &I); return; } } while (false)
;
2763}
2764
2765void Verifier::visitTruncInst(TruncInst &I) {
2766 // Get the source and destination types
2767 Type *SrcTy = I.getOperand(0)->getType();
2768 Type *DestTy = I.getType();
2769
2770 // Get the size of the types in bits, we'll need this later
2771 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2772 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2773
2774 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I)do { if (!(SrcTy->isIntOrIntVectorTy())) { CheckFailed("Trunc only operates on integer"
, &I); return; } } while (false)
;
2775 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I)do { if (!(DestTy->isIntOrIntVectorTy())) { CheckFailed("Trunc only produces integer"
, &I); return; } } while (false)
;
2776 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("trunc source and destination must both be a vector or neither"
, &I); return; } } while (false)
2777 "trunc source and destination must both be a vector or neither", &I)do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("trunc source and destination must both be a vector or neither"
, &I); return; } } while (false)
;
2778 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I)do { if (!(SrcBitSize > DestBitSize)) { CheckFailed("DestTy too big for Trunc"
, &I); return; } } while (false)
;
2779
2780 visitInstruction(I);
2781}
2782
2783void Verifier::visitZExtInst(ZExtInst &I) {
2784 // Get the source and destination types
2785 Type *SrcTy = I.getOperand(0)->getType();
2786 Type *DestTy = I.getType();
2787
2788 // Get the size of the types in bits, we'll need this later
2789 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I)do { if (!(SrcTy->isIntOrIntVectorTy())) { CheckFailed("ZExt only operates on integer"
, &I); return; } } while (false)
;
2790 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I)do { if (!(DestTy->isIntOrIntVectorTy())) { CheckFailed("ZExt only produces an integer"
, &I); return; } } while (false)
;
2791 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("zext source and destination must both be a vector or neither"
, &I); return; } } while (false)
2792 "zext source and destination must both be a vector or neither", &I)do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("zext source and destination must both be a vector or neither"
, &I); return; } } while (false)
;
2793 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2794 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2795
2796 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I)do { if (!(SrcBitSize < DestBitSize)) { CheckFailed("Type too small for ZExt"
, &I); return; } } while (false)
;
2797
2798 visitInstruction(I);
2799}
2800
2801void Verifier::visitSExtInst(SExtInst &I) {
2802 // Get the source and destination types
2803 Type *SrcTy = I.getOperand(0)->getType();
2804 Type *DestTy = I.getType();
2805
2806 // Get the size of the types in bits, we'll need this later
2807 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2808 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2809
2810 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I)do { if (!(SrcTy->isIntOrIntVectorTy())) { CheckFailed("SExt only operates on integer"
, &I); return; } } while (false)
;
2811 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I)do { if (!(DestTy->isIntOrIntVectorTy())) { CheckFailed("SExt only produces an integer"
, &I); return; } } while (false)
;
2812 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("sext source and destination must both be a vector or neither"
, &I); return; } } while (false)
2813 "sext source and destination must both be a vector or neither", &I)do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("sext source and destination must both be a vector or neither"
, &I); return; } } while (false)
;
2814 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I)do { if (!(SrcBitSize < DestBitSize)) { CheckFailed("Type too small for SExt"
, &I); return; } } while (false)
;
2815
2816 visitInstruction(I);
2817}
2818
2819void Verifier::visitFPTruncInst(FPTruncInst &I) {
2820 // Get the source and destination types
2821 Type *SrcTy = I.getOperand(0)->getType();
2822 Type *DestTy = I.getType();
2823 // Get the size of the types in bits, we'll need this later
2824 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2825 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2826
2827 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I)do { if (!(SrcTy->isFPOrFPVectorTy())) { CheckFailed("FPTrunc only operates on FP"
, &I); return; } } while (false)
;
2828 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I)do { if (!(DestTy->isFPOrFPVectorTy())) { CheckFailed("FPTrunc only produces an FP"
, &I); return; } } while (false)
;
2829 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("fptrunc source and destination must both be a vector or neither"
, &I); return; } } while (false)
2830 "fptrunc source and destination must both be a vector or neither", &I)do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("fptrunc source and destination must both be a vector or neither"
, &I); return; } } while (false)
;
2831 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I)do { if (!(SrcBitSize > DestBitSize)) { CheckFailed("DestTy too big for FPTrunc"
, &I); return; } } while (false)
;
2832
2833 visitInstruction(I);
2834}
2835
2836void Verifier::visitFPExtInst(FPExtInst &I) {
2837 // Get the source and destination types
2838 Type *SrcTy = I.getOperand(0)->getType();
2839 Type *DestTy = I.getType();
2840
2841 // Get the size of the types in bits, we'll need this later
2842 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2843 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2844
2845 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I)do { if (!(SrcTy->isFPOrFPVectorTy())) { CheckFailed("FPExt only operates on FP"
, &I); return; } } while (false)
;
2846 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I)do { if (!(DestTy->isFPOrFPVectorTy())) { CheckFailed("FPExt only produces an FP"
, &I); return; } } while (false)
;
2847 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("fpext source and destination must both be a vector or neither"
, &I); return; } } while (false)
2848 "fpext source and destination must both be a vector or neither", &I)do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("fpext source and destination must both be a vector or neither"
, &I); return; } } while (false)
;
2849 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I)do { if (!(SrcBitSize < DestBitSize)) { CheckFailed("DestTy too small for FPExt"
, &I); return; } } while (false)
;
2850
2851 visitInstruction(I);
2852}
2853
2854void Verifier::visitUIToFPInst(UIToFPInst &I) {
2855 // Get the source and destination types
2856 Type *SrcTy = I.getOperand(0)->getType();
2857 Type *DestTy = I.getType();
2858
2859 bool SrcVec = SrcTy->isVectorTy();
2860 bool DstVec = DestTy->isVectorTy();
2861
2862 Assert(SrcVec == DstVec,do { if (!(SrcVec == DstVec)) { CheckFailed("UIToFP source and dest must both be vector or scalar"
, &I); return; } } while (false)
2863 "UIToFP source and dest must both be vector or scalar", &I)do { if (!(SrcVec == DstVec)) { CheckFailed("UIToFP source and dest must both be vector or scalar"
, &I); return; } } while (false)
;
2864 Assert(SrcTy->isIntOrIntVectorTy(),do { if (!(SrcTy->isIntOrIntVectorTy())) { CheckFailed("UIToFP source must be integer or integer vector"
, &I); return; } } while (false)
2865 "UIToFP source must be integer or integer vector", &I)do { if (!(SrcTy->isIntOrIntVectorTy())) { CheckFailed("UIToFP source must be integer or integer vector"
, &I); return; } } while (false)
;
2866 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",do { if (!(DestTy->isFPOrFPVectorTy())) { CheckFailed("UIToFP result must be FP or FP vector"
, &I); return; } } while (false)
2867 &I)do { if (!(DestTy->isFPOrFPVectorTy())) { CheckFailed("UIToFP result must be FP or FP vector"
, &I); return; } } while (false)
;
2868
2869 if (SrcVec && DstVec)
2870 Assert(cast<VectorType>(SrcTy)->getElementCount() ==do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("UIToFP source and dest vector length mismatch",
&I); return; } } while (false)
2871 cast<VectorType>(DestTy)->getElementCount(),do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("UIToFP source and dest vector length mismatch",
&I); return; } } while (false)
2872 "UIToFP source and dest vector length mismatch", &I)do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("UIToFP source and dest vector length mismatch",
&I); return; } } while (false)
;
2873
2874 visitInstruction(I);
2875}
2876
2877void Verifier::visitSIToFPInst(SIToFPInst &I) {
2878 // Get the source and destination types
2879 Type *SrcTy = I.getOperand(0)->getType();
2880 Type *DestTy = I.getType();
2881
2882 bool SrcVec = SrcTy->isVectorTy();
2883 bool DstVec = DestTy->isVectorTy();
2884
2885 Assert(SrcVec == DstVec,do { if (!(SrcVec == DstVec)) { CheckFailed("SIToFP source and dest must both be vector or scalar"
, &I); return; } } while (false)
2886 "SIToFP source and dest must both be vector or scalar", &I)do { if (!(SrcVec == DstVec)) { CheckFailed("SIToFP source and dest must both be vector or scalar"
, &I); return; } } while (false)
;
2887 Assert(SrcTy->isIntOrIntVectorTy(),do { if (!(SrcTy->isIntOrIntVectorTy())) { CheckFailed("SIToFP source must be integer or integer vector"
, &I); return; } } while (false)
2888 "SIToFP source must be integer or integer vector", &I)do { if (!(SrcTy->isIntOrIntVectorTy())) { CheckFailed("SIToFP source must be integer or integer vector"
, &I); return; } } while (false)
;
2889 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",do { if (!(DestTy->isFPOrFPVectorTy())) { CheckFailed("SIToFP result must be FP or FP vector"
, &I); return; } } while (false)
2890 &I)do { if (!(DestTy->isFPOrFPVectorTy())) { CheckFailed("SIToFP result must be FP or FP vector"
, &I); return; } } while (false)
;
2891
2892 if (SrcVec && DstVec)
2893 Assert(cast<VectorType>(SrcTy)->getElementCount() ==do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("SIToFP source and dest vector length mismatch",
&I); return; } } while (false)
2894 cast<VectorType>(DestTy)->getElementCount(),do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("SIToFP source and dest vector length mismatch",
&I); return; } } while (false)
2895 "SIToFP source and dest vector length mismatch", &I)do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("SIToFP source and dest vector length mismatch",
&I); return; } } while (false)
;
2896
2897 visitInstruction(I);
2898}
2899
2900void Verifier::visitFPToUIInst(FPToUIInst &I) {
2901 // Get the source and destination types
2902 Type *SrcTy = I.getOperand(0)->getType();
2903 Type *DestTy = I.getType();
2904
2905 bool SrcVec = SrcTy->isVectorTy();
2906 bool DstVec = DestTy->isVectorTy();
2907
2908 Assert(SrcVec == DstVec,do { if (!(SrcVec == DstVec)) { CheckFailed("FPToUI source and dest must both be vector or scalar"
, &I); return; } } while (false)
2909 "FPToUI source and dest must both be vector or scalar", &I)do { if (!(SrcVec == DstVec)) { CheckFailed("FPToUI source and dest must both be vector or scalar"
, &I); return; } } while (false)
;
2910 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",do { if (!(SrcTy->isFPOrFPVectorTy())) { CheckFailed("FPToUI source must be FP or FP vector"
, &I); return; } } while (false)
2911 &I)do { if (!(SrcTy->isFPOrFPVectorTy())) { CheckFailed("FPToUI source must be FP or FP vector"
, &I); return; } } while (false)
;
2912 Assert(DestTy->isIntOrIntVectorTy(),do { if (!(DestTy->isIntOrIntVectorTy())) { CheckFailed("FPToUI result must be integer or integer vector"
, &I); return; } } while (false)
2913 "FPToUI result must be integer or integer vector", &I)do { if (!(DestTy->isIntOrIntVectorTy())) { CheckFailed("FPToUI result must be integer or integer vector"
, &I); return; } } while (false)
;
2914
2915 if (SrcVec && DstVec)
2916 Assert(cast<VectorType>(SrcTy)->getElementCount() ==do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("FPToUI source and dest vector length mismatch",
&I); return; } } while (false)
2917 cast<VectorType>(DestTy)->getElementCount(),do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("FPToUI source and dest vector length mismatch",
&I); return; } } while (false)
2918 "FPToUI source and dest vector length mismatch", &I)do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("FPToUI source and dest vector length mismatch",
&I); return; } } while (false)
;
2919
2920 visitInstruction(I);
2921}
2922
2923void Verifier::visitFPToSIInst(FPToSIInst &I) {
2924 // Get the source and destination types
2925 Type *SrcTy = I.getOperand(0)->getType();
2926 Type *DestTy = I.getType();
2927
2928 bool SrcVec = SrcTy->isVectorTy();
2929 bool DstVec = DestTy->isVectorTy();
2930
2931 Assert(SrcVec == DstVec,do { if (!(SrcVec == DstVec)) { CheckFailed("FPToSI source and dest must both be vector or scalar"
, &I); return; } } while (false)
2932 "FPToSI source and dest must both be vector or scalar", &I)do { if (!(SrcVec == DstVec)) { CheckFailed("FPToSI source and dest must both be vector or scalar"
, &I); return; } } while (false)
;
2933 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",do { if (!(SrcTy->isFPOrFPVectorTy())) { CheckFailed("FPToSI source must be FP or FP vector"
, &I); return; } } while (false)
2934 &I)do { if (!(SrcTy->isFPOrFPVectorTy())) { CheckFailed("FPToSI source must be FP or FP vector"
, &I); return; } } while (false)
;
2935 Assert(DestTy->isIntOrIntVectorTy(),do { if (!(DestTy->isIntOrIntVectorTy())) { CheckFailed("FPToSI result must be integer or integer vector"
, &I); return; } } while (false)
2936 "FPToSI result must be integer or integer vector", &I)do { if (!(DestTy->isIntOrIntVectorTy())) { CheckFailed("FPToSI result must be integer or integer vector"
, &I); return; } } while (false)
;
2937
2938 if (SrcVec && DstVec)
2939 Assert(cast<VectorType>(SrcTy)->getElementCount() ==do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("FPToSI source and dest vector length mismatch",
&I); return; } } while (false)
2940 cast<VectorType>(DestTy)->getElementCount(),do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("FPToSI source and dest vector length mismatch",
&I); return; } } while (false)
2941 "FPToSI source and dest vector length mismatch", &I)do { if (!(cast<VectorType>(SrcTy)->getElementCount(
) == cast<VectorType>(DestTy)->getElementCount())) {
CheckFailed("FPToSI source and dest vector length mismatch",
&I); return; } } while (false)
;
2942
2943 visitInstruction(I);
2944}
2945
2946void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2947 // Get the source and destination types
2948 Type *SrcTy = I.getOperand(0)->getType();
2949 Type *DestTy = I.getType();
2950
2951 Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I)do { if (!(SrcTy->isPtrOrPtrVectorTy())) { CheckFailed("PtrToInt source must be pointer"
, &I); return; } } while (false)
;
2952
2953 Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I)do { if (!(DestTy->isIntOrIntVectorTy())) { CheckFailed("PtrToInt result must be integral"
, &I); return; } } while (false)
;
2954 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("PtrToInt type mismatch", &I); return; } }
while (false)
2955 &I)do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("PtrToInt type mismatch", &I); return; } }
while (false)
;
2956
2957 if (SrcTy->isVectorTy()) {
2958 auto *VSrc = cast<VectorType>(SrcTy);
2959 auto *VDest = cast<VectorType>(DestTy);
2960 Assert(VSrc->getElementCount() == VDest->getElementCount(),do { if (!(VSrc->getElementCount() == VDest->getElementCount
())) { CheckFailed("PtrToInt Vector width mismatch", &I);
return; } } while (false)
2961 "PtrToInt Vector width mismatch", &I)do { if (!(VSrc->getElementCount() == VDest->getElementCount
())) { CheckFailed("PtrToInt Vector width mismatch", &I);
return; } } while (false)
;
2962 }
2963
2964 visitInstruction(I);
2965}
2966
2967void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2968 // Get the source and destination types
2969 Type *SrcTy = I.getOperand(0)->getType();
2970 Type *DestTy = I.getType();
2971
2972 Assert(SrcTy->isIntOrIntVectorTy(),do { if (!(SrcTy->isIntOrIntVectorTy())) { CheckFailed("IntToPtr source must be an integral"
, &I); return; } } while (false)
2973 "IntToPtr source must be an integral", &I)do { if (!(SrcTy->isIntOrIntVectorTy())) { CheckFailed("IntToPtr source must be an integral"
, &I); return; } } while (false)
;
2974 Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I)do { if (!(DestTy->isPtrOrPtrVectorTy())) { CheckFailed("IntToPtr result must be a pointer"
, &I); return; } } while (false)
;
2975
2976 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("IntToPtr type mismatch", &I); return; } }
while (false)
2977 &I)do { if (!(SrcTy->isVectorTy() == DestTy->isVectorTy())
) { CheckFailed("IntToPtr type mismatch", &I); return; } }
while (false)
;
2978 if (SrcTy->isVectorTy()) {
2979 auto *VSrc = cast<VectorType>(SrcTy);
2980 auto *VDest = cast<VectorType>(DestTy);
2981 Assert(VSrc->getElementCount() == VDest->getElementCount(),do { if (!(VSrc->getElementCount() == VDest->getElementCount
())) { CheckFailed("IntToPtr Vector width mismatch", &I);
return; } } while (false)
2982 "IntToPtr Vector width mismatch", &I)do { if (!(VSrc->getElementCount() == VDest->getElementCount
())) { CheckFailed("IntToPtr Vector width mismatch", &I);
return; } } while (false)
;
2983 }
2984 visitInstruction(I);
2985}
2986
2987void Verifier::visitBitCastInst(BitCastInst &I) {
2988 Assert(do { if (!(CastInst::castIsValid(Instruction::BitCast, I.getOperand
(0), I.getType()))) { CheckFailed("Invalid bitcast", &I);
return; } } while (false)
2989 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),do { if (!(CastInst::castIsValid(Instruction::BitCast, I.getOperand
(0), I.getType()))) { CheckFailed("Invalid bitcast", &I);
return; } } while (false)
2990 "Invalid bitcast", &I)do { if (!(CastInst::castIsValid(Instruction::BitCast, I.getOperand
(0), I.getType()))) { CheckFailed("Invalid bitcast", &I);
return; } } while (false)
;
2991 visitInstruction(I);
2992}
2993
2994void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2995 Type *SrcTy = I.getOperand(0)->getType();
2996 Type *DestTy = I.getType();
2997
2998 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",do { if (!(SrcTy->isPtrOrPtrVectorTy())) { CheckFailed("AddrSpaceCast source must be a pointer"
, &I); return; } } while (false)
2999 &I)do { if (!(SrcTy->isPtrOrPtrVectorTy())) { CheckFailed("AddrSpaceCast source must be a pointer"
, &I); return; } } while (false)
;
3000 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",do { if (!(DestTy->isPtrOrPtrVectorTy())) { CheckFailed("AddrSpaceCast result must be a pointer"
, &I); return; } } while (false)
3001 &I)do { if (!(DestTy->isPtrOrPtrVectorTy())) { CheckFailed("AddrSpaceCast result must be a pointer"
, &I); return; } } while (false)
;
3002 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),do { if (!(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace
())) { CheckFailed("AddrSpaceCast must be between different address spaces"
, &I); return; } } while (false)
3003 "AddrSpaceCast must be between different address spaces", &I)do { if (!(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace
())) { CheckFailed("AddrSpaceCast must be between different address spaces"
, &I); return; } } while (false)
;
3004 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3005 Assert(SrcVTy->getElementCount() ==do { if (!(SrcVTy->getElementCount() == cast<VectorType
>(DestTy)->getElementCount())) { CheckFailed("AddrSpaceCast vector pointer number of elements mismatch"
, &I); return; } } while (false)
3006 cast<VectorType>(DestTy)->getElementCount(),do { if (!(SrcVTy->getElementCount() == cast<VectorType
>(DestTy)->getElementCount())) { CheckFailed("AddrSpaceCast vector pointer number of elements mismatch"
, &I); return; } } while (false)
3007 "AddrSpaceCast vector pointer number of elements mismatch", &I)do { if (!(SrcVTy->getElementCount() == cast<VectorType
>(DestTy)->getElementCount())) { CheckFailed("AddrSpaceCast vector pointer number of elements mismatch"
, &I); return; } } while (false)
;
3008 visitInstruction(I);
3009}
3010
3011/// visitPHINode - Ensure that a PHI node is well formed.
3012///
3013void Verifier::visitPHINode(PHINode &PN) {
3014 // Ensure that the PHI nodes are all grouped together at the top of the block.
3015 // This can be tested by checking whether the instruction before this is
3016 // either nonexistent (because this is begin()) or is a PHI node. If not,
3017 // then there is some other instruction before a PHI.
3018 Assert(&PN == &PN.getParent()->front() ||do { if (!(&PN == &PN.getParent()->front() || isa<
PHINode>(--BasicBlock::iterator(&PN)))) { CheckFailed(
"PHI nodes not grouped at top of basic block!", &PN, PN.getParent
()); return; } } while (false)
3019 isa<PHINode>(--BasicBlock::iterator(&PN)),do { if (!(&PN == &PN.getParent()->front() || isa<
PHINode>(--BasicBlock::iterator(&PN)))) { CheckFailed(
"PHI nodes not grouped at top of basic block!", &PN, PN.getParent
()); return; } } while (false)
3020 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent())do { if (!(&PN == &PN.getParent()->front() || isa<
PHINode>(--BasicBlock::iterator(&PN)))) { CheckFailed(
"PHI nodes not grouped at top of basic block!", &PN, PN.getParent
()); return; } } while (false)
;
3021
3022 // Check that a PHI doesn't yield a Token.
3023 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!")do { if (!(!PN.getType()->isTokenTy())) { CheckFailed("PHI nodes cannot have token type!"
); return; } } while (false)
;
3024
3025 // Check that all of the values of the PHI node have the same type as the
3026 // result, and that the incoming blocks are really basic blocks.
3027 for (Value *IncValue : PN.incoming_values()) {
3028 Assert(PN.getType() == IncValue->getType(),do { if (!(PN.getType() == IncValue->getType())) { CheckFailed
("PHI node operands are not the same type as the result!", &
PN); return; } } while (false)
3029 "PHI node operands are not the same type as the result!", &PN)do { if (!(PN.getType() == IncValue->getType())) { CheckFailed
("PHI node operands are not the same type as the result!", &
PN); return; } } while (false)
;
3030 }
3031
3032 // All other PHI node constraints are checked in the visitBasicBlock method.
3033
3034 visitInstruction(PN);
3035}
3036
3037void Verifier::visitCallBase(CallBase &Call) {
3038 Assert(Call.getCalledOperand()->getType()->isPointerTy(),do { if (!(Call.getCalledOperand()->getType()->isPointerTy
())) { CheckFailed("Called function must be a pointer!", Call
); return; } } while (false)
3039 "Called function must be a pointer!", Call)do { if (!(Call.getCalledOperand()->getType()->isPointerTy
())) { CheckFailed("Called function must be a pointer!", Call
); return; } } while (false)
;
3040 PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType());
3041
3042 Assert(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType()),do { if (!(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType
()))) { CheckFailed("Called function is not the same type as the call!"
, Call); return; } } while (false)
3043 "Called function is not the same type as the call!", Call)do { if (!(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType
()))) { CheckFailed("Called function is not the same type as the call!"
, Call); return; } } while (false)
;
3044
3045 FunctionType *FTy = Call.getFunctionType();
3046
3047 // Verify that the correct number of arguments are being passed
3048 if (FTy->isVarArg())
3049 Assert(Call.arg_size() >= FTy->getNumParams(),do { if (!(Call.arg_size() >= FTy->getNumParams())) { CheckFailed
("Called function requires more parameters than were provided!"
, Call); return; } } while (false)
3050 "Called function requires more parameters than were provided!",do { if (!(Call.arg_size() >= FTy->getNumParams())) { CheckFailed
("Called function requires more parameters than were provided!"
, Call); return; } } while (false)
3051 Call)do { if (!(Call.arg_size() >= FTy->getNumParams())) { CheckFailed
("Called function requires more parameters than were provided!"
, Call); return; } } while (false)
;
3052 else
3053 Assert(Call.arg_size() == FTy->getNumParams(),do { if (!(Call.arg_size() == FTy->getNumParams())) { CheckFailed
("Incorrect number of arguments passed to called function!", Call
); return; } } while (false)
3054 "Incorrect number of arguments passed to called function!", Call)do { if (!(Call.arg_size() == FTy->getNumParams())) { CheckFailed
("Incorrect number of arguments passed to called function!", Call
); return; } } while (false)
;
3055
3056 // Verify that all arguments to the call match the function type.
3057 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3058 Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i),do { if (!(Call.getArgOperand(i)->getType() == FTy->getParamType
(i))) { CheckFailed("Call parameter type does not match function signature!"
, Call.getArgOperand(i), FTy->getParamType(i), Call); return
; } } while (false)
3059 "Call parameter type does not match function signature!",do { if (!(Call.getArgOperand(i)->getType() == FTy->getParamType
(i))) { CheckFailed("Call parameter type does not match function signature!"
, Call.getArgOperand(i), FTy->getParamType(i), Call); return
; } } while (false)
3060 Call.getArgOperand(i), FTy->getParamType(i), Call)do { if (!(Call.getArgOperand(i)->getType() == FTy->getParamType
(i))) { CheckFailed("Call parameter type does not match function signature!"
, Call.getArgOperand(i), FTy->getParamType(i), Call); return
; } } while (false)
;
3061
3062 AttributeList Attrs = Call.getAttributes();
3063
3064 Assert(verifyAttributeCount(Attrs, Call.arg_size()),do { if (!(verifyAttributeCount(Attrs, Call.arg_size()))) { CheckFailed
("Attribute after last parameter!", Call); return; } } while (
false)
3065 "Attribute after last parameter!", Call)do { if (!(verifyAttributeCount(Attrs, Call.arg_size()))) { CheckFailed
("Attribute after last parameter!", Call); return; } } while (
false)
;
3066
3067 Function *Callee =
3068 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3069 bool IsIntrinsic = Callee && Callee->isIntrinsic();
3070 if (IsIntrinsic)
3071 Assert(Callee->getValueType() == FTy,do { if (!(Callee->getValueType() == FTy)) { CheckFailed("Intrinsic called with incompatible signature"
, Call); return; } } while (false)
3072 "Intrinsic called with incompatible signature", Call)do { if (!(Callee->getValueType() == FTy)) { CheckFailed("Intrinsic called with incompatible signature"
, Call); return; } } while (false)
;
3073
3074 if (Attrs.hasFnAttribute(Attribute::Speculatable)) {
3075 // Don't allow speculatable on call sites, unless the underlying function
3076 // declaration is also speculatable.
3077 Assert(Callee && Callee->isSpeculatable(),do { if (!(Callee && Callee->isSpeculatable())) { CheckFailed
("speculatable attribute may not apply to call sites", Call);
return; } } while (false)
3078 "speculatable attribute may not apply to call sites", Call)do { if (!(Callee && Callee->isSpeculatable())) { CheckFailed
("speculatable attribute may not apply to call sites", Call);
return; } } while (false)
;
3079 }
3080
3081 if (Attrs.hasFnAttribute(Attribute::Preallocated)) {
3082 Assert(Call.getCalledFunction()->getIntrinsicID() ==do { if (!(Call.getCalledFunction()->getIntrinsicID() == Intrinsic
::call_preallocated_arg)) { CheckFailed("preallocated as a call site attribute can only be on "
"llvm.call.preallocated.arg"); return; } } while (false)
3083 Intrinsic::call_preallocated_arg,do { if (!(Call.getCalledFunction()->getIntrinsicID() == Intrinsic
::call_preallocated_arg)) { CheckFailed("preallocated as a call site attribute can only be on "
"llvm.call.preallocated.arg"); return; } } while (false)
3084 "preallocated as a call site attribute can only be on "do { if (!(Call.getCalledFunction()->getIntrinsicID() == Intrinsic
::call_preallocated_arg)) { CheckFailed("preallocated as a call site attribute can only be on "
"llvm.call.preallocated.arg"); return; } } while (false)
3085 "llvm.call.preallocated.arg")do { if (!(Call.getCalledFunction()->getIntrinsicID() == Intrinsic
::call_preallocated_arg)) { CheckFailed("preallocated as a call site attribute can only be on "
"llvm.call.preallocated.arg"); return; } } while (false)
;
3086 }
3087
3088 // Verify call attributes.
3089 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic);
3090
3091 // Conservatively check the inalloca argument.
3092 // We have a bug if we can find that there is an underlying alloca without
3093 // inalloca.
3094 if (Call.hasInAllocaArgument()) {
3095 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
3096 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
3097 Assert(AI->isUsedWithInAlloca(),do { if (!(AI->isUsedWithInAlloca())) { CheckFailed("inalloca argument for call has mismatched alloca"
, AI, Call); return; } } while (false)
3098 "inalloca argument for call has mismatched alloca", AI, Call)do { if (!(AI->isUsedWithInAlloca())) { CheckFailed("inalloca argument for call has mismatched alloca"
, AI, Call); return; } } while (false)
;
3099 }
3100
3101 // For each argument of the callsite, if it has the swifterror argument,
3102 // make sure the underlying alloca/parameter it comes from has a swifterror as
3103 // well.
3104 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3105 if (Call.paramHasAttr(i, Attribute::SwiftError)) {
3106 Value *SwiftErrorArg = Call.getArgOperand(i);
3107 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
3108 Assert(AI->isSwiftError(),do { if (!(AI->isSwiftError())) { CheckFailed("swifterror argument for call has mismatched alloca"
, AI, Call); return; } } while (false)
3109 "swifterror argument for call has mismatched alloca", AI, Call)do { if (!(AI->isSwiftError())) { CheckFailed("swifterror argument for call has mismatched alloca"
, AI, Call); return; } } while (false)
;
3110 continue;
3111 }
3112 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3113 Assert(ArgI,do { if (!(ArgI)) { CheckFailed("swifterror argument should come from an alloca or parameter"
, SwiftErrorArg, Call); return; } } while (false)
3114 "swifterror argument should come from an alloca or parameter",do { if (!(ArgI)) { CheckFailed("swifterror argument should come from an alloca or parameter"
, SwiftErrorArg, Call); return; } } while (false)
3115 SwiftErrorArg, Call)do { if (!(ArgI)) { CheckFailed("swifterror argument should come from an alloca or parameter"
, SwiftErrorArg, Call); return; } } while (false)
;
3116 Assert(ArgI->hasSwiftErrorAttr(),do { if (!(ArgI->hasSwiftErrorAttr())) { CheckFailed("swifterror argument for call has mismatched parameter"
, ArgI, Call); return; } } while (false)
3117 "swifterror argument for call has mismatched parameter", ArgI,do { if (!(ArgI->hasSwiftErrorAttr())) { CheckFailed("swifterror argument for call has mismatched parameter"
, ArgI, Call); return; } } while (false)
3118 Call)do { if (!(ArgI->hasSwiftErrorAttr())) { CheckFailed("swifterror argument for call has mismatched parameter"
, ArgI, Call); return; } } while (false)
;
3119 }
3120
3121 if (Attrs.hasParamAttribute(i, Attribute::ImmArg)) {
3122 // Don't allow immarg on call sites, unless the underlying declaration
3123 // also has the matching immarg.
3124 Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),do { if (!(Callee && Callee->hasParamAttribute(i, Attribute
::ImmArg))) { CheckFailed("immarg may not apply only to call sites"
, Call.getArgOperand(i), Call); return; } } while (false)
3125 "immarg may not apply only to call sites",do { if (!(Callee && Callee->hasParamAttribute(i, Attribute
::ImmArg))) { CheckFailed("immarg may not apply only to call sites"
, Call.getArgOperand(i), Call); return; } } while (false)
3126 Call.getArgOperand(i), Call)do { if (!(Callee && Callee->hasParamAttribute(i, Attribute
::ImmArg))) { CheckFailed("immarg may not apply only to call sites"
, Call.getArgOperand(i), Call); return; } } while (false)
;
3127 }
3128
3129 if (Call.paramHasAttr(i, Attribute::ImmArg)) {
3130 Value *ArgVal = Call.getArgOperand(i);
3131 Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),do { if (!(isa<ConstantInt>(ArgVal) || isa<ConstantFP
>(ArgVal))) { CheckFailed("immarg operand has non-immediate parameter"
, ArgVal, Call); return; } } while (false)
3132 "immarg operand has non-immediate parameter", ArgVal, Call)do { if (!(isa<ConstantInt>(ArgVal) || isa<ConstantFP
>(ArgVal))) { CheckFailed("immarg operand has non-immediate parameter"
, ArgVal, Call); return; } } while (false)
;
3133 }
3134
3135 if (Call.paramHasAttr(i, Attribute::Preallocated)) {
3136 Value *ArgVal = Call.getArgOperand(i);
3137 bool hasOB =
3138 Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
3139 bool isMustTail = Call.isMustTailCall();
3140 Assert(hasOB != isMustTail,do { if (!(hasOB != isMustTail)) { CheckFailed("preallocated operand either requires a preallocated bundle or "
"the call to be musttail (but not both)", ArgVal, Call); return
; } } while (false)
3141 "preallocated operand either requires a preallocated bundle or "do { if (!(hasOB != isMustTail)) { CheckFailed("preallocated operand either requires a preallocated bundle or "
"the call to be musttail (but not both)", ArgVal, Call); return
; } } while (false)
3142 "the call to be musttail (but not both)",do { if (!(hasOB != isMustTail)) { CheckFailed("preallocated operand either requires a preallocated bundle or "
"the call to be musttail (but not both)", ArgVal, Call); return
; } } while (false)
3143 ArgVal, Call)do { if (!(hasOB != isMustTail)) { CheckFailed("preallocated operand either requires a preallocated bundle or "
"the call to be musttail (but not both)", ArgVal, Call); return
; } } while (false)
;
3144 }
3145 }
3146
3147 if (FTy->isVarArg()) {
3148 // FIXME? is 'nest' even legal here?
3149 bool SawNest = false;
3150 bool SawReturned = false;
3151
3152 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3153 if (Attrs.hasParamAttribute(Idx, Attribute::Nest))
3154 SawNest = true;
3155 if (Attrs.hasParamAttribute(Idx, Attribute::Returned))
3156 SawReturned = true;
3157 }
3158
3159 // Check attributes on the varargs part.
3160 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
3161 Type *Ty = Call.getArgOperand(Idx)->getType();
3162 AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx);
3163 verifyParameterAttrs(ArgAttrs, Ty, &Call);
3164
3165 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
3166 Assert(!SawNest, "More than one parameter has attribute nest!", Call)do { if (!(!SawNest)) { CheckFailed("More than one parameter has attribute nest!"
, Call); return; } } while (false)
;
3167 SawNest = true;
3168 }
3169
3170 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
3171 Assert(!SawReturned, "More than one parameter has attribute returned!",do { if (!(!SawReturned)) { CheckFailed("More than one parameter has attribute returned!"
, Call); return; } } while (false)
3172 Call)do { if (!(!SawReturned)) { CheckFailed("More than one parameter has attribute returned!"
, Call); return; } } while (false)
;
3173 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),do { if (!(Ty->canLosslesslyBitCastTo(FTy->getReturnType
()))) { CheckFailed("Incompatible argument and return types for 'returned' "
"attribute", Call); return; } } while (false)
3174 "Incompatible argument and return types for 'returned' "do { if (!(Ty->canLosslesslyBitCastTo(FTy->getReturnType
()))) { CheckFailed("Incompatible argument and return types for 'returned' "
"attribute", Call); return; } } while (false)
3175 "attribute",do { if (!(Ty->canLosslesslyBitCastTo(FTy->getReturnType
()))) { CheckFailed("Incompatible argument and return types for 'returned' "
"attribute", Call); return; } } while (false)
3176 Call)do { if (!(Ty->canLosslesslyBitCastTo(FTy->getReturnType
()))) { CheckFailed("Incompatible argument and return types for 'returned' "
"attribute", Call); return; } } while (false)
;
3177 SawReturned = true;
3178 }
3179
3180 // Statepoint intrinsic is vararg but the wrapped function may be not.
3181 // Allow sret here and check the wrapped function in verifyStatepoint.
3182 if (!Call.getCalledFunction() ||
3183 Call.getCalledFunction()->getIntrinsicID() !=
3184 Intrinsic::experimental_gc_statepoint)
3185 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),do { if (!(!ArgAttrs.hasAttribute(Attribute::StructRet))) { CheckFailed
("Attribute 'sret' cannot be used for vararg call arguments!"
, Call); return; } } while (false)
3186 "Attribute 'sret' cannot be used for vararg call arguments!",do { if (!(!ArgAttrs.hasAttribute(Attribute::StructRet))) { CheckFailed
("Attribute 'sret' cannot be used for vararg call arguments!"
, Call); return; } } while (false)
3187 Call)do { if (!(!ArgAttrs.hasAttribute(Attribute::StructRet))) { CheckFailed
("Attribute 'sret' cannot be used for vararg call arguments!"
, Call); return; } } while (false)
;
3188
3189 if (ArgAttrs.hasAttribute(Attribute::InAlloca))
3190 Assert(Idx == Call.arg_size() - 1,do { if (!(Idx == Call.arg_size() - 1)) { CheckFailed("inalloca isn't on the last argument!"
, Call); return; } } while (false)
3191 "inalloca isn't on the last argument!", Call)do { if (!(Idx == Call.arg_size() - 1)) { CheckFailed("inalloca isn't on the last argument!"
, Call); return; } } while (false)
;
3192 }
3193 }
3194
3195 // Verify that there's no metadata unless it's a direct call to an intrinsic.
3196 if (!IsIntrinsic) {
3197 for (Type *ParamTy : FTy->params()) {
3198 Assert(!ParamTy->isMetadataTy(),do { if (!(!ParamTy->isMetadataTy())) { CheckFailed("Function has metadata parameter but isn't an intrinsic"
, Call); return; } } while (false)
3199 "Function has metadata parameter but isn't an intrinsic", Call)do { if (!(!ParamTy->isMetadataTy())) { CheckFailed("Function has metadata parameter but isn't an intrinsic"
, Call); return; } } while (false)
;
3200 Assert(!ParamTy->isTokenTy(),do { if (!(!ParamTy->isTokenTy())) { CheckFailed("Function has token parameter but isn't an intrinsic"
, Call); return; } } while (false)
3201 "Function has token parameter but isn't an intrinsic", Call)do { if (!(!ParamTy->isTokenTy())) { CheckFailed("Function has token parameter but isn't an intrinsic"
, Call); return; } } while (false)
;
3202 }
3203 }
3204
3205 // Verify that indirect calls don't return tokens.
3206 if (!Call.getCalledFunction()) {
3207 Assert(!FTy->getReturnType()->isTokenTy(),do { if (!(!FTy->getReturnType()->isTokenTy())) { CheckFailed
("Return type cannot be token for indirect call!"); return; }
} while (false)
3208 "Return type cannot be token for indirect call!")do { if (!(!FTy->getReturnType()->isTokenTy())) { CheckFailed
("Return type cannot be token for indirect call!"); return; }
} while (false)
;
3209 Assert(!FTy->getReturnType()->isX86_AMXTy(),do { if (!(!FTy->getReturnType()->isX86_AMXTy())) { CheckFailed
("Return type cannot be x86_amx for indirect call!"); return;
} } while (false)
3210 "Return type cannot be x86_amx for indirect call!")do { if (!(!FTy->getReturnType()->isX86_AMXTy())) { CheckFailed
("Return type cannot be x86_amx for indirect call!"); return;
} } while (false)
;
3211 }
3212
3213 if (Function *F = Call.getCalledFunction())
3214 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3215 visitIntrinsicCall(ID, Call);
3216
3217 // Verify that a callsite has at most one "deopt", at most one "funclet", at
3218 // most one "gc-transition", at most one "cfguardtarget",
3219 // and at most one "preallocated" operand bundle.
3220 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
3221 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3222 FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3223 FoundAttachedCallBundle = false;
3224 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
3225 OperandBundleUse BU = Call.getOperandBundleAt(i);
3226 uint32_t Tag = BU.getTagID();
3227 if (Tag == LLVMContext::OB_deopt) {
3228 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call)do { if (!(!FoundDeoptBundle)) { CheckFailed("Multiple deopt operand bundles"
, Call); return; } } while (false)
;
3229 FoundDeoptBundle = true;
3230 } else if (Tag == LLVMContext::OB_gc_transition) {
3231 Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",do { if (!(!FoundGCTransitionBundle)) { CheckFailed("Multiple gc-transition operand bundles"
, Call); return; } } while (false)
3232 Call)do { if (!(!FoundGCTransitionBundle)) { CheckFailed("Multiple gc-transition operand bundles"
, Call); return; } } while (false)
;
3233 FoundGCTransitionBundle = true;
3234 } else if (Tag == LLVMContext::OB_funclet) {
3235 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call)do { if (!(!FoundFuncletBundle)) { CheckFailed("Multiple funclet operand bundles"
, Call); return; } } while (false)
;
3236 FoundFuncletBundle = true;
3237 Assert(BU.Inputs.size() == 1,do { if (!(BU.Inputs.size() == 1)) { CheckFailed("Expected exactly one funclet bundle operand"
, Call); return; } } while (false)
3238 "Expected exactly one funclet bundle operand", Call)do { if (!(BU.Inputs.size() == 1)) { CheckFailed("Expected exactly one funclet bundle operand"
, Call); return; } } while (false)
;
3239 Assert(isa<FuncletPadInst>(BU.Inputs.front()),do { if (!(isa<FuncletPadInst>(BU.Inputs.front()))) { CheckFailed
("Funclet bundle operands should correspond to a FuncletPadInst"
, Call); return; } } while (false)
3240 "Funclet bundle operands should correspond to a FuncletPadInst",do { if (!(isa<FuncletPadInst>(BU.Inputs.front()))) { CheckFailed
("Funclet bundle operands should correspond to a FuncletPadInst"
, Call); return; } } while (false)
3241 Call)do { if (!(isa<FuncletPadInst>(BU.Inputs.front()))) { CheckFailed
("Funclet bundle operands should correspond to a FuncletPadInst"
, Call); return; } } while (false)
;
3242 } else if (Tag == LLVMContext::OB_cfguardtarget) {
3243 Assert(!FoundCFGuardTargetBundle,do { if (!(!FoundCFGuardTargetBundle)) { CheckFailed("Multiple CFGuardTarget operand bundles"
, Call); return; } } while (false)
3244 "Multiple CFGuardTarget operand bundles", Call)do { if (!(!FoundCFGuardTargetBundle)) { CheckFailed("Multiple CFGuardTarget operand bundles"
, Call); return; } } while (false)
;
3245 FoundCFGuardTargetBundle = true;
3246 Assert(BU.Inputs.size() == 1,do { if (!(BU.Inputs.size() == 1)) { CheckFailed("Expected exactly one cfguardtarget bundle operand"
, Call); return; } } while (false)
3247 "Expected exactly one cfguardtarget bundle operand", Call)do { if (!(BU.Inputs.size() == 1)) { CheckFailed("Expected exactly one cfguardtarget bundle operand"
, Call); return; } } while (false)
;
3248 } else if (Tag == LLVMContext::OB_preallocated) {
3249 Assert(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",do { if (!(!FoundPreallocatedBundle)) { CheckFailed("Multiple preallocated operand bundles"
, Call); return; } } while (false)
3250 Call)do { if (!(!FoundPreallocatedBundle)) { CheckFailed("Multiple preallocated operand bundles"
, Call); return; } } while (false)
;
3251 FoundPreallocatedBundle = true;
3252 Assert(BU.Inputs.size() == 1,do { if (!(BU.Inputs.size() == 1)) { CheckFailed("Expected exactly one preallocated bundle operand"
, Call); return; } } while (false)
3253 "Expected exactly one preallocated bundle operand", Call)do { if (!(BU.Inputs.size() == 1)) { CheckFailed("Expected exactly one preallocated bundle operand"
, Call); return; } } while (false)
;
3254 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
3255 Assert(Input &&do { if (!(Input && Input->getIntrinsicID() == Intrinsic
::call_preallocated_setup)) { CheckFailed("\"preallocated\" argument must be a token from "
"llvm.call.preallocated.setup", Call); return; } } while (false
)
3256 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,do { if (!(Input && Input->getIntrinsicID() == Intrinsic
::call_preallocated_setup)) { CheckFailed("\"preallocated\" argument must be a token from "
"llvm.call.preallocated.setup", Call); return; } } while (false
)
3257 "\"preallocated\" argument must be a token from "do { if (!(Input && Input->getIntrinsicID() == Intrinsic
::call_preallocated_setup)) { CheckFailed("\"preallocated\" argument must be a token from "
"llvm.call.preallocated.setup", Call); return; } } while (false
)
3258 "llvm.call.preallocated.setup",do { if (!(Input && Input->getIntrinsicID() == Intrinsic
::call_preallocated_setup)) { CheckFailed("\"preallocated\" argument must be a token from "
"llvm.call.preallocated.setup", Call); return; } } while (false
)
3259 Call)do { if (!(Input && Input->getIntrinsicID() == Intrinsic
::call_preallocated_setup)) { CheckFailed("\"preallocated\" argument must be a token from "
"llvm.call.preallocated.setup", Call); return; } } while (false
)
;
3260 } else if (Tag == LLVMContext::OB_gc_live) {
3261 Assert(!FoundGCLiveBundle, "Multiple gc-live operand bundles",do { if (!(!FoundGCLiveBundle)) { CheckFailed("Multiple gc-live operand bundles"
, Call); return; } } while (false)
3262 Call)do { if (!(!FoundGCLiveBundle)) { CheckFailed("Multiple gc-live operand bundles"
, Call); return; } } while (false)
;
3263 FoundGCLiveBundle = true;
3264 } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
3265 Assert(!FoundAttachedCallBundle,do { if (!(!FoundAttachedCallBundle)) { CheckFailed("Multiple \"clang.arc.attachedcall\" operand bundles"
, Call); return; } } while (false)
3266 "Multiple \"clang.arc.attachedcall\" operand bundles", Call)do { if (!(!FoundAttachedCallBundle)) { CheckFailed("Multiple \"clang.arc.attachedcall\" operand bundles"
, Call); return; } } while (false)
;
3267 FoundAttachedCallBundle = true;
3268 }
3269 }
3270
3271 if (FoundAttachedCallBundle)
3272 Assert((FTy->getReturnType()->isPointerTy() ||do { if (!((FTy->getReturnType()->isPointerTy() || (Call
.doesNotReturn() && FTy->getReturnType()->isVoidTy
())))) { CheckFailed("a call with operand bundle \"clang.arc.attachedcall\" must call a "
"function returning a pointer or a non-returning function that has "
"a void return type", Call); return; } } while (false)
3273 (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),do { if (!((FTy->getReturnType()->isPointerTy() || (Call
.doesNotReturn() && FTy->getReturnType()->isVoidTy
())))) { CheckFailed("a call with operand bundle \"clang.arc.attachedcall\" must call a "
"function returning a pointer or a non-returning function that has "
"a void return type", Call); return; } } while (false)
3274 "a call with operand bundle \"clang.arc.attachedcall\" must call a "do { if (!((FTy->getReturnType()->isPointerTy() || (Call
.doesNotReturn() && FTy->getReturnType()->isVoidTy
())))) { CheckFailed("a call with operand bundle \"clang.arc.attachedcall\" must call a "
"function returning a pointer or a non-returning function that has "
"a void return type", Call); return; } } while (false)
3275 "function returning a pointer or a non-returning function that has "do { if (!((FTy->getReturnType()->isPointerTy() || (Call
.doesNotReturn() && FTy->getReturnType()->isVoidTy
())))) { CheckFailed("a call with operand bundle \"clang.arc.attachedcall\" must call a "
"function returning a pointer or a non-returning function that has "
"a void return type", Call); return; } } while (false)
3276 "a void return type",do { if (!((FTy->getReturnType()->isPointerTy() || (Call
.doesNotReturn() && FTy->getReturnType()->isVoidTy
())))) { CheckFailed("a call with operand bundle \"clang.arc.attachedcall\" must call a "
"function returning a pointer or a non-returning function that has "
"a void return type", Call); return; } } while (false)
3277 Call)do { if (!((FTy->getReturnType()->isPointerTy() || (Call
.doesNotReturn() && FTy->getReturnType()->isVoidTy
())))) { CheckFailed("a call with operand bundle \"clang.arc.attachedcall\" must call a "
"function returning a pointer or a non-returning function that has "
"a void return type", Call); return; } } while (false)
;
3278
3279 // Verify that each inlinable callsite of a debug-info-bearing function in a
3280 // debug-info-bearing function has a debug location attached to it. Failure to
3281 // do so causes assertion failures when the inliner sets up inline scope info.
3282 if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3283 Call.getCalledFunction()->getSubprogram())
3284 AssertDI(Call.getDebugLoc(),do { if (!(Call.getDebugLoc())) { DebugInfoCheckFailed("inlinable function call in a function with "
"debug info must have a !dbg location", Call); return; } } while
(false)
3285 "inlinable function call in a function with "do { if (!(Call.getDebugLoc())) { DebugInfoCheckFailed("inlinable function call in a function with "
"debug info must have a !dbg location", Call); return; } } while
(false)
3286 "debug info must have a !dbg location",do { if (!(Call.getDebugLoc())) { DebugInfoCheckFailed("inlinable function call in a function with "
"debug info must have a !dbg location", Call); return; } } while
(false)
3287 Call)do { if (!(Call.getDebugLoc())) { DebugInfoCheckFailed("inlinable function call in a function with "
"debug info must have a !dbg location", Call); return; } } while
(false)
;
3288
3289 visitInstruction(Call);
3290}
3291
3292void Verifier::verifyTailCCMustTailAttrs(AttrBuilder Attrs,
3293 StringRef Context) {
3294 Assert(!Attrs.contains(Attribute::InAlloca),do { if (!(!Attrs.contains(Attribute::InAlloca))) { CheckFailed
(Twine("inalloca attribute not allowed in ") + Context); return
; } } while (false)
3295 Twine("inalloca attribute not allowed in ") + Context)do { if (!(!Attrs.contains(Attribute::InAlloca))) { CheckFailed
(Twine("inalloca attribute not allowed in ") + Context); return
; } } while (false)
;
3296 Assert(!Attrs.contains(Attribute::InReg),do { if (!(!Attrs.contains(Attribute::InReg))) { CheckFailed(
Twine("inreg attribute not allowed in ") + Context); return; }
} while (false)
3297 Twine("inreg attribute not allowed in ") + Context)do { if (!(!Attrs.contains(Attribute::InReg))) { CheckFailed(
Twine("inreg attribute not allowed in ") + Context); return; }
} while (false)
;
3298 Assert(!Attrs.contains(Attribute::SwiftError),do { if (!(!Attrs.contains(Attribute::SwiftError))) { CheckFailed
(Twine("swifterror attribute not allowed in ") + Context); return
; } } while (false)
3299 Twine("swifterror attribute not allowed in ") + Context)do { if (!(!Attrs.contains(Attribute::SwiftError))) { CheckFailed
(Twine("swifterror attribute not allowed in ") + Context); return
; } } while (false)
;
3300 Assert(!Attrs.contains(Attribute::Preallocated),do { if (!(!Attrs.contains(Attribute::Preallocated))) { CheckFailed
(Twine("preallocated attribute not allowed in ") + Context); return
; } } while (false)
3301 Twine("preallocated attribute not allowed in ") + Context)do { if (!(!Attrs.contains(Attribute::Preallocated))) { CheckFailed
(Twine("preallocated attribute not allowed in ") + Context); return
; } } while (false)
;
3302 Assert(!Attrs.contains(Attribute::ByRef),do { if (!(!Attrs.contains(Attribute::ByRef))) { CheckFailed(
Twine("byref attribute not allowed in ") + Context); return; }
} while (false)
3303 Twine("byref attribute not allowed in ") + Context)do { if (!(!Attrs.contains(Attribute::ByRef))) { CheckFailed(
Twine("byref attribute not allowed in ") + Context); return; }
} while (false)
;
3304}
3305
3306/// Two types are "congruent" if they are identical, or if they are both pointer
3307/// types with different pointee types and the same address space.
3308static bool isTypeCongruent(Type *L, Type *R) {
3309 if (L == R)
3310 return true;
3311 PointerType *PL = dyn_cast<PointerType>(L);
3312 PointerType *PR = dyn_cast<PointerType>(R);
3313 if (!PL || !PR)
3314 return false;
3315 return PL->getAddressSpace() == PR->getAddressSpace();
3316}
3317
3318static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs) {
3319 static const Attribute::AttrKind ABIAttrs[] = {
3320 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
3321 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
3322 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
3323 Attribute::ByRef};
3324 AttrBuilder Copy;
3325 for (auto AK : ABIAttrs) {
3326 Attribute Attr = Attrs.getParamAttributes(I).getAttribute(AK);
3327 if (Attr.isValid())
3328 Copy.addAttribute(Attr);
3329 }
3330
3331 // `align` is ABI-affecting only in combination with `byval` or `byref`.
3332 if (Attrs.hasParamAttribute(I, Attribute::Alignment) &&
3333 (Attrs.hasParamAttribute(I, Attribute::ByVal) ||
3334 Attrs.hasParamAttribute(I, Attribute::ByRef)))
3335 Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
3336 return Copy;
3337}
3338
3339void Verifier::verifyMustTailCall(CallInst &CI) {
3340 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI)do { if (!(!CI.isInlineAsm())) { CheckFailed("cannot use musttail call with inline asm"
, &CI); return; } } while (false)
;
3341
3342 Function *F = CI.getParent()->getParent();
3343 FunctionType *CallerTy = F->getFunctionType();
3344 FunctionType *CalleeTy = CI.getFunctionType();
3345 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),do { if (!(CallerTy->isVarArg() == CalleeTy->isVarArg()
)) { CheckFailed("cannot guarantee tail call due to mismatched varargs"
, &CI); return; } } while (false)
3346 "cannot guarantee tail call due to mismatched varargs", &CI)do { if (!(CallerTy->isVarArg() == CalleeTy->isVarArg()
)) { CheckFailed("cannot guarantee tail call due to mismatched varargs"
, &CI); return; } } while (false)
;
3347 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),do { if (!(isTypeCongruent(CallerTy->getReturnType(), CalleeTy
->getReturnType()))) { CheckFailed("cannot guarantee tail call due to mismatched return types"
, &CI); return; } } while (false)
3348 "cannot guarantee tail call due to mismatched return types", &CI)do { if (!(isTypeCongruent(CallerTy->getReturnType(), CalleeTy
->getReturnType()))) { CheckFailed("cannot guarantee tail call due to mismatched return types"
, &CI); return; } } while (false)
;
3349
3350 // - The calling conventions of the caller and callee must match.
3351 Assert(F->getCallingConv() == CI.getCallingConv(),do { if (!(F->getCallingConv() == CI.getCallingConv())) { CheckFailed
("cannot guarantee tail call due to mismatched calling conv",
&CI); return; } } while (false)
3352 "cannot guarantee tail call due to mismatched calling conv", &CI)do { if (!(F->getCallingConv() == CI.getCallingConv())) { CheckFailed
("cannot guarantee tail call due to mismatched calling conv",
&CI); return; } } while (false)
;
3353
3354 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
3355 // or a pointer bitcast followed by a ret instruction.
3356 // - The ret instruction must return the (possibly bitcasted) value
3357 // produced by the call or void.
3358 Value *RetVal = &CI;
3359 Instruction *Next = CI.getNextNode();
3360
3361 // Handle the optional bitcast.
3362 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3363 Assert(BI->getOperand(0) == RetVal,do { if (!(BI->getOperand(0) == RetVal)) { CheckFailed("bitcast following musttail call must use the call"
, BI); return; } } while (false)
3364 "bitcast following musttail call must use the call", BI)do { if (!(BI->getOperand(0) == RetVal)) { CheckFailed("bitcast following musttail call must use the call"
, BI); return; } } while (false)
;
3365 RetVal = BI;
3366 Next = BI->getNextNode();
3367 }
3368
3369 // Check the return.
3370 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
3371 Assert(Ret, "musttail call must precede a ret with an optional bitcast",do { if (!(Ret)) { CheckFailed("musttail call must precede a ret with an optional bitcast"
, &CI); return; } } while (false)
3372 &CI)do { if (!(Ret)) { CheckFailed("musttail call must precede a ret with an optional bitcast"
, &CI); return; } } while (false)
;
3373 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||do { if (!(!Ret->getReturnValue() || Ret->getReturnValue
() == RetVal || isa<UndefValue>(Ret->getReturnValue(
)))) { CheckFailed("musttail call result must be returned", Ret
); return; } } while (false)
3374 isa<UndefValue>(Ret->getReturnValue()),do { if (!(!Ret->getReturnValue() || Ret->getReturnValue
() == RetVal || isa<UndefValue>(Ret->getReturnValue(
)))) { CheckFailed("musttail call result must be returned", Ret
); return; } } while (false)
3375 "musttail call result must be returned", Ret)do { if (!(!Ret->getReturnValue() || Ret->getReturnValue
() == RetVal || isa<UndefValue>(Ret->getReturnValue(
)))) { CheckFailed("musttail call result must be returned", Ret
); return; } } while (false)
;
3376
3377 AttributeList CallerAttrs = F->getAttributes();
3378 AttributeList CalleeAttrs = CI.getAttributes();
3379 if (CI.getCallingConv() == CallingConv::SwiftTail ||
3380 CI.getCallingConv() == CallingConv::Tail) {
3381 StringRef CCName =
3382 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3383
3384 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3385 // are allowed in swifttailcc call
3386 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3387 AttrBuilder ABIAttrs = getParameterABIAttributes(I, CallerAttrs);
3388 SmallString<32> Context{CCName, StringRef(" musttail caller")};
3389 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3390 }
3391 for (int I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
3392 AttrBuilder ABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
3393 SmallString<32> Context{CCName, StringRef(" musttail callee")};
3394 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3395 }
3396 // - Varargs functions are not allowed
3397 Assert(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +do { if (!(!CallerTy->isVarArg())) { CheckFailed(Twine("cannot guarantee "
) + CCName + " tail call for varargs function"); return; } } while
(false)
3398 " tail call for varargs function")do { if (!(!CallerTy->isVarArg())) { CheckFailed(Twine("cannot guarantee "
) + CCName + " tail call for varargs function"); return; } } while
(false)
;
3399 return;
3400 }
3401
3402 // - The caller and callee prototypes must match. Pointer types of
3403 // parameters or return types may differ in pointee type, but not
3404 // address space.
3405 if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
3406 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),do { if (!(CallerTy->getNumParams() == CalleeTy->getNumParams
())) { CheckFailed("cannot guarantee tail call due to mismatched parameter counts"
, &CI); return; } } while (false)
3407 "cannot guarantee tail call due to mismatched parameter counts",do { if (!(CallerTy->getNumParams() == CalleeTy->getNumParams
())) { CheckFailed("cannot guarantee tail call due to mismatched parameter counts"
, &CI); return; } } while (false)
3408 &CI)do { if (!(CallerTy->getNumParams() == CalleeTy->getNumParams
())) { CheckFailed("cannot guarantee tail call due to mismatched parameter counts"
, &CI); return; } } while (false)
;
3409 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3410 Assert(do { if (!(isTypeCongruent(CallerTy->getParamType(I), CalleeTy
->getParamType(I)))) { CheckFailed("cannot guarantee tail call due to mismatched parameter types"
, &CI); return; } } while (false)
3411 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),do { if (!(isTypeCongruent(CallerTy->getParamType(I), CalleeTy
->getParamType(I)))) { CheckFailed("cannot guarantee tail call due to mismatched parameter types"
, &CI); return; } } while (false)
3412 "cannot guarantee tail call due to mismatched parameter types", &CI)do { if (!(isTypeCongruent(CallerTy->getParamType(I), CalleeTy
->getParamType(I)))) { CheckFailed("cannot guarantee tail call due to mismatched parameter types"
, &CI); return; } } while (false)
;
3413 }
3414 }
3415
3416 // - All ABI-impacting function attributes, such as sret, byval, inreg,
3417 // returned, preallocated, and inalloca, must match.
3418 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3419 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
3420 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
3421 Assert(CallerABIAttrs == CalleeABIAttrs,do { if (!(CallerABIAttrs == CalleeABIAttrs)) { CheckFailed("cannot guarantee tail call due to mismatched ABI impacting "
"function attributes", &CI, CI.getOperand(I)); return; }
} while (false)
3422 "cannot guarantee tail call due to mismatched ABI impacting "do { if (!(CallerABIAttrs == CalleeABIAttrs)) { CheckFailed("cannot guarantee tail call due to mismatched ABI impacting "
"function attributes", &CI, CI.getOperand(I)); return; }
} while (false)
3423 "function attributes",do { if (!(CallerABIAttrs == CalleeABIAttrs)) { CheckFailed("cannot guarantee tail call due to mismatched ABI impacting "
"function attributes", &CI, CI.getOperand(I)); return; }
} while (false)
3424 &CI, CI.getOperand(I))do { if (!(CallerABIAttrs == CalleeABIAttrs)) { CheckFailed("cannot guarantee tail call due to mismatched ABI impacting "
"function attributes", &CI, CI.getOperand(I)); return; }
} while (false)
;
3425 }
3426}
3427
3428void Verifier::visitCallInst(CallInst &CI) {
3429 visitCallBase(CI);
3430
3431 if (CI.isMustTailCall())
3432 verifyMustTailCall(CI);
3433}
3434
3435void Verifier::visitInvokeInst(InvokeInst &II) {
3436 visitCallBase(II);
3437
3438 // Verify that the first non-PHI instruction of the unwind destination is an
3439 // exception handling instruction.
3440 Assert(do { if (!(II.getUnwindDest()->isEHPad())) { CheckFailed("The unwind destination does not have an exception handling instruction!"
, &II); return; } } while (false)
3441 II.getUnwindDest()->isEHPad(),do { if (!(II.getUnwindDest()->isEHPad())) { CheckFailed("The unwind destination does not have an exception handling instruction!"
, &II); return; } } while (false)
3442 "The unwind destination does not have an exception handling instruction!",do { if (!(II.getUnwindDest()->isEHPad())) { CheckFailed("The unwind destination does not have an exception handling instruction!"
, &II); return; } } while (false)
3443 &II)do { if (!(II.getUnwindDest()->isEHPad())) { CheckFailed("The unwind destination does not have an exception handling instruction!"
, &II); return; } } while (false)
;
3444
3445 visitTerminator(II);
3446}
3447
3448/// visitUnaryOperator - Check the argument to the unary operator.
3449///
3450void Verifier::visitUnaryOperator(UnaryOperator &U) {
3451 Assert(U.getType() == U.getOperand(0)->getType(),do { if (!(U.getType() == U.getOperand(0)->getType())) { CheckFailed
("Unary operators must have same type for" "operands and result!"
, &U); return; } } while (false)
3452 "Unary operators must have same type for"do { if (!(U.getType() == U.getOperand(0)->getType())) { CheckFailed
("Unary operators must have same type for" "operands and result!"
, &U); return; } } while (false)
3453 "operands and result!",do { if (!(U.getType() == U.getOperand(0)->getType())) { CheckFailed
("Unary operators must have same type for" "operands and result!"
, &U); return; } } while (false)
3454 &U)do { if (!(U.getType() == U.getOperand(0)->getType())) { CheckFailed
("Unary operators must have same type for" "operands and result!"
, &U); return; } } while (false)
;
3455
3456 switch (U.getOpcode()) {
3457 // Check that floating-point arithmetic operators are only used with
3458 // floating-point operands.
3459 case Instruction::FNeg:
3460 Assert(U.getType()->isFPOrFPVectorTy(),do { if (!(U.getType()->isFPOrFPVectorTy())) { CheckFailed
("FNeg operator only works with float types!", &U); return
; } } while (false)
3461 "FNeg operator only works with float types!", &U)do { if (!(U.getType()->isFPOrFPVectorTy())) { CheckFailed
("FNeg operator only works with float types!", &U); return
; } } while (false)
;
3462 break;
3463 default:
3464 llvm_unreachable("Unknown UnaryOperator opcode!")__builtin_unreachable();
3465 }
3466
3467 visitInstruction(U);
3468}
3469
3470/// visitBinaryOperator - Check that both arguments to the binary operator are
3471/// of the same type!
3472///
3473void Verifier::visitBinaryOperator(BinaryOperator &B) {
3474 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),do { if (!(B.getOperand(0)->getType() == B.getOperand(1)->
getType())) { CheckFailed("Both operands to a binary operator are not of the same type!"
, &B); return; } } while (false)
3475 "Both operands to a binary operator are not of the same type!", &B)do { if (!(B.getOperand(0)->getType() == B.getOperand(1)->
getType())) { CheckFailed("Both operands to a binary operator are not of the same type!"
, &B); return; } } while (false)
;
3476
3477 switch (B.getOpcode()) {
3478 // Check that integer arithmetic operators are only used with
3479 // integral operands.
3480 case Instruction::Add:
3481 case Instruction::Sub:
3482 case Instruction::Mul:
3483 case Instruction::SDiv:
3484 case Instruction::UDiv:
3485 case Instruction::SRem:
3486 case Instruction::URem:
3487 Assert(B.getType()->isIntOrIntVectorTy(),do { if (!(B.getType()->isIntOrIntVectorTy())) { CheckFailed
("Integer arithmetic operators only work with integral types!"
, &B); return; } } while (false)
3488 "Integer arithmetic operators only work with integral types!", &B)do { if (!(B.getType()->isIntOrIntVectorTy())) { CheckFailed
("Integer arithmetic operators only work with integral types!"
, &B); return; } } while (false)
;
3489 Assert(B.getType() == B.getOperand(0)->getType(),do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Integer arithmetic operators must have same type " "for operands and result!"
, &B); return; } } while (false)
3490 "Integer arithmetic operators must have same type "do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Integer arithmetic operators must have same type " "for operands and result!"
, &B); return; } } while (false)
3491 "for operands and result!",do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Integer arithmetic operators must have same type " "for operands and result!"
, &B); return; } } while (false)
3492 &B)do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Integer arithmetic operators must have same type " "for operands and result!"
, &B); return; } } while (false)
;
3493 break;
3494 // Check that floating-point arithmetic operators are only used with
3495 // floating-point operands.
3496 case Instruction::FAdd:
3497 case Instruction::FSub:
3498 case Instruction::FMul:
3499 case Instruction::FDiv:
3500 case Instruction::FRem:
3501 Assert(B.getType()->isFPOrFPVectorTy(),do { if (!(B.getType()->isFPOrFPVectorTy())) { CheckFailed
("Floating-point arithmetic operators only work with " "floating-point types!"
, &B); return; } } while (false)
3502 "Floating-point arithmetic operators only work with "do { if (!(B.getType()->isFPOrFPVectorTy())) { CheckFailed
("Floating-point arithmetic operators only work with " "floating-point types!"
, &B); return; } } while (false)
3503 "floating-point types!",do { if (!(B.getType()->isFPOrFPVectorTy())) { CheckFailed
("Floating-point arithmetic operators only work with " "floating-point types!"
, &B); return; } } while (false)
3504 &B)do { if (!(B.getType()->isFPOrFPVectorTy())) { CheckFailed
("Floating-point arithmetic operators only work with " "floating-point types!"
, &B); return; } } while (false)
;
3505 Assert(B.getType() == B.getOperand(0)->getType(),do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Floating-point arithmetic operators must have same type " "for operands and result!"
, &B); return; } } while (false)
3506 "Floating-point arithmetic operators must have same type "do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Floating-point arithmetic operators must have same type " "for operands and result!"
, &B); return; } } while (false)
3507 "for operands and result!",do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Floating-point arithmetic operators must have same type " "for operands and result!"
, &B); return; } } while (false)
3508 &B)do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Floating-point arithmetic operators must have same type " "for operands and result!"
, &B); return; } } while (false)
;
3509 break;
3510 // Check that logical operators are only used with integral operands.
3511 case Instruction::And:
3512 case Instruction::Or:
3513 case Instruction::Xor:
3514 Assert(B.getType()->isIntOrIntVectorTy(),do { if (!(B.getType()->isIntOrIntVectorTy())) { CheckFailed
("Logical operators only work with integral types!", &B);
return; } } while (false)
3515 "Logical operators only work with integral types!", &B)do { if (!(B.getType()->isIntOrIntVectorTy())) { CheckFailed
("Logical operators only work with integral types!", &B);
return; } } while (false)
;
3516 Assert(B.getType() == B.getOperand(0)->getType(),do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Logical operators must have same type for operands and result!"
, &B); return; } } while (false)
3517 "Logical operators must have same type for operands and result!",do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Logical operators must have same type for operands and result!"
, &B); return; } } while (false)
3518 &B)do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Logical operators must have same type for operands and result!"
, &B); return; } } while (false)
;
3519 break;
3520 case Instruction::Shl:
3521 case Instruction::LShr:
3522 case Instruction::AShr:
3523 Assert(B.getType()->isIntOrIntVectorTy(),do { if (!(B.getType()->isIntOrIntVectorTy())) { CheckFailed
("Shifts only work with integral types!", &B); return; } }
while (false)
3524 "Shifts only work with integral types!", &B)do { if (!(B.getType()->isIntOrIntVectorTy())) { CheckFailed
("Shifts only work with integral types!", &B); return; } }
while (false)
;
3525 Assert(B.getType() == B.getOperand(0)->getType(),do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Shift return type must be same as operands!", &B); return
; } } while (false)
3526 "Shift return type must be same as operands!", &B)do { if (!(B.getType() == B.getOperand(0)->getType())) { CheckFailed
("Shift return type must be same as operands!", &B); return
; } } while (false)
;
3527 break;
3528 default:
3529 llvm_unreachable("Unknown BinaryOperator opcode!")__builtin_unreachable();
3530 }
3531
3532 visitInstruction(B);
3533}
3534
3535void Verifier::visitICmpInst(ICmpInst &IC) {
3536 // Check that the operands are the same type
3537 Type *Op0Ty = IC.getOperand(0)->getType();
3538 Type *Op1Ty = IC.getOperand(1)->getType();
3539 Assert(Op0Ty == Op1Ty,do { if (!(Op0Ty == Op1Ty)) { CheckFailed("Both operands to ICmp instruction are not of the same type!"
, &IC); return; } } while (false)
3540 "Both operands to ICmp instruction are not of the same type!", &IC)do { if (!(Op0Ty == Op1Ty)) { CheckFailed("Both operands to ICmp instruction are not of the same type!"
, &IC); return; } } while (false)
;
3541 // Check that the operands are the right type
3542 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),do { if (!(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy
())) { CheckFailed("Invalid operand types for ICmp instruction"
, &IC); return; } } while (false)
3543 "Invalid operand types for ICmp instruction", &IC)do { if (!(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy
())) { CheckFailed("Invalid operand types for ICmp instruction"
, &IC); return; } } while (false)
;
3544 // Check that the predicate is valid.
3545 Assert(IC.isIntPredicate(),do { if (!(IC.isIntPredicate())) { CheckFailed("Invalid predicate in ICmp instruction!"
, &IC); return; } } while (false)
3546 "Invalid predicate in ICmp instruction!", &IC)do { if (!(IC.isIntPredicate())) { CheckFailed("Invalid predicate in ICmp instruction!"
, &IC); return; } } while (false)
;
3547
3548 visitInstruction(IC);
3549}
3550
3551void Verifier::visitFCmpInst(FCmpInst &FC) {
3552 // Check that the operands are the same type
3553 Type *Op0Ty = FC.getOperand(0)->getType();
3554 Type *Op1Ty = FC.getOperand(1)->getType();
3555 Assert(Op0Ty == Op1Ty,do { if (!(Op0Ty == Op1Ty)) { CheckFailed("Both operands to FCmp instruction are not of the same type!"
, &FC); return; } } while (false)
3556 "Both operands to FCmp instruction are not of the same type!", &FC)do { if (!(Op0Ty == Op1Ty)) { CheckFailed("Both operands to FCmp instruction are not of the same type!"
, &FC); return; } } while (false)
;
3557 // Check that the operands are the right type
3558 Assert(Op0Ty->isFPOrFPVectorTy(),do { if (!(Op0Ty->isFPOrFPVectorTy())) { CheckFailed("Invalid operand types for FCmp instruction"
, &FC); return; } } while (false)
3559 "Invalid operand types for FCmp instruction", &FC)do { if (!(Op0Ty->isFPOrFPVectorTy())) { CheckFailed("Invalid operand types for FCmp instruction"
, &FC); return; } } while (false)
;
3560 // Check that the predicate is valid.
3561 Assert(FC.isFPPredicate(),do { if (!(FC.isFPPredicate())) { CheckFailed("Invalid predicate in FCmp instruction!"
, &FC); return; } } while (false)
3562 "Invalid predicate in FCmp instruction!", &FC)do { if (!(FC.isFPPredicate())) { CheckFailed("Invalid predicate in FCmp instruction!"
, &FC); return; } } while (false)
;
3563
3564 visitInstruction(FC);
3565}
3566
3567void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
3568 Assert(do { if (!(ExtractElementInst::isValidOperands(EI.getOperand(
0), EI.getOperand(1)))) { CheckFailed("Invalid extractelement operands!"
, &EI); return; } } while (false)
3569 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),do { if (!(ExtractElementInst::isValidOperands(EI.getOperand(
0), EI.getOperand(1)))) { CheckFailed("Invalid extractelement operands!"
, &EI); return; } } while (false)
3570 "Invalid extractelement operands!", &EI)do { if (!(ExtractElementInst::isValidOperands(EI.getOperand(
0), EI.getOperand(1)))) { CheckFailed("Invalid extractelement operands!"
, &EI); return; } } while (false)
;
3571 visitInstruction(EI);
3572}
3573
3574void Verifier::visitInsertElementInst(InsertElementInst &IE) {
3575 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),do { if (!(InsertElementInst::isValidOperands(IE.getOperand(0
), IE.getOperand(1), IE.getOperand(2)))) { CheckFailed("Invalid insertelement operands!"
, &IE); return; } } while (false)
3576 IE.getOperand(2)),do { if (!(InsertElementInst::isValidOperands(IE.getOperand(0
), IE.getOperand(1), IE.getOperand(2)))) { CheckFailed("Invalid insertelement operands!"
, &IE); return; } } while (false)
3577 "Invalid insertelement operands!", &IE)do { if (!(InsertElementInst::isValidOperands(IE.getOperand(0
), IE.getOperand(1), IE.getOperand(2)))) { CheckFailed("Invalid insertelement operands!"
, &IE); return; } } while (false)
;
3578 visitInstruction(IE);
3579}
3580
3581void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
3582 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),do { if (!(ShuffleVectorInst::isValidOperands(SV.getOperand(0
), SV.getOperand(1), SV.getShuffleMask()))) { CheckFailed("Invalid shufflevector operands!"
, &SV); return; } } while (false)
3583 SV.getShuffleMask()),do { if (!(ShuffleVectorInst::isValidOperands(SV.getOperand(0
), SV.getOperand(1), SV.getShuffleMask()))) { CheckFailed("Invalid shufflevector operands!"
, &SV); return; } } while (false)
3584 "Invalid shufflevector operands!", &SV)do { if (!(ShuffleVectorInst::isValidOperands(SV.getOperand(0
), SV.getOperand(1), SV.getShuffleMask()))) { CheckFailed("Invalid shufflevector operands!"
, &SV); return; } } while (false)
;
3585 visitInstruction(SV);
3586}
3587
3588void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3589 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
3590
3591 Assert(isa<PointerType>(TargetTy),do { if (!(isa<PointerType>(TargetTy))) { CheckFailed("GEP base pointer is not a vector or a vector of pointers"
, &GEP); return; } } while (false)
3592 "GEP base pointer is not a vector or a vector of pointers", &GEP)do { if (!(isa<PointerType>(TargetTy))) { CheckFailed("GEP base pointer is not a vector or a vector of pointers"
, &GEP); return; } } while (false)
;
3593 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP)do { if (!(GEP.getSourceElementType()->isSized())) { CheckFailed
("GEP into unsized type!", &GEP); return; } } while (false
)
;
3594
3595 SmallVector<Value *, 16> Idxs(GEP.indices());
3596 Assert(all_of(do { if (!(all_of( Idxs, [](Value* V) { return V->getType(
)->isIntOrIntVectorTy(); }))) { CheckFailed("GEP indexes must be integers"
, &GEP); return; } } while (false)
3597 Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }),do { if (!(all_of( Idxs, [](Value* V) { return V->getType(
)->isIntOrIntVectorTy(); }))) { CheckFailed("GEP indexes must be integers"
, &GEP); return; } } while (false)
3598 "GEP indexes must be integers", &GEP)do { if (!(all_of( Idxs, [](Value* V) { return V->getType(
)->isIntOrIntVectorTy(); }))) { CheckFailed("GEP indexes must be integers"
, &GEP); return; } } while (false)
;
3599 Type *ElTy =
3600 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
3601 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP)do { if (!(ElTy)) { CheckFailed("Invalid indices for GEP pointer type!"
, &GEP); return; } } while (false)
;
3602
3603 Assert(GEP.getType()->isPtrOrPtrVectorTy() &&do { if (!(GEP.getType()->isPtrOrPtrVectorTy() && GEP
.getResultElementType() == ElTy)) { CheckFailed("GEP is not of right type for indices!"
, &GEP, ElTy); return; } } while (false)
3604 GEP.getResultElementType() == ElTy,do { if (!(GEP.getType()->isPtrOrPtrVectorTy() && GEP
.getResultElementType() == ElTy)) { CheckFailed("GEP is not of right type for indices!"
, &GEP, ElTy); return; } } while (false)
3605 "GEP is not of right type for indices!", &GEP, ElTy)do { if (!(GEP.getType()->isPtrOrPtrVectorTy() && GEP
.getResultElementType() == ElTy)) { CheckFailed("GEP is not of right type for indices!"
, &GEP, ElTy); return; } } while (false)
;
3606
3607 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
3608 // Additional checks for vector GEPs.
3609 ElementCount GEPWidth = GEPVTy->getElementCount();
3610 if (GEP.getPointerOperandType()->isVectorTy())
3611 Assert(do { if (!(GEPWidth == cast<VectorType>(GEP.getPointerOperandType
())->getElementCount())) { CheckFailed("Vector GEP result width doesn't match operand's"
, &GEP); return; } } while (false)
3612 GEPWidth ==do { if (!(GEPWidth == cast<VectorType>(GEP.getPointerOperandType
())->getElementCount())) { CheckFailed("Vector GEP result width doesn't match operand's"
, &GEP); return; } } while (false)
3613 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),do { if (!(GEPWidth == cast<VectorType>(GEP.getPointerOperandType
())->getElementCount())) { CheckFailed("Vector GEP result width doesn't match operand's"
, &GEP); return; } } while (false)
3614 "Vector GEP result width doesn't match operand's", &GEP)do { if (!(GEPWidth == cast<VectorType>(GEP.getPointerOperandType
())->getElementCount())) { CheckFailed("Vector GEP result width doesn't match operand's"
, &GEP); return; } } while (false)
;
3615 for (Value *Idx : Idxs) {
3616 Type *IndexTy = Idx->getType();
3617 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3618 ElementCount IndexWidth = IndexVTy->getElementCount();
3619 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP)do { if (!(IndexWidth == GEPWidth)) { CheckFailed("Invalid GEP index vector width"
, &GEP); return; } } while (false)
;
3620 }
3621 Assert(IndexTy->isIntOrIntVectorTy(),do { if (!(IndexTy->isIntOrIntVectorTy())) { CheckFailed("All GEP indices should be of integer type"
); return; } } while (false)
3622 "All GEP indices should be of integer type")do { if (!(IndexTy->isIntOrIntVectorTy())) { CheckFailed("All GEP indices should be of integer type"
); return; } } while (false)
;
3623 }
3624 }
3625
3626 if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
3627 Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),do { if (!(GEP.getAddressSpace() == PTy->getAddressSpace()
)) { CheckFailed("GEP address space doesn't match type", &
GEP); return; } } while (false)
3628 "GEP address space doesn't match type", &GEP)do { if (!(GEP.getAddressSpace() == PTy->getAddressSpace()
)) { CheckFailed("GEP address space doesn't match type", &
GEP); return; } } while (false)
;
3629 }
3630
3631 visitInstruction(GEP);
3632}
3633
3634static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
3635 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
3636}
3637
3638void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
3639 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&((void)0)
3640 "precondition violation")((void)0);
3641
3642 unsigned NumOperands = Range->getNumOperands();
3643 Assert(NumOperands % 2 == 0, "Unfinished range!", Range)do { if (!(NumOperands % 2 == 0)) { CheckFailed("Unfinished range!"
, Range); return; } } while (false)
;
3644 unsigned NumRanges = NumOperands / 2;
3645 Assert(NumRanges >= 1, "It should have at least one range!", Range)do { if (!(NumRanges >= 1)) { CheckFailed("It should have at least one range!"
, Range); return; } } while (false)
;
3646
3647 ConstantRange LastRange(1, true); // Dummy initial value
3648 for (unsigned i = 0; i < NumRanges; ++i) {
3649 ConstantInt *Low =
3650 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
3651 Assert(Low, "The lower limit must be an integer!", Low)do { if (!(Low)) { CheckFailed("The lower limit must be an integer!"
, Low); return; } } while (false)
;
3652 ConstantInt *High =
3653 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
3654 Assert(High, "The upper limit must be an integer!", High)do { if (!(High)) { CheckFailed("The upper limit must be an integer!"
, High); return; } } while (false)
;
3655 Assert(High->getType() == Low->getType() && High->getType() == Ty,do { if (!(High->getType() == Low->getType() &&
High->getType() == Ty)) { CheckFailed("Range types must match instruction type!"
, &I); return; } } while (false)
3656 "Range types must match instruction type!", &I)do { if (!(High->getType() == Low->getType() &&
High->getType() == Ty)) { CheckFailed("Range types must match instruction type!"
, &I); return; } } while (false)
;
3657
3658 APInt HighV = High->getValue();
3659 APInt LowV = Low->getValue();
3660 ConstantRange CurRange(LowV, HighV);
3661 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),do { if (!(!CurRange.isEmptySet() && !CurRange.isFullSet
())) { CheckFailed("Range must not be empty!", Range); return
; } } while (false)
3662 "Range must not be empty!", Range)do { if (!(!CurRange.isEmptySet() && !CurRange.isFullSet
())) { CheckFailed("Range must not be empty!", Range); return
; } } while (false)
;
3663 if (i != 0) {
3664 Assert(CurRange.intersectWith(LastRange).isEmptySet(),do { if (!(CurRange.intersectWith(LastRange).isEmptySet())) {
CheckFailed("Intervals are overlapping", Range); return; } }
while (false)
3665 "Intervals are overlapping", Range)do { if (!(CurRange.intersectWith(LastRange).isEmptySet())) {
CheckFailed("Intervals are overlapping", Range); return; } }
while (false)
;
3666 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",do { if (!(LowV.sgt(LastRange.getLower()))) { CheckFailed("Intervals are not in order"
, Range); return; } } while (false)
3667 Range)do { if (!(LowV.sgt(LastRange.getLower()))) { CheckFailed("Intervals are not in order"
, Range); return; } } while (false)
;
3668 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",do { if (!(!isContiguous(CurRange, LastRange))) { CheckFailed
("Intervals are contiguous", Range); return; } } while (false
)
3669 Range)do { if (!(!isContiguous(CurRange, LastRange))) { CheckFailed
("Intervals are contiguous", Range); return; } } while (false
)
;
3670 }
3671 LastRange = ConstantRange(LowV, HighV);
3672 }
3673 if (NumRanges > 2) {
3674 APInt FirstLow =
3675 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
3676 APInt FirstHigh =
3677 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
3678 ConstantRange FirstRange(FirstLow, FirstHigh);
3679 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),do { if (!(FirstRange.intersectWith(LastRange).isEmptySet()))
{ CheckFailed("Intervals are overlapping", Range); return; }
} while (false)
3680 "Intervals are overlapping", Range)do { if (!(FirstRange.intersectWith(LastRange).isEmptySet()))
{ CheckFailed("Intervals are overlapping", Range); return; }
} while (false)
;
3681 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",do { if (!(!isContiguous(FirstRange, LastRange))) { CheckFailed
("Intervals are contiguous", Range); return; } } while (false
)
3682 Range)do { if (!(!isContiguous(FirstRange, LastRange))) { CheckFailed
("Intervals are contiguous", Range); return; } } while (false
)
;
3683 }
3684}
3685
3686void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
3687 unsigned Size = DL.getTypeSizeInBits(Ty);
3688 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I)do { if (!(Size >= 8)) { CheckFailed("atomic memory access' size must be byte-sized"
, Ty, I); return; } } while (false)
;
3689 Assert(!(Size & (Size - 1)),do { if (!(!(Size & (Size - 1)))) { CheckFailed("atomic memory access' operand must have a power-of-two size"
, Ty, I); return; } } while (false)
3690 "atomic memory access' operand must have a power-of-two size", Ty, I)do { if (!(!(Size & (Size - 1)))) { CheckFailed("atomic memory access' operand must have a power-of-two size"
, Ty, I); return; } } while (false)
;
3691}
3692
3693void Verifier::visitLoadInst(LoadInst &LI) {
3694 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1
Assuming the object is a 'PointerType'
3695 Assert(PTy, "Load operand must be a pointer.", &LI)do { if (!(PTy)) { CheckFailed("Load operand must be a pointer."
, &LI); return; } } while (false)
;
2
Taking false branch
3
Loop condition is false. Exiting loop
3696 Type *ElTy = LI.getType();
3697 Assert(LI.getAlignment() <= Value::MaximumAlignment,do { if (!(LI.getAlignment() <= Value::MaximumAlignment)) {
CheckFailed("huge alignment values are unsupported", &LI
); return; } } while (false)
4
Calling 'LoadInst::getAlignment'
3698 "huge alignment values are unsupported", &LI)do { if (!(LI.getAlignment() <= Value::MaximumAlignment)) {
CheckFailed("huge alignment values are unsupported", &LI
); return; } } while (false)
;
3699 Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI)do { if (!(ElTy->isSized())) { CheckFailed("loading unsized types is not allowed"
, &LI); return; } } while (false)
;
3700 if (LI.isAtomic()) {
3701 Assert(LI.getOrdering() != AtomicOrdering::Release &&do { if (!(LI.getOrdering() != AtomicOrdering::Release &&
LI.getOrdering() != AtomicOrdering::AcquireRelease)) { CheckFailed
("Load cannot have Release ordering", &LI); return; } } while
(false)
3702 LI.getOrdering() != AtomicOrdering::AcquireRelease,do { if (!(LI.getOrdering() != AtomicOrdering::Release &&
LI.getOrdering() != AtomicOrdering::AcquireRelease)) { CheckFailed
("Load cannot have Release ordering", &LI); return; } } while
(false)
3703 "Load cannot have Release ordering", &LI)do { if (!(LI.getOrdering() != AtomicOrdering::Release &&
LI.getOrdering() != AtomicOrdering::AcquireRelease)) { CheckFailed
("Load cannot have Release ordering", &LI); return; } } while
(false)
;
3704 Assert(LI.getAlignment() != 0,do { if (!(LI.getAlignment() != 0)) { CheckFailed("Atomic load must specify explicit alignment"
, &LI); return; } } while (false)
3705 "Atomic load must specify explicit alignment", &LI)do { if (!(LI.getAlignment() != 0)) { CheckFailed("Atomic load must specify explicit alignment"
, &LI); return; } } while (false)
;
3706 Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),do { if (!(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomic load operand must have integer, pointer, or floating point "
"type!", ElTy, &LI); return; } } while (false)
3707 "atomic load operand must have integer, pointer, or floating point "do { if (!(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomic load operand must have integer, pointer, or floating point "
"type!", ElTy, &LI); return; } } while (false)
3708 "type!",do { if (!(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomic load operand must have integer, pointer, or floating point "
"type!", ElTy, &LI); return; } } while (false)
3709 ElTy, &LI)do { if (!(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomic load operand must have integer, pointer, or floating point "
"type!", ElTy, &LI); return; } } while (false)
;
3710 checkAtomicMemAccessSize(ElTy, &LI);
3711 } else {
3712 Assert(LI.getSyncScopeID() == SyncScope::System,do { if (!(LI.getSyncScopeID() == SyncScope::System)) { CheckFailed
("Non-atomic load cannot have SynchronizationScope specified"
, &LI); return; } } while (false)
3713 "Non-atomic load cannot have SynchronizationScope specified", &LI)do { if (!(LI.getSyncScopeID() == SyncScope::System)) { CheckFailed
("Non-atomic load cannot have SynchronizationScope specified"
, &LI); return; } } while (false)
;
3714 }
3715
3716 visitInstruction(LI);
3717}
3718
3719void Verifier::visitStoreInst(StoreInst &SI) {
3720 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
3721 Assert(PTy, "Store operand must be a pointer.", &SI)do { if (!(PTy)) { CheckFailed("Store operand must be a pointer."
, &SI); return; } } while (false)
;
3722 Type *ElTy = SI.getOperand(0)->getType();
3723 Assert(PTy->isOpaqueOrPointeeTypeMatches(ElTy),do { if (!(PTy->isOpaqueOrPointeeTypeMatches(ElTy))) { CheckFailed
("Stored value type does not match pointer operand type!", &
SI, ElTy); return; } } while (false)
3724 "Stored value type does not match pointer operand type!", &SI, ElTy)do { if (!(PTy->isOpaqueOrPointeeTypeMatches(ElTy))) { CheckFailed
("Stored value type does not match pointer operand type!", &
SI, ElTy); return; } } while (false)
;
3725 Assert(SI.getAlignment() <= Value::MaximumAlignment,do { if (!(SI.getAlignment() <= Value::MaximumAlignment)) {
CheckFailed("huge alignment values are unsupported", &SI
); return; } } while (false)
3726 "huge alignment values are unsupported", &SI)do { if (!(SI.getAlignment() <= Value::MaximumAlignment)) {
CheckFailed("huge alignment values are unsupported", &SI
); return; } } while (false)
;
3727 Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI)do { if (!(ElTy->isSized())) { CheckFailed("storing unsized types is not allowed"
, &SI); return; } } while (false)
;
3728 if (SI.isAtomic()) {
3729 Assert(SI.getOrdering() != AtomicOrdering::Acquire &&do { if (!(SI.getOrdering() != AtomicOrdering::Acquire &&
SI.getOrdering() != AtomicOrdering::AcquireRelease)) { CheckFailed
("Store cannot have Acquire ordering", &SI); return; } } while
(false)
3730 SI.getOrdering() != AtomicOrdering::AcquireRelease,do { if (!(SI.getOrdering() != AtomicOrdering::Acquire &&
SI.getOrdering() != AtomicOrdering::AcquireRelease)) { CheckFailed
("Store cannot have Acquire ordering", &SI); return; } } while
(false)
3731 "Store cannot have Acquire ordering", &SI)do { if (!(SI.getOrdering() != AtomicOrdering::Acquire &&
SI.getOrdering() != AtomicOrdering::AcquireRelease)) { CheckFailed
("Store cannot have Acquire ordering", &SI); return; } } while
(false)
;
3732 Assert(SI.getAlignment() != 0,do { if (!(SI.getAlignment() != 0)) { CheckFailed("Atomic store must specify explicit alignment"
, &SI); return; } } while (false)
3733 "Atomic store must specify explicit alignment", &SI)do { if (!(SI.getAlignment() != 0)) { CheckFailed("Atomic store must specify explicit alignment"
, &SI); return; } } while (false)
;
3734 Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),do { if (!(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomic store operand must have integer, pointer, or floating point "
"type!", ElTy, &SI); return; } } while (false)
3735 "atomic store operand must have integer, pointer, or floating point "do { if (!(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomic store operand must have integer, pointer, or floating point "
"type!", ElTy, &SI); return; } } while (false)
3736 "type!",do { if (!(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomic store operand must have integer, pointer, or floating point "
"type!", ElTy, &SI); return; } } while (false)
3737 ElTy, &SI)do { if (!(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomic store operand must have integer, pointer, or floating point "
"type!", ElTy, &SI); return; } } while (false)
;
3738 checkAtomicMemAccessSize(ElTy, &SI);
3739 } else {
3740 Assert(SI.getSyncScopeID() == SyncScope::System,do { if (!(SI.getSyncScopeID() == SyncScope::System)) { CheckFailed
("Non-atomic store cannot have SynchronizationScope specified"
, &SI); return; } } while (false)
3741 "Non-atomic store cannot have SynchronizationScope specified", &SI)do { if (!(SI.getSyncScopeID() == SyncScope::System)) { CheckFailed
("Non-atomic store cannot have SynchronizationScope specified"
, &SI); return; } } while (false)
;
3742 }
3743 visitInstruction(SI);
3744}
3745
3746/// Check that SwiftErrorVal is used as a swifterror argument in CS.
3747void Verifier::verifySwiftErrorCall(CallBase &Call,
3748 const Value *SwiftErrorVal) {
3749 for (const auto &I : llvm::enumerate(Call.args())) {
3750 if (I.value() == SwiftErrorVal) {
3751 Assert(Call.paramHasAttr(I.index(), Attribute::SwiftError),do { if (!(Call.paramHasAttr(I.index(), Attribute::SwiftError
))) { CheckFailed("swifterror value when used in a callsite should be marked "
"with swifterror attribute", SwiftErrorVal, Call); return; }
} while (false)
3752 "swifterror value when used in a callsite should be marked "do { if (!(Call.paramHasAttr(I.index(), Attribute::SwiftError
))) { CheckFailed("swifterror value when used in a callsite should be marked "
"with swifterror attribute", SwiftErrorVal, Call); return; }
} while (false)
3753 "with swifterror attribute",do { if (!(Call.paramHasAttr(I.index(), Attribute::SwiftError
))) { CheckFailed("swifterror value when used in a callsite should be marked "
"with swifterror attribute", SwiftErrorVal, Call); return; }
} while (false)
3754 SwiftErrorVal, Call)do { if (!(Call.paramHasAttr(I.index(), Attribute::SwiftError
))) { CheckFailed("swifterror value when used in a callsite should be marked "
"with swifterror attribute", SwiftErrorVal, Call); return; }
} while (false)
;
3755 }
3756 }
3757}
3758
3759void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
3760 // Check that swifterror value is only used by loads, stores, or as
3761 // a swifterror argument.
3762 for (const User *U : SwiftErrorVal->users()) {
3763 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||do { if (!(isa<LoadInst>(U) || isa<StoreInst>(U) ||
isa<CallInst>(U) || isa<InvokeInst>(U))) { CheckFailed
("swifterror value can only be loaded and stored from, or " "as a swifterror argument!"
, SwiftErrorVal, U); return; } } while (false)
3764 isa<InvokeInst>(U),do { if (!(isa<LoadInst>(U) || isa<StoreInst>(U) ||
isa<CallInst>(U) || isa<InvokeInst>(U))) { CheckFailed
("swifterror value can only be loaded and stored from, or " "as a swifterror argument!"
, SwiftErrorVal, U); return; } } while (false)
3765 "swifterror value can only be loaded and stored from, or "do { if (!(isa<LoadInst>(U) || isa<StoreInst>(U) ||
isa<CallInst>(U) || isa<InvokeInst>(U))) { CheckFailed
("swifterror value can only be loaded and stored from, or " "as a swifterror argument!"
, SwiftErrorVal, U); return; } } while (false)
3766 "as a swifterror argument!",do { if (!(isa<LoadInst>(U) || isa<StoreInst>(U) ||
isa<CallInst>(U) || isa<InvokeInst>(U))) { CheckFailed
("swifterror value can only be loaded and stored from, or " "as a swifterror argument!"
, SwiftErrorVal, U); return; } } while (false)
3767 SwiftErrorVal, U)do { if (!(isa<LoadInst>(U) || isa<StoreInst>(U) ||
isa<CallInst>(U) || isa<InvokeInst>(U))) { CheckFailed
("swifterror value can only be loaded and stored from, or " "as a swifterror argument!"
, SwiftErrorVal, U); return; } } while (false)
;
3768 // If it is used by a store, check it is the second operand.
3769 if (auto StoreI = dyn_cast<StoreInst>(U))
3770 Assert(StoreI->getOperand(1) == SwiftErrorVal,do { if (!(StoreI->getOperand(1) == SwiftErrorVal)) { CheckFailed
("swifterror value should be the second operand when used " "by stores"
, SwiftErrorVal, U); return; } } while (false)
3771 "swifterror value should be the second operand when used "do { if (!(StoreI->getOperand(1) == SwiftErrorVal)) { CheckFailed
("swifterror value should be the second operand when used " "by stores"
, SwiftErrorVal, U); return; } } while (false)
3772 "by stores", SwiftErrorVal, U)do { if (!(StoreI->getOperand(1) == SwiftErrorVal)) { CheckFailed
("swifterror value should be the second operand when used " "by stores"
, SwiftErrorVal, U); return; } } while (false)
;
3773 if (auto *Call = dyn_cast<CallBase>(U))
3774 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
3775 }
3776}
3777
3778void Verifier::visitAllocaInst(AllocaInst &AI) {
3779 SmallPtrSet<Type*, 4> Visited;
3780 Assert(AI.getAllocatedType()->isSized(&Visited),do { if (!(AI.getAllocatedType()->isSized(&Visited))) {
CheckFailed("Cannot allocate unsized type", &AI); return
; } } while (false)
3781 "Cannot allocate unsized type", &AI)do { if (!(AI.getAllocatedType()->isSized(&Visited))) {
CheckFailed("Cannot allocate unsized type", &AI); return
; } } while (false)
;
3782 Assert(AI.getArraySize()->getType()->isIntegerTy(),do { if (!(AI.getArraySize()->getType()->isIntegerTy())
) { CheckFailed("Alloca array size must have integer type", &
AI); return; } } while (false)
3783 "Alloca array size must have integer type", &AI)do { if (!(AI.getArraySize()->getType()->isIntegerTy())
) { CheckFailed("Alloca array size must have integer type", &
AI); return; } } while (false)
;
3784 Assert(AI.getAlignment() <= Value::MaximumAlignment,do { if (!(AI.getAlignment() <= Value::MaximumAlignment)) {
CheckFailed("huge alignment values are unsupported", &AI
); return; } } while (false)
3785 "huge alignment values are unsupported", &AI)do { if (!(AI.getAlignment() <= Value::MaximumAlignment)) {
CheckFailed("huge alignment values are unsupported", &AI
); return; } } while (false)
;
3786
3787 if (AI.isSwiftError()) {
3788 verifySwiftErrorValue(&AI);
3789 }
3790
3791 visitInstruction(AI);
3792}
3793
3794void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
3795 Type *ElTy = CXI.getOperand(1)->getType();
3796 Assert(ElTy->isIntOrPtrTy(),do { if (!(ElTy->isIntOrPtrTy())) { CheckFailed("cmpxchg operand must have integer or pointer type"
, ElTy, &CXI); return; } } while (false)
3797 "cmpxchg operand must have integer or pointer type", ElTy, &CXI)do { if (!(ElTy->isIntOrPtrTy())) { CheckFailed("cmpxchg operand must have integer or pointer type"
, ElTy, &CXI); return; } } while (false)
;
3798 checkAtomicMemAccessSize(ElTy, &CXI);
3799 visitInstruction(CXI);
3800}
3801
3802void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
3803 Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,do { if (!(RMWI.getOrdering() != AtomicOrdering::Unordered)) {
CheckFailed("atomicrmw instructions cannot be unordered.", &
RMWI); return; } } while (false)
3804 "atomicrmw instructions cannot be unordered.", &RMWI)do { if (!(RMWI.getOrdering() != AtomicOrdering::Unordered)) {
CheckFailed("atomicrmw instructions cannot be unordered.", &
RMWI); return; } } while (false)
;
3805 auto Op = RMWI.getOperation();
3806 Type *ElTy = RMWI.getOperand(1)->getType();
3807 if (Op == AtomicRMWInst::Xchg) {
3808 Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " +do { if (!(ElTy->isIntegerTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomicrmw " + AtomicRMWInst::getOperationName
(Op) + " operand must have integer or floating point type!", &
RMWI, ElTy); return; } } while (false)
3809 AtomicRMWInst::getOperationName(Op) +do { if (!(ElTy->isIntegerTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomicrmw " + AtomicRMWInst::getOperationName
(Op) + " operand must have integer or floating point type!", &
RMWI, ElTy); return; } } while (false)
3810 " operand must have integer or floating point type!",do { if (!(ElTy->isIntegerTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomicrmw " + AtomicRMWInst::getOperationName
(Op) + " operand must have integer or floating point type!", &
RMWI, ElTy); return; } } while (false)
3811 &RMWI, ElTy)do { if (!(ElTy->isIntegerTy() || ElTy->isFloatingPointTy
())) { CheckFailed("atomicrmw " + AtomicRMWInst::getOperationName
(Op) + " operand must have integer or floating point type!", &
RMWI, ElTy); return; } } while (false)
;
3812 } else if (AtomicRMWInst::isFPOperation(Op)) {
3813 Assert(ElTy->isFloatingPointTy(), "atomicrmw " +do { if (!(ElTy->isFloatingPointTy())) { CheckFailed("atomicrmw "
+ AtomicRMWInst::getOperationName(Op) + " operand must have floating point type!"
, &RMWI, ElTy); return; } } while (false)
3814 AtomicRMWInst::getOperationName(Op) +do { if (!(ElTy->isFloatingPointTy())) { CheckFailed("atomicrmw "
+ AtomicRMWInst::getOperationName(Op) + " operand must have floating point type!"
, &RMWI, ElTy); return; } } while (false)
3815 " operand must have floating point type!",do { if (!(ElTy->isFloatingPointTy())) { CheckFailed("atomicrmw "
+ AtomicRMWInst::getOperationName(Op) + " operand must have floating point type!"
, &RMWI, ElTy); return; } } while (false)
3816 &RMWI, ElTy)do { if (!(ElTy->isFloatingPointTy())) { CheckFailed("atomicrmw "
+ AtomicRMWInst::getOperationName(Op) + " operand must have floating point type!"
, &RMWI, ElTy); return; } } while (false)
;
3817 } else {
3818 Assert(ElTy->isIntegerTy(), "atomicrmw " +do { if (!(ElTy->isIntegerTy())) { CheckFailed("atomicrmw "
+ AtomicRMWInst::getOperationName(Op) + " operand must have integer type!"
, &RMWI, ElTy); return; } } while (false)
3819 AtomicRMWInst::getOperationName(Op) +do { if (!(ElTy->isIntegerTy())) { CheckFailed("atomicrmw "
+ AtomicRMWInst::getOperationName(Op) + " operand must have integer type!"
, &RMWI, ElTy); return; } } while (false)
3820 " operand must have integer type!",do { if (!(ElTy->isIntegerTy())) { CheckFailed("atomicrmw "
+ AtomicRMWInst::getOperationName(Op) + " operand must have integer type!"
, &RMWI, ElTy); return; } } while (false)
3821 &RMWI, ElTy)do { if (!(ElTy->isIntegerTy())) { CheckFailed("atomicrmw "
+ AtomicRMWInst::getOperationName(Op) + " operand must have integer type!"
, &RMWI, ElTy); return; } } while (false)
;
3822 }
3823 checkAtomicMemAccessSize(ElTy, &RMWI);
3824 Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,do { if (!(AtomicRMWInst::FIRST_BINOP <= Op && Op <=
AtomicRMWInst::LAST_BINOP)) { CheckFailed("Invalid binary operation!"
, &RMWI); return; } } while (false)
3825 "Invalid binary operation!", &RMWI)do { if (!(AtomicRMWInst::FIRST_BINOP <= Op && Op <=
AtomicRMWInst::LAST_BINOP)) { CheckFailed("Invalid binary operation!"
, &RMWI); return; } } while (false)
;
3826 visitInstruction(RMWI);
3827}
3828
3829void Verifier::visitFenceInst(FenceInst &FI) {
3830 const AtomicOrdering Ordering = FI.getOrdering();
3831 Assert(Ordering == AtomicOrdering::Acquire ||do { if (!(Ordering == AtomicOrdering::Acquire || Ordering ==
AtomicOrdering::Release || Ordering == AtomicOrdering::AcquireRelease
|| Ordering == AtomicOrdering::SequentiallyConsistent)) { CheckFailed
("fence instructions may only have acquire, release, acq_rel, or "
"seq_cst ordering.", &FI); return; } } while (false)
3832 Ordering == AtomicOrdering::Release ||do { if (!(Ordering == AtomicOrdering::Acquire || Ordering ==
AtomicOrdering::Release || Ordering == AtomicOrdering::AcquireRelease
|| Ordering == AtomicOrdering::SequentiallyConsistent)) { CheckFailed
("fence instructions may only have acquire, release, acq_rel, or "
"seq_cst ordering.", &FI); return; } } while (false)
3833 Ordering == AtomicOrdering::AcquireRelease ||do { if (!(Ordering == AtomicOrdering::Acquire || Ordering ==
AtomicOrdering::Release || Ordering == AtomicOrdering::AcquireRelease
|| Ordering == AtomicOrdering::SequentiallyConsistent)) { CheckFailed
("fence instructions may only have acquire, release, acq_rel, or "
"seq_cst ordering.", &FI); return; } } while (false)
3834 Ordering == AtomicOrdering::SequentiallyConsistent,do { if (!(Ordering == AtomicOrdering::Acquire || Ordering ==
AtomicOrdering::Release || Ordering == AtomicOrdering::AcquireRelease
|| Ordering == AtomicOrdering::SequentiallyConsistent)) { CheckFailed
("fence instructions may only have acquire, release, acq_rel, or "
"seq_cst ordering.", &FI); return; } } while (false)
3835 "fence instructions may only have acquire, release, acq_rel, or "do { if (!(Ordering == AtomicOrdering::Acquire || Ordering ==
AtomicOrdering::Release || Ordering == AtomicOrdering::AcquireRelease
|| Ordering == AtomicOrdering::SequentiallyConsistent)) { CheckFailed
("fence instructions may only have acquire, release, acq_rel, or "
"seq_cst ordering.", &FI); return; } } while (false)
3836 "seq_cst ordering.",do { if (!(Ordering == AtomicOrdering::Acquire || Ordering ==
AtomicOrdering::Release || Ordering == AtomicOrdering::AcquireRelease
|| Ordering == AtomicOrdering::SequentiallyConsistent)) { CheckFailed
("fence instructions may only have acquire, release, acq_rel, or "
"seq_cst ordering.", &FI); return; } } while (false)
3837 &FI)do { if (!(Ordering == AtomicOrdering::Acquire || Ordering ==
AtomicOrdering::Release || Ordering == AtomicOrdering::AcquireRelease
|| Ordering == AtomicOrdering::SequentiallyConsistent)) { CheckFailed
("fence instructions may only have acquire, release, acq_rel, or "
"seq_cst ordering.", &FI); return; } } while (false)
;
3838 visitInstruction(FI);
3839}
3840
3841void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
3842 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),do { if (!(ExtractValueInst::getIndexedType(EVI.getAggregateOperand
()->getType(), EVI.getIndices()) == EVI.getType())) { CheckFailed
("Invalid ExtractValueInst operands!", &EVI); return; } }
while (false)
3843 EVI.getIndices()) == EVI.getType(),do { if (!(ExtractValueInst::getIndexedType(EVI.getAggregateOperand
()->getType(), EVI.getIndices()) == EVI.getType())) { CheckFailed
("Invalid ExtractValueInst operands!", &EVI); return; } }
while (false)
3844 "Invalid ExtractValueInst operands!", &EVI)do { if (!(ExtractValueInst::getIndexedType(EVI.getAggregateOperand
()->getType(), EVI.getIndices()) == EVI.getType())) { CheckFailed
("Invalid ExtractValueInst operands!", &EVI); return; } }
while (false)
;
3845
3846 visitInstruction(EVI);
3847}
3848
3849void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
3850 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),do { if (!(ExtractValueInst::getIndexedType(IVI.getAggregateOperand
()->getType(), IVI.getIndices()) == IVI.getOperand(1)->
getType())) { CheckFailed("Invalid InsertValueInst operands!"
, &IVI); return; } } while (false)
3851 IVI.getIndices()) ==do { if (!(ExtractValueInst::getIndexedType(IVI.getAggregateOperand
()->getType(), IVI.getIndices()) == IVI.getOperand(1)->
getType())) { CheckFailed("Invalid InsertValueInst operands!"
, &IVI); return; } } while (false)
3852 IVI.getOperand(1)->getType(),do { if (!(ExtractValueInst::getIndexedType(IVI.getAggregateOperand
()->getType(), IVI.getIndices()) == IVI.getOperand(1)->
getType())) { CheckFailed("Invalid InsertValueInst operands!"
, &IVI); return; } } while (false)
3853 "Invalid InsertValueInst operands!", &IVI)do { if (!(ExtractValueInst::getIndexedType(IVI.getAggregateOperand
()->getType(), IVI.getIndices()) == IVI.getOperand(1)->
getType())) { CheckFailed("Invalid InsertValueInst operands!"
, &IVI); return; } } while (false)
;
3854
3855 visitInstruction(IVI);
3856}
3857
3858static Value *getParentPad(Value *EHPad) {
3859 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
3860 return FPI->getParentPad();
3861
3862 return cast<CatchSwitchInst>(EHPad)->getParentPad();
3863}
3864
3865void Verifier::visitEHPadPredecessors(Instruction &I) {
3866 assert(I.isEHPad())((void)0);
3867
3868 BasicBlock *BB = I.getParent();
3869 Function *F = BB->getParent();
3870
3871 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I)do { if (!(BB != &F->getEntryBlock())) { CheckFailed("EH pad cannot be in entry block."
, &I); return; } } while (false)
;
3872
3873 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
3874 // The landingpad instruction defines its parent as a landing pad block. The
3875 // landing pad block may be branched to only by the unwind edge of an
3876 // invoke.
3877 for (BasicBlock *PredBB : predecessors(BB)) {
3878 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
3879 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,do { if (!(II && II->getUnwindDest() == BB &&
II->getNormalDest() != BB)) { CheckFailed("Block containing LandingPadInst must be jumped to "
"only by the unwind edge of an invoke.", LPI); return; } } while
(false)
3880 "Block containing LandingPadInst must be jumped to "do { if (!(II && II->getUnwindDest() == BB &&
II->getNormalDest() != BB)) { CheckFailed("Block containing LandingPadInst must be jumped to "
"only by the unwind edge of an invoke.", LPI); return; } } while
(false)
3881 "only by the unwind edge of an invoke.",do { if (!(II && II->getUnwindDest() == BB &&
II->getNormalDest() != BB)) { CheckFailed("Block containing LandingPadInst must be jumped to "
"only by the unwind edge of an invoke.", LPI); return; } } while
(false)
3882 LPI)do { if (!(II && II->getUnwindDest() == BB &&
II->getNormalDest() != BB)) { CheckFailed("Block containing LandingPadInst must be jumped to "
"only by the unwind edge of an invoke.", LPI); return; } } while
(false)
;
3883 }
3884 return;
3885 }
3886 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
3887 if (!pred_empty(BB))
3888 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),do { if (!(BB->getUniquePredecessor() == CPI->getCatchSwitch
()->getParent())) { CheckFailed("Block containg CatchPadInst must be jumped to "
"only by its catchswitch.", CPI); return; } } while (false)
3889 "Block containg CatchPadInst must be jumped to "do { if (!(BB->getUniquePredecessor() == CPI->getCatchSwitch
()->getParent())) { CheckFailed("Block containg CatchPadInst must be jumped to "
"only by its catchswitch.", CPI); return; } } while (false)
3890 "only by its catchswitch.",do { if (!(BB->getUniquePredecessor() == CPI->getCatchSwitch
()->getParent())) { CheckFailed("Block containg CatchPadInst must be jumped to "
"only by its catchswitch.", CPI); return; } } while (false)
3891 CPI)do { if (!(BB->getUniquePredecessor() == CPI->getCatchSwitch
()->getParent())) { CheckFailed("Block containg CatchPadInst must be jumped to "
"only by its catchswitch.", CPI); return; } } while (false)
;
3892 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),do { if (!(BB != CPI->getCatchSwitch()->getUnwindDest()
)) { CheckFailed("Catchswitch cannot unwind to one of its catchpads"
, CPI->getCatchSwitch(), CPI); return; } } while (false)
3893 "Catchswitch cannot unwind to one of its catchpads",do { if (!(BB != CPI->getCatchSwitch()->getUnwindDest()
)) { CheckFailed("Catchswitch cannot unwind to one of its catchpads"
, CPI->getCatchSwitch(), CPI); return; } } while (false)
3894 CPI->getCatchSwitch(), CPI)do { if (!(BB != CPI->getCatchSwitch()->getUnwindDest()
)) { CheckFailed("Catchswitch cannot unwind to one of its catchpads"
, CPI->getCatchSwitch(), CPI); return; } } while (false)
;
3895 return;
3896 }
3897
3898 // Verify that each pred has a legal terminator with a legal to/from EH
3899 // pad relationship.
3900 Instruction *ToPad = &I;
3901 Value *ToPadParent = getParentPad(ToPad);
3902 for (BasicBlock *PredBB : predecessors(BB)) {
3903 Instruction *TI = PredBB->getTerminator();
3904 Value *FromPad;
3905 if (auto *II = dyn_cast<InvokeInst>(TI)) {
3906 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,do { if (!(II->getUnwindDest() == BB && II->getNormalDest
() != BB)) { CheckFailed("EH pad must be jumped to via an unwind edge"
, ToPad, II); return; } } while (false)
3907 "EH pad must be jumped to via an unwind edge", ToPad, II)do { if (!(II->getUnwindDest() == BB && II->getNormalDest
() != BB)) { CheckFailed("EH pad must be jumped to via an unwind edge"
, ToPad, II); return; } } while (false)
;
3908 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
3909 FromPad = Bundle->Inputs[0];
3910 else
3911 FromPad = ConstantTokenNone::get(II->getContext());
3912 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3913 FromPad = CRI->getOperand(0);
3914 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI)do { if (!(FromPad != ToPadParent)) { CheckFailed("A cleanupret must exit its cleanup"
, CRI); return; } } while (false)
;
3915 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3916 FromPad = CSI;
3917 } else {
3918 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI)do { if (!(false)) { CheckFailed("EH pad must be jumped to via an unwind edge"
, ToPad, TI); return; } } while (false)
;
3919 }
3920
3921 // The edge may exit from zero or more nested pads.
3922 SmallSet<Value *, 8> Seen;
3923 for (;; FromPad = getParentPad(FromPad)) {
3924 Assert(FromPad != ToPad,do { if (!(FromPad != ToPad)) { CheckFailed("EH pad cannot handle exceptions raised within it"
, FromPad, TI); return; } } while (false)
3925 "EH pad cannot handle exceptions raised within it", FromPad, TI)do { if (!(FromPad != ToPad)) { CheckFailed("EH pad cannot handle exceptions raised within it"
, FromPad, TI); return; } } while (false)
;
3926 if (FromPad == ToPadParent) {
3927 // This is a legal unwind edge.
3928 break;
3929 }
3930 Assert(!isa<ConstantTokenNone>(FromPad),do { if (!(!isa<ConstantTokenNone>(FromPad))) { CheckFailed
("A single unwind edge may only enter one EH pad", TI); return
; } } while (false)
3931 "A single unwind edge may only enter one EH pad", TI)do { if (!(!isa<ConstantTokenNone>(FromPad))) { CheckFailed
("A single unwind edge may only enter one EH pad", TI); return
; } } while (false)
;
3932 Assert(Seen.insert(FromPad).second,do { if (!(Seen.insert(FromPad).second)) { CheckFailed("EH pad jumps through a cycle of pads"
, FromPad); return; } } while (false)
3933 "EH pad jumps through a cycle of pads", FromPad)do { if (!(Seen.insert(FromPad).second)) { CheckFailed("EH pad jumps through a cycle of pads"
, FromPad); return; } } while (false)
;
3934 }
3935 }
3936}
3937
3938void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
3939 // The landingpad instruction is ill-formed if it doesn't have any clauses and
3940 // isn't a cleanup.
3941 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),do { if (!(LPI.getNumClauses() > 0 || LPI.isCleanup())) { CheckFailed
("LandingPadInst needs at least one clause or to be a cleanup."
, &LPI); return; } } while (false)
3942 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI)do { if (!(LPI.getNumClauses() > 0 || LPI.isCleanup())) { CheckFailed
("LandingPadInst needs at least one clause or to be a cleanup."
, &LPI); return; } } while (false)
;
3943
3944 visitEHPadPredecessors(LPI);
3945
3946 if (!LandingPadResultTy)
3947 LandingPadResultTy = LPI.getType();
3948 else
3949 Assert(LandingPadResultTy == LPI.getType(),do { if (!(LandingPadResultTy == LPI.getType())) { CheckFailed
("The landingpad instruction should have a consistent result type "
"inside a function.", &LPI); return; } } while (false)
3950 "The landingpad instruction should have a consistent result type "do { if (!(LandingPadResultTy == LPI.getType())) { CheckFailed
("The landingpad instruction should have a consistent result type "
"inside a function.", &LPI); return; } } while (false)
3951 "inside a function.",do { if (!(LandingPadResultTy == LPI.getType())) { CheckFailed
("The landingpad instruction should have a consistent result type "
"inside a function.", &LPI); return; } } while (false)
3952 &LPI)do { if (!(LandingPadResultTy == LPI.getType())) { CheckFailed
("The landingpad instruction should have a consistent result type "
"inside a function.", &LPI); return; } } while (false)
;
3953
3954 Function *F = LPI.getParent()->getParent();
3955 Assert(F->hasPersonalityFn(),do { if (!(F->hasPersonalityFn())) { CheckFailed("LandingPadInst needs to be in a function with a personality."
, &LPI); return; } } while (false)
3956 "LandingPadInst needs to be in a function with a personality.", &LPI)do { if (!(F->hasPersonalityFn())) { CheckFailed("LandingPadInst needs to be in a function with a personality."
, &LPI); return; } } while (false)
;
3957
3958 // The landingpad instruction must be the first non-PHI instruction in the
3959 // block.
3960 Assert(LPI.getParent()->getLandingPadInst() == &LPI,do { if (!(LPI.getParent()->getLandingPadInst() == &LPI
)) { CheckFailed("LandingPadInst not the first non-PHI instruction in the block."
, &LPI); return; } } while (false)
3961 "LandingPadInst not the first non-PHI instruction in the block.",do { if (!(LPI.getParent()->getLandingPadInst() == &LPI
)) { CheckFailed("LandingPadInst not the first non-PHI instruction in the block."
, &LPI); return; } } while (false)
3962 &LPI)do { if (!(LPI.getParent()->getLandingPadInst() == &LPI
)) { CheckFailed("LandingPadInst not the first non-PHI instruction in the block."
, &LPI); return; } } while (false)
;
3963
3964 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
3965 Constant *Clause = LPI.getClause(i);
3966 if (LPI.isCatch(i)) {
3967 Assert(isa<PointerType>(Clause->getType()),do { if (!(isa<PointerType>(Clause->getType()))) { CheckFailed
("Catch operand does not have pointer type!", &LPI); return
; } } while (false)
3968 "Catch operand does not have pointer type!", &LPI)do { if (!(isa<PointerType>(Clause->getType()))) { CheckFailed
("Catch operand does not have pointer type!", &LPI); return
; } } while (false)
;
3969 } else {
3970 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI)do { if (!(LPI.isFilter(i))) { CheckFailed("Clause is neither catch nor filter!"
, &LPI); return; } } while (false)
;
3971 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),do { if (!(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero
>(Clause))) { CheckFailed("Filter operand is not an array of constants!"
, &LPI); return; } } while (false)
3972 "Filter operand is not an array of constants!", &LPI)do { if (!(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero
>(Clause))) { CheckFailed("Filter operand is not an array of constants!"
, &LPI); return; } } while (false)
;
3973 }
3974 }
3975
3976 visitInstruction(LPI);
3977}
3978
3979void Verifier::visitResumeInst(ResumeInst &RI) {
3980 Assert(RI.getFunction()->hasPersonalityFn(),do { if (!(RI.getFunction()->hasPersonalityFn())) { CheckFailed
("ResumeInst needs to be in a function with a personality.", &
RI); return; } } while (false)
3981 "ResumeInst needs to be in a function with a personality.", &RI)do { if (!(RI.getFunction()->hasPersonalityFn())) { CheckFailed
("ResumeInst needs to be in a function with a personality.", &
RI); return; } } while (false)
;
3982
3983 if (!LandingPadResultTy)
3984 LandingPadResultTy = RI.getValue()->getType();
3985 else
3986 Assert(LandingPadResultTy == RI.getValue()->getType(),do { if (!(LandingPadResultTy == RI.getValue()->getType())
) { CheckFailed("The resume instruction should have a consistent result type "
"inside a function.", &RI); return; } } while (false)
3987 "The resume instruction should have a consistent result type "do { if (!(LandingPadResultTy == RI.getValue()->getType())
) { CheckFailed("The resume instruction should have a consistent result type "
"inside a function.", &RI); return; } } while (false)
3988 "inside a function.",do { if (!(LandingPadResultTy == RI.getValue()->getType())
) { CheckFailed("The resume instruction should have a consistent result type "
"inside a function.", &RI); return; } } while (false)
3989 &RI)do { if (!(LandingPadResultTy == RI.getValue()->getType())
) { CheckFailed("The resume instruction should have a consistent result type "
"inside a function.", &RI); return; } } while (false)
;
3990
3991 visitTerminator(RI);
3992}
3993
3994void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
3995 BasicBlock *BB = CPI.getParent();
3996
3997 Function *F = BB->getParent();
3998 Assert(F->hasPersonalityFn(),do { if (!(F->hasPersonalityFn())) { CheckFailed("CatchPadInst needs to be in a function with a personality."
, &CPI); return; } } while (false)
3999 "CatchPadInst needs to be in a function with a personality.", &CPI)do { if (!(F->hasPersonalityFn())) { CheckFailed("CatchPadInst needs to be in a function with a personality."
, &CPI); return; } } while (false)
;
4000
4001 Assert(isa<CatchSwitchInst>(CPI.getParentPad()),do { if (!(isa<CatchSwitchInst>(CPI.getParentPad()))) {
CheckFailed("CatchPadInst needs to be directly nested in a CatchSwitchInst."
, CPI.getParentPad()); return; } } while (false)
4002 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",do { if (!(isa<CatchSwitchInst>(CPI.getParentPad()))) {
CheckFailed("CatchPadInst needs to be directly nested in a CatchSwitchInst."
, CPI.getParentPad()); return; } } while (false)
4003 CPI.getParentPad())do { if (!(isa<CatchSwitchInst>(CPI.getParentPad()))) {
CheckFailed("CatchPadInst needs to be directly nested in a CatchSwitchInst."
, CPI.getParentPad()); return; } } while (false)
;
4004
4005 // The catchpad instruction must be the first non-PHI instruction in the
4006 // block.
4007 Assert(BB->getFirstNonPHI() == &CPI,do { if (!(BB->getFirstNonPHI() == &CPI)) { CheckFailed
("CatchPadInst not the first non-PHI instruction in the block."
, &CPI); return; } } while (false)
4008 "CatchPadInst not the first non-PHI instruction in the block.", &CPI)do { if (!(BB->getFirstNonPHI() == &CPI)) { CheckFailed
("CatchPadInst not the first non-PHI instruction in the block."
, &CPI); return; } } while (false)
;
4009
4010 visitEHPadPredecessors(CPI);
4011 visitFuncletPadInst(CPI);
4012}
4013
4014void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4015 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),do { if (!(isa<CatchPadInst>(CatchReturn.getOperand(0))
)) { CheckFailed("CatchReturnInst needs to be provided a CatchPad"
, &CatchReturn, CatchReturn.getOperand(0)); return; } } while
(false)
4016 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,do { if (!(isa<CatchPadInst>(CatchReturn.getOperand(0))
)) { CheckFailed("CatchReturnInst needs to be provided a CatchPad"
, &CatchReturn, CatchReturn.getOperand(0)); return; } } while
(false)
4017 CatchReturn.getOperand(0))do { if (!(isa<CatchPadInst>(CatchReturn.getOperand(0))
)) { CheckFailed("CatchReturnInst needs to be provided a CatchPad"
, &CatchReturn, CatchReturn.getOperand(0)); return; } } while
(false)
;
4018
4019 visitTerminator(CatchReturn);
4020}
4021
4022void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4023 BasicBlock *BB = CPI.getParent();
4024
4025 Function *F = BB->getParent();
4026 Assert(F->hasPersonalityFn(),do { if (!(F->hasPersonalityFn())) { CheckFailed("CleanupPadInst needs to be in a function with a personality."
, &CPI); return; } } while (false)
4027 "CleanupPadInst needs to be in a function with a personality.", &CPI)do { if (!(F->hasPersonalityFn())) { CheckFailed("CleanupPadInst needs to be in a function with a personality."
, &CPI); return; } } while (false)
;
4028
4029 // The cleanuppad instruction must be the first non-PHI instruction in the
4030 // block.
4031 Assert(BB->getFirstNonPHI() == &CPI,do { if (!(BB->getFirstNonPHI() == &CPI)) { CheckFailed
("CleanupPadInst not the first non-PHI instruction in the block."
, &CPI); return; } } while (false)
4032 "CleanupPadInst not the first non-PHI instruction in the block.",do { if (!(BB->getFirstNonPHI() == &CPI)) { CheckFailed
("CleanupPadInst not the first non-PHI instruction in the block."
, &CPI); return; } } while (false)
4033 &CPI)do { if (!(BB->getFirstNonPHI() == &CPI)) { CheckFailed
("CleanupPadInst not the first non-PHI instruction in the block."
, &CPI); return; } } while (false)
;
4034
4035 auto *ParentPad = CPI.getParentPad();
4036 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),do { if (!(isa<ConstantTokenNone>(ParentPad) || isa<
FuncletPadInst>(ParentPad))) { CheckFailed("CleanupPadInst has an invalid parent."
, &CPI); return; } } while (false)
4037 "CleanupPadInst has an invalid parent.", &CPI)do { if (!(isa<ConstantTokenNone>(ParentPad) || isa<
FuncletPadInst>(ParentPad))) { CheckFailed("CleanupPadInst has an invalid parent."
, &CPI); return; } } while (false)
;
4038
4039 visitEHPadPredecessors(CPI);
4040 visitFuncletPadInst(CPI);
4041}
4042
4043void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4044 User *FirstUser = nullptr;
4045 Value *FirstUnwindPad = nullptr;
4046 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
4047 SmallSet<FuncletPadInst *, 8> Seen;
4048
4049 while (!Worklist.empty()) {
4050 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4051 Assert(Seen.insert(CurrentPad).second,do { if (!(Seen.insert(CurrentPad).second)) { CheckFailed("FuncletPadInst must not be nested within itself"
, CurrentPad); return; } } while (false)
4052 "FuncletPadInst must not be nested within itself", CurrentPad)do { if (!(Seen.insert(CurrentPad).second)) { CheckFailed("FuncletPadInst must not be nested within itself"
, CurrentPad); return; } } while (false)
;
4053 Value *UnresolvedAncestorPad = nullptr;
4054 for (User *U : CurrentPad->users()) {
4055 BasicBlock *UnwindDest;
4056 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
4057 UnwindDest = CRI->getUnwindDest();
4058 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
4059 // We allow catchswitch unwind to caller to nest
4060 // within an outer pad that unwinds somewhere else,
4061 // because catchswitch doesn't have a nounwind variant.
4062 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
4063 if (CSI->unwindsToCaller())
4064 continue;
4065 UnwindDest = CSI->getUnwindDest();
4066 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
4067 UnwindDest = II->getUnwindDest();
4068 } else if (isa<CallInst>(U)) {
4069 // Calls which don't unwind may be found inside funclet
4070 // pads that unwind somewhere else. We don't *require*
4071 // such calls to be annotated nounwind.
4072 continue;
4073 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
4074 // The unwind dest for a cleanup can only be found by
4075 // recursive search. Add it to the worklist, and we'll
4076 // search for its first use that determines where it unwinds.
4077 Worklist.push_back(CPI);
4078 continue;
4079 } else {
4080 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U)do { if (!(isa<CatchReturnInst>(U))) { CheckFailed("Bogus funclet pad use"
, U); return; } } while (false)
;
4081 continue;
4082 }
4083
4084 Value *UnwindPad;
4085 bool ExitsFPI;
4086 if (UnwindDest) {
4087 UnwindPad = UnwindDest->getFirstNonPHI();
4088 if (!cast<Instruction>(UnwindPad)->isEHPad())
4089 continue;
4090 Value *UnwindParent = getParentPad(UnwindPad);
4091 // Ignore unwind edges that don't exit CurrentPad.
4092 if (UnwindParent == CurrentPad)
4093 continue;
4094 // Determine whether the original funclet pad is exited,
4095 // and if we are scanning nested pads determine how many
4096 // of them are exited so we can stop searching their
4097 // children.
4098 Value *ExitedPad = CurrentPad;
4099 ExitsFPI = false;
4100 do {
4101 if (ExitedPad == &FPI) {
4102 ExitsFPI = true;
4103 // Now we can resolve any ancestors of CurrentPad up to
4104 // FPI, but not including FPI since we need to make sure
4105 // to check all direct users of FPI for consistency.
4106 UnresolvedAncestorPad = &FPI;
4107 break;
4108 }
4109 Value *ExitedParent = getParentPad(ExitedPad);
4110 if (ExitedParent == UnwindParent) {
4111 // ExitedPad is the ancestor-most pad which this unwind
4112 // edge exits, so we can resolve up to it, meaning that
4113 // ExitedParent is the first ancestor still unresolved.
4114 UnresolvedAncestorPad = ExitedParent;
4115 break;
4116 }
4117 ExitedPad = ExitedParent;
4118 } while (!isa<ConstantTokenNone>(ExitedPad));
4119 } else {
4120 // Unwinding to caller exits all pads.
4121 UnwindPad = ConstantTokenNone::get(FPI.getContext());
4122 ExitsFPI = true;
4123 UnresolvedAncestorPad = &FPI;
4124 }
4125
4126 if (ExitsFPI) {
4127 // This unwind edge exits FPI. Make sure it agrees with other
4128 // such edges.
4129 if (FirstUser) {
4130 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "do { if (!(UnwindPad == FirstUnwindPad)) { CheckFailed("Unwind edges out of a funclet "
"pad must have the same unwind " "dest", &FPI, U, FirstUser
); return; } } while (false)
4131 "pad must have the same unwind "do { if (!(UnwindPad == FirstUnwindPad)) { CheckFailed("Unwind edges out of a funclet "
"pad must have the same unwind " "dest", &FPI, U, FirstUser
); return; } } while (false)
4132 "dest",do { if (!(UnwindPad == FirstUnwindPad)) { CheckFailed("Unwind edges out of a funclet "
"pad must have the same unwind " "dest", &FPI, U, FirstUser
); return; } } while (false)
4133 &FPI, U, FirstUser)do { if (!(UnwindPad == FirstUnwindPad)) { CheckFailed("Unwind edges out of a funclet "
"pad must have the same unwind " "dest", &FPI, U, FirstUser
); return; } } while (false)
;
4134 } else {
4135 FirstUser = U;
4136 FirstUnwindPad = UnwindPad;
4137 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
4138 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
4139 getParentPad(UnwindPad) == getParentPad(&FPI))
4140 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
4141 }
4142 }
4143 // Make sure we visit all uses of FPI, but for nested pads stop as
4144 // soon as we know where they unwind to.
4145 if (CurrentPad != &FPI)
4146 break;
4147 }
4148 if (UnresolvedAncestorPad) {
4149 if (CurrentPad == UnresolvedAncestorPad) {
4150 // When CurrentPad is FPI itself, we don't mark it as resolved even if
4151 // we've found an unwind edge that exits it, because we need to verify
4152 // all direct uses of FPI.
4153 assert(CurrentPad == &FPI)((void)0);
4154 continue;
4155 }
4156 // Pop off the worklist any nested pads that we've found an unwind
4157 // destination for. The pads on the worklist are the uncles,
4158 // great-uncles, etc. of CurrentPad. We've found an unwind destination
4159 // for all ancestors of CurrentPad up to but not including
4160 // UnresolvedAncestorPad.
4161 Value *ResolvedPad = CurrentPad;
4162 while (!Worklist.empty()) {
4163 Value *UnclePad = Worklist.back();
4164 Value *AncestorPad = getParentPad(UnclePad);
4165 // Walk ResolvedPad up the ancestor list until we either find the
4166 // uncle's parent or the last resolved ancestor.
4167 while (ResolvedPad != AncestorPad) {
4168 Value *ResolvedParent = getParentPad(ResolvedPad);
4169 if (ResolvedParent == UnresolvedAncestorPad) {
4170 break;
4171 }
4172 ResolvedPad = ResolvedParent;
4173 }
4174 // If the resolved ancestor search didn't find the uncle's parent,
4175 // then the uncle is not yet resolved.
4176 if (ResolvedPad != AncestorPad)
4177 break;
4178 // This uncle is resolved, so pop it from the worklist.
4179 Worklist.pop_back();
4180 }
4181 }
4182 }
4183
4184 if (FirstUnwindPad) {
4185 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
4186 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
4187 Value *SwitchUnwindPad;
4188 if (SwitchUnwindDest)
4189 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
4190 else
4191 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
4192 Assert(SwitchUnwindPad == FirstUnwindPad,do { if (!(SwitchUnwindPad == FirstUnwindPad)) { CheckFailed(
"Unwind edges out of a catch must have the same unwind dest as "
"the parent catchswitch", &FPI, FirstUser, CatchSwitch);
return; } } while (false)
4193 "Unwind edges out of a catch must have the same unwind dest as "do { if (!(SwitchUnwindPad == FirstUnwindPad)) { CheckFailed(
"Unwind edges out of a catch must have the same unwind dest as "
"the parent catchswitch", &FPI, FirstUser, CatchSwitch);
return; } } while (false)
4194 "the parent catchswitch",do { if (!(SwitchUnwindPad == FirstUnwindPad)) { CheckFailed(
"Unwind edges out of a catch must have the same unwind dest as "
"the parent catchswitch", &FPI, FirstUser, CatchSwitch);
return; } } while (false)
4195 &FPI, FirstUser, CatchSwitch)do { if (!(SwitchUnwindPad == FirstUnwindPad)) { CheckFailed(
"Unwind edges out of a catch must have the same unwind dest as "
"the parent catchswitch", &FPI, FirstUser, CatchSwitch);
return; } } while (false)
;
4196 }
4197 }
4198
4199 visitInstruction(FPI);
4200}
4201
4202void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
4203 BasicBlock *BB = CatchSwitch.getParent();
4204
4205 Function *F = BB->getParent();
4206 Assert(F->hasPersonalityFn(),do { if (!(F->hasPersonalityFn())) { CheckFailed("CatchSwitchInst needs to be in a function with a personality."
, &CatchSwitch); return; } } while (false)
4207 "CatchSwitchInst needs to be in a function with a personality.",do { if (!(F->hasPersonalityFn())) { CheckFailed("CatchSwitchInst needs to be in a function with a personality."
, &CatchSwitch); return; } } while (false)
4208 &CatchSwitch)do { if (!(F->hasPersonalityFn())) { CheckFailed("CatchSwitchInst needs to be in a function with a personality."
, &CatchSwitch); return; } } while (false)
;
4209
4210 // The catchswitch instruction must be the first non-PHI instruction in the
4211 // block.
4212 Assert(BB->getFirstNonPHI() == &CatchSwitch,do { if (!(BB->getFirstNonPHI() == &CatchSwitch)) { CheckFailed
("CatchSwitchInst not the first non-PHI instruction in the block."
, &CatchSwitch); return; } } while (false)
4213 "CatchSwitchInst not the first non-PHI instruction in the block.",do { if (!(BB->getFirstNonPHI() == &CatchSwitch)) { CheckFailed
("CatchSwitchInst not the first non-PHI instruction in the block."
, &CatchSwitch); return; } } while (false)
4214 &CatchSwitch)do { if (!(BB->getFirstNonPHI() == &CatchSwitch)) { CheckFailed
("CatchSwitchInst not the first non-PHI instruction in the block."
, &CatchSwitch); return; } } while (false)
;
4215
4216 auto *ParentPad = CatchSwitch.getParentPad();
4217 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),do { if (!(isa<ConstantTokenNone>(ParentPad) || isa<
FuncletPadInst>(ParentPad))) { CheckFailed("CatchSwitchInst has an invalid parent."
, ParentPad); return; } } while (false)
4218 "CatchSwitchInst has an invalid parent.", ParentPad)do { if (!(isa<ConstantTokenNone>(ParentPad) || isa<
FuncletPadInst>(ParentPad))) { CheckFailed("CatchSwitchInst has an invalid parent."
, ParentPad); return; } } while (false)
;
4219
4220 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
4221 Instruction *I = UnwindDest->getFirstNonPHI();
4222 Assert(I->isEHPad() && !isa<LandingPadInst>(I),do { if (!(I->isEHPad() && !isa<LandingPadInst>
(I))) { CheckFailed("CatchSwitchInst must unwind to an EH block which is not a "
"landingpad.", &CatchSwitch); return; } } while (false)
4223 "CatchSwitchInst must unwind to an EH block which is not a "do { if (!(I->isEHPad() && !isa<LandingPadInst>
(I))) { CheckFailed("CatchSwitchInst must unwind to an EH block which is not a "
"landingpad.", &CatchSwitch); return; } } while (false)
4224 "landingpad.",do { if (!(I->isEHPad() && !isa<LandingPadInst>
(I))) { CheckFailed("CatchSwitchInst must unwind to an EH block which is not a "
"landingpad.", &CatchSwitch); return; } } while (false)
4225 &CatchSwitch)do { if (!(I->isEHPad() && !isa<LandingPadInst>
(I))) { CheckFailed("CatchSwitchInst must unwind to an EH block which is not a "
"landingpad.", &CatchSwitch); return; } } while (false)
;
4226
4227 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
4228 if (getParentPad(I) == ParentPad)
4229 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
4230 }
4231
4232 Assert(CatchSwitch.getNumHandlers() != 0,do { if (!(CatchSwitch.getNumHandlers() != 0)) { CheckFailed(
"CatchSwitchInst cannot have empty handler list", &CatchSwitch
); return; } } while (false)
4233 "CatchSwitchInst cannot have empty handler list", &CatchSwitch)do { if (!(CatchSwitch.getNumHandlers() != 0)) { CheckFailed(
"CatchSwitchInst cannot have empty handler list", &CatchSwitch
); return; } } while (false)
;
4234
4235 for (BasicBlock *Handler : CatchSwitch.handlers()) {
4236 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),do { if (!(isa<CatchPadInst>(Handler->getFirstNonPHI
()))) { CheckFailed("CatchSwitchInst handlers must be catchpads"
, &CatchSwitch, Handler); return; } } while (false)
4237 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler)do { if (!(isa<CatchPadInst>(Handler->getFirstNonPHI
()))) { CheckFailed("CatchSwitchInst handlers must be catchpads"
, &CatchSwitch, Handler); return; } } while (false)
;
4238 }
4239
4240 visitEHPadPredecessors(CatchSwitch);
4241 visitTerminator(CatchSwitch);
4242}
4243
4244void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
4245 Assert(isa<CleanupPadInst>(CRI.getOperand(0)),do { if (!(isa<CleanupPadInst>(CRI.getOperand(0)))) { CheckFailed
("CleanupReturnInst needs to be provided a CleanupPad", &
CRI, CRI.getOperand(0)); return; } } while (false)
4246 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,do { if (!(isa<CleanupPadInst>(CRI.getOperand(0)))) { CheckFailed
("CleanupReturnInst needs to be provided a CleanupPad", &
CRI, CRI.getOperand(0)); return; } } while (false)
4247 CRI.getOperand(0))do { if (!(isa<CleanupPadInst>(CRI.getOperand(0)))) { CheckFailed
("CleanupReturnInst needs to be provided a CleanupPad", &
CRI, CRI.getOperand(0)); return; } } while (false)
;
4248
4249 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
4250 Instruction *I = UnwindDest->getFirstNonPHI();
4251 Assert(I->isEHPad() && !isa<LandingPadInst>(I),do { if (!(I->isEHPad() && !isa<LandingPadInst>
(I))) { CheckFailed("CleanupReturnInst must unwind to an EH block which is not a "
"landingpad.", &CRI); return; } } while (false)
4252 "CleanupReturnInst must unwind to an EH block which is not a "do { if (!(I->isEHPad() && !isa<LandingPadInst>
(I))) { CheckFailed("CleanupReturnInst must unwind to an EH block which is not a "
"landingpad.", &CRI); return; } } while (false)
4253 "landingpad.",do { if (!(I->isEHPad() && !isa<LandingPadInst>
(I))) { CheckFailed("CleanupReturnInst must unwind to an EH block which is not a "
"landingpad.", &CRI); return; } } while (false)
4254 &CRI)do { if (!(I->isEHPad() && !isa<LandingPadInst>
(I))) { CheckFailed("CleanupReturnInst must unwind to an EH block which is not a "
"landingpad.", &CRI); return; } } while (false)
;
4255 }
4256
4257 visitTerminator(CRI);
4258}
4259
4260void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
4261 Instruction *Op = cast<Instruction>(I.getOperand(i));
4262 // If the we have an invalid invoke, don't try to compute the dominance.
4263 // We already reject it in the invoke specific checks and the dominance
4264 // computation doesn't handle multiple edges.
4265 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
4266 if (II->getNormalDest() == II->getUnwindDest())
4267 return;
4268 }
4269
4270 // Quick check whether the def has already been encountered in the same block.
4271 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
4272 // uses are defined to happen on the incoming edge, not at the instruction.
4273 //
4274 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
4275 // wrapping an SSA value, assert that we've already encountered it. See
4276 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
4277 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
4278 return;
4279
4280 const Use &U = I.getOperandUse(i);
4281 Assert(DT.dominates(Op, U),do { if (!(DT.dominates(Op, U))) { CheckFailed("Instruction does not dominate all uses!"
, Op, &I); return; } } while (false)
4282 "Instruction does not dominate all uses!", Op, &I)do { if (!(DT.dominates(Op, U))) { CheckFailed("Instruction does not dominate all uses!"
, Op, &I); return; } } while (false)
;
4283}
4284
4285void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
4286 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "do { if (!(I.getType()->isPointerTy())) { CheckFailed("dereferenceable, dereferenceable_or_null "
"apply only to pointer types", &I); return; } } while (false
)
4287 "apply only to pointer types", &I)do { if (!(I.getType()->isPointerTy())) { CheckFailed("dereferenceable, dereferenceable_or_null "
"apply only to pointer types", &I); return; } } while (false
)
;
4288 Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),do { if (!((isa<LoadInst>(I) || isa<IntToPtrInst>
(I)))) { CheckFailed("dereferenceable, dereferenceable_or_null apply only to load"
" and inttoptr instructions, use attributes for calls or invokes"
, &I); return; } } while (false)
4289 "dereferenceable, dereferenceable_or_null apply only to load"do { if (!((isa<LoadInst>(I) || isa<IntToPtrInst>
(I)))) { CheckFailed("dereferenceable, dereferenceable_or_null apply only to load"
" and inttoptr instructions, use attributes for calls or invokes"
, &I); return; } } while (false)
4290 " and inttoptr instructions, use attributes for calls or invokes", &I)do { if (!((isa<LoadInst>(I) || isa<IntToPtrInst>
(I)))) { CheckFailed("dereferenceable, dereferenceable_or_null apply only to load"
" and inttoptr instructions, use attributes for calls or invokes"
, &I); return; } } while (false)
;
4291 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "do { if (!(MD->getNumOperands() == 1)) { CheckFailed("dereferenceable, dereferenceable_or_null "
"take one operand!", &I); return; } } while (false)
4292 "take one operand!", &I)do { if (!(MD->getNumOperands() == 1)) { CheckFailed("dereferenceable, dereferenceable_or_null "
"take one operand!", &I); return; } } while (false)
;
4293 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
4294 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "do { if (!(CI && CI->getType()->isIntegerTy(64)
)) { CheckFailed("dereferenceable, " "dereferenceable_or_null metadata value must be an i64!"
, &I); return; } } while (false)
4295 "dereferenceable_or_null metadata value must be an i64!", &I)do { if (!(CI && CI->getType()->isIntegerTy(64)
)) { CheckFailed("dereferenceable, " "dereferenceable_or_null metadata value must be an i64!"
, &I); return; } } while (false)
;
4296}
4297
4298void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
4299 Assert(MD->getNumOperands() >= 2,do { if (!(MD->getNumOperands() >= 2)) { CheckFailed("!prof annotations should have no less than 2 operands"
, MD); return; } } while (false)
4300 "!prof annotations should have no less than 2 operands", MD)do { if (!(MD->getNumOperands() >= 2)) { CheckFailed("!prof annotations should have no less than 2 operands"
, MD); return; } } while (false)
;
4301
4302 // Check first operand.
4303 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD)do { if (!(MD->getOperand(0) != nullptr)) { CheckFailed("first operand should not be null"
, MD); return; } } while (false)
;
4304 Assert(isa<MDString>(MD->getOperand(0)),do { if (!(isa<MDString>(MD->getOperand(0)))) { CheckFailed
("expected string with name of the !prof annotation", MD); return
; } } while (false)
4305 "expected string with name of the !prof annotation", MD)do { if (!(isa<MDString>(MD->getOperand(0)))) { CheckFailed
("expected string with name of the !prof annotation", MD); return
; } } while (false)
;
4306 MDString *MDS = cast<MDString>(MD->getOperand(0));
4307 StringRef ProfName = MDS->getString();
4308
4309 // Check consistency of !prof branch_weights metadata.
4310 if (ProfName.equals("branch_weights")) {
4311 if (isa<InvokeInst>(&I)) {
4312 Assert(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,do { if (!(MD->getNumOperands() == 2 || MD->getNumOperands
() == 3)) { CheckFailed("Wrong number of InvokeInst branch_weights operands"
, MD); return; } } while (false)
4313 "Wrong number of InvokeInst branch_weights operands", MD)do { if (!(MD->getNumOperands() == 2 || MD->getNumOperands
() == 3)) { CheckFailed("Wrong number of InvokeInst branch_weights operands"
, MD); return; } } while (false)
;
4314 } else {
4315 unsigned ExpectedNumOperands = 0;
4316 if (BranchInst *BI = dyn_cast<BranchInst>(&I))
4317 ExpectedNumOperands = BI->getNumSuccessors();
4318 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
4319 ExpectedNumOperands = SI->getNumSuccessors();
4320 else if (isa<CallInst>(&I))
4321 ExpectedNumOperands = 1;
4322 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
4323 ExpectedNumOperands = IBI->getNumDestinations();
4324 else if (isa<SelectInst>(&I))
4325 ExpectedNumOperands = 2;
4326 else
4327 CheckFailed("!prof branch_weights are not allowed for this instruction",
4328 MD);
4329
4330 Assert(MD->getNumOperands() == 1 + ExpectedNumOperands,do { if (!(MD->getNumOperands() == 1 + ExpectedNumOperands
)) { CheckFailed("Wrong number of operands", MD); return; } }
while (false)
4331 "Wrong number of operands", MD)do { if (!(MD->getNumOperands() == 1 + ExpectedNumOperands
)) { CheckFailed("Wrong number of operands", MD); return; } }
while (false)
;
4332 }
4333 for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
4334 auto &MDO = MD->getOperand(i);
4335 Assert(MDO, "second operand should not be null", MD)do { if (!(MDO)) { CheckFailed("second operand should not be null"
, MD); return; } } while (false)
;
4336 Assert(mdconst::dyn_extract<ConstantInt>(MDO),do { if (!(mdconst::dyn_extract<ConstantInt>(MDO))) { CheckFailed
("!prof brunch_weights operand is not a const int"); return; }
} while (false)
4337 "!prof brunch_weights operand is not a const int")do { if (!(mdconst::dyn_extract<ConstantInt>(MDO))) { CheckFailed
("!prof brunch_weights operand is not a const int"); return; }
} while (false)
;
4338 }
4339 }
4340}
4341
4342void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
4343 Assert(isa<MDTuple>(Annotation), "annotation must be a tuple")do { if (!(isa<MDTuple>(Annotation))) { CheckFailed("annotation must be a tuple"
); return; } } while (false)
;
4344 Assert(Annotation->getNumOperands() >= 1,do { if (!(Annotation->getNumOperands() >= 1)) { CheckFailed
("annotation must have at least one operand"); return; } } while
(false)
4345 "annotation must have at least one operand")do { if (!(Annotation->getNumOperands() >= 1)) { CheckFailed
("annotation must have at least one operand"); return; } } while
(false)
;
4346 for (const MDOperand &Op : Annotation->operands())
4347 Assert(isa<MDString>(Op.get()), "operands must be strings")do { if (!(isa<MDString>(Op.get()))) { CheckFailed("operands must be strings"
); return; } } while (false)
;
4348}
4349
4350/// verifyInstruction - Verify that an instruction is well formed.
4351///
4352void Verifier::visitInstruction(Instruction &I) {
4353 BasicBlock *BB = I.getParent();
4354 Assert(BB, "Instruction not embedded in basic block!", &I)do { if (!(BB)) { CheckFailed("Instruction not embedded in basic block!"
, &I); return; } } while (false)
;
4355
4356 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
4357 for (User *U : I.users()) {
4358 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),do { if (!(U != (User *)&I || !DT.isReachableFromEntry(BB
))) { CheckFailed("Only PHI nodes may reference their own value!"
, &I); return; } } while (false)
4359 "Only PHI nodes may reference their own value!", &I)do { if (!(U != (User *)&I || !DT.isReachableFromEntry(BB
))) { CheckFailed("Only PHI nodes may reference their own value!"
, &I); return; } } while (false)
;
4360 }
4361 }
4362
4363 // Check that void typed values don't have names
4364 Assert(!I.getType()->isVoidTy() || !I.hasName(),do { if (!(!I.getType()->isVoidTy() || !I.hasName())) { CheckFailed
("Instruction has a name, but provides a void value!", &I
); return; } } while (false)
4365 "Instruction has a name, but provides a void value!", &I)do { if (!(!I.getType()->isVoidTy() || !I.hasName())) { CheckFailed
("Instruction has a name, but provides a void value!", &I
); return; } } while (false)
;
4366
4367 // Check that the return value of the instruction is either void or a legal
4368 // value type.
4369 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),do { if (!(I.getType()->isVoidTy() || I.getType()->isFirstClassType
())) { CheckFailed("Instruction returns a non-scalar type!", &
I); return; } } while (false)
4370 "Instruction returns a non-scalar type!", &I)do { if (!(I.getType()->isVoidTy() || I.getType()->isFirstClassType
())) { CheckFailed("Instruction returns a non-scalar type!", &
I); return; } } while (false)
;
4371
4372 // Check that the instruction doesn't produce metadata. Calls are already
4373 // checked against the callee type.
4374 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),do { if (!(!I.getType()->isMetadataTy() || isa<CallInst
>(I) || isa<InvokeInst>(I))) { CheckFailed("Invalid use of metadata!"
, &I); return; } } while (false)
4375 "Invalid use of metadata!", &I)do { if (!(!I.getType()->isMetadataTy() || isa<CallInst
>(I) || isa<InvokeInst>(I))) { CheckFailed("Invalid use of metadata!"
, &I); return; } } while (false)
;
4376
4377 // Check that all uses of the instruction, if they are instructions
4378 // themselves, actually have parent basic blocks. If the use is not an
4379 // instruction, it is an error!
4380 for (Use &U : I.uses()) {
4381 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
4382 Assert(Used->getParent() != nullptr,do { if (!(Used->getParent() != nullptr)) { CheckFailed("Instruction referencing"
" instruction not embedded in a basic block!", &I, Used)
; return; } } while (false)
4383 "Instruction referencing"do { if (!(Used->getParent() != nullptr)) { CheckFailed("Instruction referencing"
" instruction not embedded in a basic block!", &I, Used)
; return; } } while (false)
4384 " instruction not embedded in a basic block!",do { if (!(Used->getParent() != nullptr)) { CheckFailed("Instruction referencing"
" instruction not embedded in a basic block!", &I, Used)
; return; } } while (false)
4385 &I, Used)do { if (!(Used->getParent() != nullptr)) { CheckFailed("Instruction referencing"
" instruction not embedded in a basic block!", &I, Used)
; return; } } while (false)
;
4386 else {
4387 CheckFailed("Use of instruction is not an instruction!", U);
4388 return;
4389 }
4390 }
4391
4392 // Get a pointer to the call base of the instruction if it is some form of
4393 // call.
4394 const CallBase *CBI = dyn_cast<CallBase>(&I);
4395
4396 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
4397 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I)do { if (!(I.getOperand(i) != nullptr)) { CheckFailed("Instruction has null operand!"
, &I); return; } } while (false)
;
4398
4399 // Check to make sure that only first-class-values are operands to
4400 // instructions.
4401 if (!I.getOperand(i)->getType()->isFirstClassType()) {
4402 Assert(false, "Instruction operands must be first-class values!", &I)do { if (!(false)) { CheckFailed("Instruction operands must be first-class values!"
, &I); return; } } while (false)
;
4403 }
4404
4405 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
4406 // Check to make sure that the "address of" an intrinsic function is never
4407 // taken.
4408 Assert(!F->isIntrinsic() ||do { if (!(!F->isIntrinsic() || (CBI && &CBI->
getCalledOperandUse() == &I.getOperandUse(i)))) { CheckFailed
("Cannot take the address of an intrinsic!", &I); return;
} } while (false)
4409 (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)),do { if (!(!F->isIntrinsic() || (CBI && &CBI->
getCalledOperandUse() == &I.getOperandUse(i)))) { CheckFailed
("Cannot take the address of an intrinsic!", &I); return;
} } while (false)
4410 "Cannot take the address of an intrinsic!", &I)do { if (!(!F->isIntrinsic() || (CBI && &CBI->
getCalledOperandUse() == &I.getOperandUse(i)))) { CheckFailed
("Cannot take the address of an intrinsic!", &I); return;
} } while (false)
;
4411 Assert(do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4412 !F->isIntrinsic() || isa<CallInst>(I) ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4413 F->getIntrinsicID() == Intrinsic::donothing ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4414 F->getIntrinsicID() == Intrinsic::seh_try_begin ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4415 F->getIntrinsicID() == Intrinsic::seh_try_end ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4416 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4417 F->getIntrinsicID() == Intrinsic::seh_scope_end ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4418 F->getIntrinsicID() == Intrinsic::coro_resume ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4419 F->getIntrinsicID() == Intrinsic::coro_destroy ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4420 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4421 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4422 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4423 F->getIntrinsicID() == Intrinsic::wasm_rethrow,do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4424 "Cannot invoke an intrinsic other than donothing, patchpoint, "do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4425 "statepoint, coro_resume or coro_destroy",do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
4426 &I)do { if (!(!F->isIntrinsic() || isa<CallInst>(I) || F
->getIntrinsicID() == Intrinsic::donothing || F->getIntrinsicID
() == Intrinsic::seh_try_begin || F->getIntrinsicID() == Intrinsic
::seh_try_end || F->getIntrinsicID() == Intrinsic::seh_scope_begin
|| F->getIntrinsicID() == Intrinsic::seh_scope_end || F->
getIntrinsicID() == Intrinsic::coro_resume || F->getIntrinsicID
() == Intrinsic::coro_destroy || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_void || F->getIntrinsicID() == Intrinsic
::experimental_patchpoint_i64 || F->getIntrinsicID() == Intrinsic
::experimental_gc_statepoint || F->getIntrinsicID() == Intrinsic
::wasm_rethrow)) { CheckFailed("Cannot invoke an intrinsic other than donothing, patchpoint, "
"statepoint, coro_resume or coro_destroy", &I); return; }
} while (false)
;
4427 Assert(F->getParent() == &M, "Referencing function in another module!",do { if (!(F->getParent() == &M)) { CheckFailed("Referencing function in another module!"
, &I, &M, F, F->getParent()); return; } } while (false
)
4428 &I, &M, F, F->getParent())do { if (!(F->getParent() == &M)) { CheckFailed("Referencing function in another module!"
, &I, &M, F, F->getParent()); return; } } while (false
)
;
4429 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
4430 Assert(OpBB->getParent() == BB->getParent(),do { if (!(OpBB->getParent() == BB->getParent())) { CheckFailed
("Referring to a basic block in another function!", &I); return
; } } while (false)
4431 "Referring to a basic block in another function!", &I)do { if (!(OpBB->getParent() == BB->getParent())) { CheckFailed
("Referring to a basic block in another function!", &I); return
; } } while (false)
;
4432 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
4433 Assert(OpArg->getParent() == BB->getParent(),do { if (!(OpArg->getParent() == BB->getParent())) { CheckFailed
("Referring to an argument in another function!", &I); return
; } } while (false)
4434 "Referring to an argument in another function!", &I)do { if (!(OpArg->getParent() == BB->getParent())) { CheckFailed
("Referring to an argument in another function!", &I); return
; } } while (false)
;
4435 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
4436 Assert(GV->getParent() == &M, "Referencing global in another module!", &I,do { if (!(GV->getParent() == &M)) { CheckFailed("Referencing global in another module!"
, &I, &M, GV, GV->getParent()); return; } } while (
false)
4437 &M, GV, GV->getParent())do { if (!(GV->getParent() == &M)) { CheckFailed("Referencing global in another module!"
, &I, &M, GV, GV->getParent()); return; } } while (
false)
;
4438 } else if (isa<Instruction>(I.getOperand(i))) {
4439 verifyDominatesUse(I, i);
4440 } else if (isa<InlineAsm>(I.getOperand(i))) {
4441 Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),do { if (!(CBI && &CBI->getCalledOperandUse() ==
&I.getOperandUse(i))) { CheckFailed("Cannot take the address of an inline asm!"
, &I); return; } } while (false)
4442 "Cannot take the address of an inline asm!", &I)do { if (!(CBI && &CBI->getCalledOperandUse() ==
&I.getOperandUse(i))) { CheckFailed("Cannot take the address of an inline asm!"
, &I); return; } } while (false)
;
4443 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
4444 if (CE->getType()->isPtrOrPtrVectorTy()) {
4445 // If we have a ConstantExpr pointer, we need to see if it came from an
4446 // illegal bitcast.
4447 visitConstantExprsRecursively(CE);
4448 }
4449 }
4450 }
4451
4452 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
4453 Assert(I.getType()->isFPOrFPVectorTy(),do { if (!(I.getType()->isFPOrFPVectorTy())) { CheckFailed
("fpmath requires a floating point result!", &I); return;
} } while (false)
4454 "fpmath requires a floating point result!", &I)do { if (!(I.getType()->isFPOrFPVectorTy())) { CheckFailed
("fpmath requires a floating point result!", &I); return;
} } while (false)
;
4455 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I)do { if (!(MD->getNumOperands() == 1)) { CheckFailed("fpmath takes one operand!"
, &I); return; } } while (false)
;
4456 if (ConstantFP *CFP0 =
4457 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
4458 const APFloat &Accuracy = CFP0->getValueAPF();
4459 Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),do { if (!(&Accuracy.getSemantics() == &APFloat::IEEEsingle
())) { CheckFailed("fpmath accuracy must have float type", &
I); return; } } while (false)
4460 "fpmath accuracy must have float type", &I)do { if (!(&Accuracy.getSemantics() == &APFloat::IEEEsingle
())) { CheckFailed("fpmath accuracy must have float type", &
I); return; } } while (false)
;
4461 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),do { if (!(Accuracy.isFiniteNonZero() && !Accuracy.isNegative
())) { CheckFailed("fpmath accuracy not a positive number!", &
I); return; } } while (false)
4462 "fpmath accuracy not a positive number!", &I)do { if (!(Accuracy.isFiniteNonZero() && !Accuracy.isNegative
())) { CheckFailed("fpmath accuracy not a positive number!", &
I); return; } } while (false)
;
4463 } else {
4464 Assert(false, "invalid fpmath accuracy!", &I)do { if (!(false)) { CheckFailed("invalid fpmath accuracy!", &
I); return; } } while (false)
;
4465 }
4466 }
4467
4468 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
4469 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),do { if (!(isa<LoadInst>(I) || isa<CallInst>(I) ||
isa<InvokeInst>(I))) { CheckFailed("Ranges are only for loads, calls and invokes!"
, &I); return; } } while (false)
4470 "Ranges are only for loads, calls and invokes!", &I)do { if (!(isa<LoadInst>(I) || isa<CallInst>(I) ||
isa<InvokeInst>(I))) { CheckFailed("Ranges are only for loads, calls and invokes!"
, &I); return; } } while (false)
;
4471 visitRangeMetadata(I, Range, I.getType());
4472 }
4473
4474 if (I.getMetadata(LLVMContext::MD_nonnull)) {
4475 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",do { if (!(I.getType()->isPointerTy())) { CheckFailed("nonnull applies only to pointer types"
, &I); return; } } while (false)
4476 &I)do { if (!(I.getType()->isPointerTy())) { CheckFailed("nonnull applies only to pointer types"
, &I); return; } } while (false)
;
4477 Assert(isa<LoadInst>(I),do { if (!(isa<LoadInst>(I))) { CheckFailed("nonnull applies only to load instructions, use attributes"
" for calls or invokes", &I); return; } } while (false)
4478 "nonnull applies only to load instructions, use attributes"do { if (!(isa<LoadInst>(I))) { CheckFailed("nonnull applies only to load instructions, use attributes"
" for calls or invokes", &I); return; } } while (false)
4479 " for calls or invokes",do { if (!(isa<LoadInst>(I))) { CheckFailed("nonnull applies only to load instructions, use attributes"
" for calls or invokes", &I); return; } } while (false)
4480 &I)do { if (!(isa<LoadInst>(I))) { CheckFailed("nonnull applies only to load instructions, use attributes"
" for calls or invokes", &I); return; } } while (false)
;
4481 }
4482
4483 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
4484 visitDereferenceableMetadata(I, MD);
4485
4486 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
4487 visitDereferenceableMetadata(I, MD);
4488
4489 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
4490 TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
4491
4492 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
4493 Assert(I.getType()->isPointerTy(), "align applies only to pointer types",do { if (!(I.getType()->isPointerTy())) { CheckFailed("align applies only to pointer types"
, &I); return; } } while (false)
4494 &I)do { if (!(I.getType()->isPointerTy())) { CheckFailed("align applies only to pointer types"
, &I); return; } } while (false)
;
4495 Assert(isa<LoadInst>(I), "align applies only to load instructions, "do { if (!(isa<LoadInst>(I))) { CheckFailed("align applies only to load instructions, "
"use attributes for calls or invokes", &I); return; } } while
(false)
4496 "use attributes for calls or invokes", &I)do { if (!(isa<LoadInst>(I))) { CheckFailed("align applies only to load instructions, "
"use attributes for calls or invokes", &I); return; } } while
(false)
;
4497 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I)do { if (!(AlignMD->getNumOperands() == 1)) { CheckFailed(
"align takes one operand!", &I); return; } } while (false
)
;
4498 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
4499 Assert(CI && CI->getType()->isIntegerTy(64),do { if (!(CI && CI->getType()->isIntegerTy(64)
)) { CheckFailed("align metadata value must be an i64!", &
I); return; } } while (false)
4500 "align metadata value must be an i64!", &I)do { if (!(CI && CI->getType()->isIntegerTy(64)
)) { CheckFailed("align metadata value must be an i64!", &
I); return; } } while (false)
;
4501 uint64_t Align = CI->getZExtValue();
4502 Assert(isPowerOf2_64(Align),do { if (!(isPowerOf2_64(Align))) { CheckFailed("align metadata value must be a power of 2!"
, &I); return; } } while (false)
4503 "align metadata value must be a power of 2!", &I)do { if (!(isPowerOf2_64(Align))) { CheckFailed("align metadata value must be a power of 2!"
, &I); return; } } while (false)
;
4504 Assert(Align <= Value::MaximumAlignment,do { if (!(Align <= Value::MaximumAlignment)) { CheckFailed
("alignment is larger that implementation defined limit", &
I); return; } } while (false)
4505 "alignment is larger that implementation defined limit", &I)do { if (!(Align <= Value::MaximumAlignment)) { CheckFailed
("alignment is larger that implementation defined limit", &
I); return; } } while (false)
;
4506 }
4507
4508 if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
4509 visitProfMetadata(I, MD);
4510
4511 if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
4512 visitAnnotationMetadata(Annotation);
4513
4514 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
4515 AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N)do { if (!(isa<DILocation>(N))) { DebugInfoCheckFailed(
"invalid !dbg metadata attachment", &I, N); return; } } while
(false)
;
4516 visitMDNode(*N, AreDebugLocsAllowed::Yes);
4517 }
4518
4519 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
4520 verifyFragmentExpression(*DII);
4521 verifyNotEntryValue(*DII);
4522 }
4523
4524 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4525 I.getAllMetadata(MDs);
4526 for (auto Attachment : MDs) {
4527 unsigned Kind = Attachment.first;
4528 auto AllowLocs =
4529 (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
4530 ? AreDebugLocsAllowed::Yes
4531 : AreDebugLocsAllowed::No;
4532 visitMDNode(*Attachment.second, AllowLocs);
4533 }
4534
4535 InstsInThisBlock.insert(&I);
4536}
4537
4538/// Allow intrinsics to be verified in different ways.
4539void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
4540 Function *IF = Call.getCalledFunction();
4541 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",do { if (!(IF->isDeclaration())) { CheckFailed("Intrinsic functions should never be defined!"
, IF); return; } } while (false)
4542 IF)do { if (!(IF->isDeclaration())) { CheckFailed("Intrinsic functions should never be defined!"
, IF); return; } } while (false)
;
4543
4544 // Verify that the intrinsic prototype lines up with what the .td files
4545 // describe.
4546 FunctionType *IFTy = IF->getFunctionType();
4547 bool IsVarArg = IFTy->isVarArg();
4548
4549 SmallVector<Intrinsic::IITDescriptor, 8> Table;
4550 getIntrinsicInfoTableEntries(ID, Table);
4551 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
4552
4553 // Walk the descriptors to extract overloaded types.
4554 SmallVector<Type *, 4> ArgTys;
4555 Intrinsic::MatchIntrinsicTypesResult Res =
4556 Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
4557 Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,do { if (!(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet))
{ CheckFailed("Intrinsic has incorrect return type!", IF); return
; } } while (false)
4558 "Intrinsic has incorrect return type!", IF)do { if (!(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet))
{ CheckFailed("Intrinsic has incorrect return type!", IF); return
; } } while (false)
;
4559 Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,do { if (!(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg))
{ CheckFailed("Intrinsic has incorrect argument type!", IF);
return; } } while (false)
4560 "Intrinsic has incorrect argument type!", IF)do { if (!(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg))
{ CheckFailed("Intrinsic has incorrect argument type!", IF);
return; } } while (false)
;
4561
4562 // Verify if the intrinsic call matches the vararg property.
4563 if (IsVarArg)
4564 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),do { if (!(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef
))) { CheckFailed("Intrinsic was not defined with variable arguments!"
, IF); return; } } while (false)
4565 "Intrinsic was not defined with variable arguments!", IF)do { if (!(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef
))) { CheckFailed("Intrinsic was not defined with variable arguments!"
, IF); return; } } while (false)
;
4566 else
4567 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),do { if (!(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef
))) { CheckFailed("Callsite was not defined with variable arguments!"
, IF); return; } } while (false)
4568 "Callsite was not defined with variable arguments!", IF)do { if (!(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef
))) { CheckFailed("Callsite was not defined with variable arguments!"
, IF); return; } } while (false)
;
4569
4570 // All descriptors should be absorbed by now.
4571 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF)do { if (!(TableRef.empty())) { CheckFailed("Intrinsic has too few arguments!"
, IF); return; } } while (false)
;
4572
4573 // Now that we have the intrinsic ID and the actual argument types (and we
4574 // know they are legal for the intrinsic!) get the intrinsic name through the
4575 // usual means. This allows us to verify the mangling of argument types into
4576 // the name.
4577 const std::string ExpectedName =
4578 Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
4579 Assert(ExpectedName == IF->getName(),do { if (!(ExpectedName == IF->getName())) { CheckFailed("Intrinsic name not mangled correctly for type arguments! "
"Should be: " + ExpectedName, IF); return; } } while (false)
4580 "Intrinsic name not mangled correctly for type arguments! "do { if (!(ExpectedName == IF->getName())) { CheckFailed("Intrinsic name not mangled correctly for type arguments! "
"Should be: " + ExpectedName, IF); return; } } while (false)
4581 "Should be: " +do { if (!(ExpectedName == IF->getName())) { CheckFailed("Intrinsic name not mangled correctly for type arguments! "
"Should be: " + ExpectedName, IF); return; } } while (false)
4582 ExpectedName,do { if (!(ExpectedName == IF->getName())) { CheckFailed("Intrinsic name not mangled correctly for type arguments! "
"Should be: " + ExpectedName, IF); return; } } while (false)
4583 IF)do { if (!(ExpectedName == IF->getName())) { CheckFailed("Intrinsic name not mangled correctly for type arguments! "
"Should be: " + ExpectedName, IF); return; } } while (false)
;
4584
4585 // If the intrinsic takes MDNode arguments, verify that they are either global
4586 // or are local to *this* function.
4587 for (Value *V : Call.args()) {
4588 if (auto *MD = dyn_cast<MetadataAsValue>(V))
4589 visitMetadataAsValue(*MD, Call.getCaller());
4590 if (auto *Const = dyn_cast<Constant>(V))
4591 Assert(!Const->getType()->isX86_AMXTy(),do { if (!(!Const->getType()->isX86_AMXTy())) { CheckFailed
("const x86_amx is not allowed in argument!"); return; } } while
(false)
4592 "const x86_amx is not allowed in argument!")do { if (!(!Const->getType()->isX86_AMXTy())) { CheckFailed
("const x86_amx is not allowed in argument!"); return; } } while
(false)
;
4593 }
4594
4595 switch (ID) {
4596 default:
4597 break;
4598 case Intrinsic::assume: {
4599 for (auto &Elem : Call.bundle_op_infos()) {
4600 Assert(Elem.Tag->getKey() == "ignore" ||do { if (!(Elem.Tag->getKey() == "ignore" || Attribute::isExistingAttribute
(Elem.Tag->getKey()))) { CheckFailed("tags must be valid attribute names"
); return; } } while (false)
4601 Attribute::isExistingAttribute(Elem.Tag->getKey()),do { if (!(Elem.Tag->getKey() == "ignore" || Attribute::isExistingAttribute
(Elem.Tag->getKey()))) { CheckFailed("tags must be valid attribute names"
); return; } } while (false)
4602 "tags must be valid attribute names")do { if (!(Elem.Tag->getKey() == "ignore" || Attribute::isExistingAttribute
(Elem.Tag->getKey()))) { CheckFailed("tags must be valid attribute names"
); return; } } while (false)
;
4603 Attribute::AttrKind Kind =
4604 Attribute::getAttrKindFromName(Elem.Tag->getKey());
4605 unsigned ArgCount = Elem.End - Elem.Begin;
4606 if (Kind == Attribute::Alignment) {
4607 Assert(ArgCount <= 3 && ArgCount >= 2,do { if (!(ArgCount <= 3 && ArgCount >= 2)) { CheckFailed
("alignment assumptions should have 2 or 3 arguments"); return
; } } while (false)
4608 "alignment assumptions should have 2 or 3 arguments")do { if (!(ArgCount <= 3 && ArgCount >= 2)) { CheckFailed
("alignment assumptions should have 2 or 3 arguments"); return
; } } while (false)
;
4609 Assert(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),do { if (!(Call.getOperand(Elem.Begin)->getType()->isPointerTy
())) { CheckFailed("first argument should be a pointer"); return
; } } while (false)
4610 "first argument should be a pointer")do { if (!(Call.getOperand(Elem.Begin)->getType()->isPointerTy
())) { CheckFailed("first argument should be a pointer"); return
; } } while (false)
;
4611 Assert(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),do { if (!(Call.getOperand(Elem.Begin + 1)->getType()->
isIntegerTy())) { CheckFailed("second argument should be an integer"
); return; } } while (false)
4612 "second argument should be an integer")do { if (!(Call.getOperand(Elem.Begin + 1)->getType()->
isIntegerTy())) { CheckFailed("second argument should be an integer"
); return; } } while (false)
;
4613 if (ArgCount == 3)
4614 Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),do { if (!(Call.getOperand(Elem.Begin + 2)->getType()->
isIntegerTy())) { CheckFailed("third argument should be an integer if present"
); return; } } while (false)
4615 "third argument should be an integer if present")do { if (!(Call.getOperand(Elem.Begin + 2)->getType()->
isIntegerTy())) { CheckFailed("third argument should be an integer if present"
); return; } } while (false)
;
4616 return;
4617 }
4618 Assert(ArgCount <= 2, "to many arguments")do { if (!(ArgCount <= 2)) { CheckFailed("to many arguments"
); return; } } while (false)
;
4619 if (Kind == Attribute::None)
4620 break;
4621 if (Attribute::isIntAttrKind(Kind)) {
4622 Assert(ArgCount == 2, "this attribute should have 2 arguments")do { if (!(ArgCount == 2)) { CheckFailed("this attribute should have 2 arguments"
); return; } } while (false)
;
4623 Assert(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),do { if (!(isa<ConstantInt>(Call.getOperand(Elem.Begin +
1)))) { CheckFailed("the second argument should be a constant integral value"
); return; } } while (false)
4624 "the second argument should be a constant integral value")do { if (!(isa<ConstantInt>(Call.getOperand(Elem.Begin +
1)))) { CheckFailed("the second argument should be a constant integral value"
); return; } } while (false)
;
4625 } else if (Attribute::canUseAsParamAttr(Kind)) {
4626 Assert((ArgCount) == 1, "this attribute should have one argument")do { if (!((ArgCount) == 1)) { CheckFailed("this attribute should have one argument"
); return; } } while (false)
;
4627 } else if (Attribute::canUseAsFnAttr(Kind)) {
4628 Assert((ArgCount) == 0, "this attribute has no argument")do { if (!((ArgCount) == 0)) { CheckFailed("this attribute has no argument"
); return; } } while (false)
;
4629 }
4630 }
4631 break;
4632 }
4633 case Intrinsic::coro_id: {
4634 auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
4635 if (isa<ConstantPointerNull>(InfoArg))
4636 break;
4637 auto *GV = dyn_cast<GlobalVariable>(InfoArg);
4638 Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),do { if (!(GV && GV->isConstant() && GV->
hasDefinitiveInitializer())) { CheckFailed("info argument of llvm.coro.id must refer to an initialized "
"constant"); return; } } while (false)
4639 "info argument of llvm.coro.id must refer to an initialized "do { if (!(GV && GV->isConstant() && GV->
hasDefinitiveInitializer())) { CheckFailed("info argument of llvm.coro.id must refer to an initialized "
"constant"); return; } } while (false)
4640 "constant")do { if (!(GV && GV->isConstant() && GV->
hasDefinitiveInitializer())) { CheckFailed("info argument of llvm.coro.id must refer to an initialized "
"constant"); return; } } while (false)
;
4641 Constant *Init = GV->getInitializer();
4642 Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),do { if (!(isa<ConstantStruct>(Init) || isa<ConstantArray
>(Init))) { CheckFailed("info argument of llvm.coro.id must refer to either a struct or "
"an array"); return; } } while (false)
4643 "info argument of llvm.coro.id must refer to either a struct or "do { if (!(isa<ConstantStruct>(Init) || isa<ConstantArray
>(Init))) { CheckFailed("info argument of llvm.coro.id must refer to either a struct or "
"an array"); return; } } while (false)
4644 "an array")do { if (!(isa<ConstantStruct>(Init) || isa<ConstantArray
>(Init))) { CheckFailed("info argument of llvm.coro.id must refer to either a struct or "
"an array"); return; } } while (false)
;
4645 break;
4646 }
4647#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
4648 case Intrinsic::INTRINSIC:
4649#include "llvm/IR/ConstrainedOps.def"
4650 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
4651 break;
4652 case Intrinsic::dbg_declare: // llvm.dbg.declare
4653 Assert(isa<MetadataAsValue>(Call.getArgOperand(0)),do { if (!(isa<MetadataAsValue>(Call.getArgOperand(0)))
) { CheckFailed("invalid llvm.dbg.declare intrinsic call 1", Call
); return; } } while (false)
4654 "invalid llvm.dbg.declare intrinsic call 1", Call)do { if (!(isa<MetadataAsValue>(Call.getArgOperand(0)))
) { CheckFailed("invalid llvm.dbg.declare intrinsic call 1", Call
); return; } } while (false)
;
4655 visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
4656 break;
4657 case Intrinsic::dbg_addr: // llvm.dbg.addr
4658 visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
4659 break;
4660 case Intrinsic::dbg_value: // llvm.dbg.value
4661 visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
4662 break;
4663 case Intrinsic::dbg_label: // llvm.dbg.label
4664 visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
4665 break;
4666 case Intrinsic::memcpy:
4667 case Intrinsic::memcpy_inline:
4668 case Intrinsic::memmove:
4669 case Intrinsic::memset: {
4670 const auto *MI = cast<MemIntrinsic>(&Call);
4671 auto IsValidAlignment = [&](unsigned Alignment) -> bool {
4672 return Alignment == 0 || isPowerOf2_32(Alignment);
4673 };
4674 Assert(IsValidAlignment(MI->getDestAlignment()),do { if (!(IsValidAlignment(MI->getDestAlignment()))) { CheckFailed
("alignment of arg 0 of memory intrinsic must be 0 or a power of 2"
, Call); return; } } while (false)
4675 "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",do { if (!(IsValidAlignment(MI->getDestAlignment()))) { CheckFailed
("alignment of arg 0 of memory intrinsic must be 0 or a power of 2"
, Call); return; } } while (false)
4676 Call)do { if (!(IsValidAlignment(MI->getDestAlignment()))) { CheckFailed
("alignment of arg 0 of memory intrinsic must be 0 or a power of 2"
, Call); return; } } while (false)
;
4677 if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
4678 Assert(IsValidAlignment(MTI->getSourceAlignment()),do { if (!(IsValidAlignment(MTI->getSourceAlignment()))) {
CheckFailed("alignment of arg 1 of memory intrinsic must be 0 or a power of 2"
, Call); return; } } while (false)
4679 "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",do { if (!(IsValidAlignment(MTI->getSourceAlignment()))) {
CheckFailed("alignment of arg 1 of memory intrinsic must be 0 or a power of 2"
, Call); return; } } while (false)
4680 Call)do { if (!(IsValidAlignment(MTI->getSourceAlignment()))) {
CheckFailed("alignment of arg 1 of memory intrinsic must be 0 or a power of 2"
, Call); return; } } while (false)
;
4681 }
4682
4683 break;
4684 }
4685 case Intrinsic::memcpy_element_unordered_atomic:
4686 case Intrinsic::memmove_element_unordered_atomic:
4687 case Intrinsic::memset_element_unordered_atomic: {
4688 const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
4689
4690 ConstantInt *ElementSizeCI =
4691 cast<ConstantInt>(AMI->getRawElementSizeInBytes());
4692 const APInt &ElementSizeVal = ElementSizeCI->getValue();
4693 Assert(ElementSizeVal.isPowerOf2(),do { if (!(ElementSizeVal.isPowerOf2())) { CheckFailed("element size of the element-wise atomic memory intrinsic "
"must be a power of 2", Call); return; } } while (false)
4694 "element size of the element-wise atomic memory intrinsic "do { if (!(ElementSizeVal.isPowerOf2())) { CheckFailed("element size of the element-wise atomic memory intrinsic "
"must be a power of 2", Call); return; } } while (false)
4695 "must be a power of 2",do { if (!(ElementSizeVal.isPowerOf2())) { CheckFailed("element size of the element-wise atomic memory intrinsic "
"must be a power of 2", Call); return; } } while (false)
4696 Call)do { if (!(ElementSizeVal.isPowerOf2())) { CheckFailed("element size of the element-wise atomic memory intrinsic "
"must be a power of 2", Call); return; } } while (false)
;
4697
4698 auto IsValidAlignment = [&](uint64_t Alignment) {
4699 return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
4700 };
4701 uint64_t DstAlignment = AMI->getDestAlignment();
4702 Assert(IsValidAlignment(DstAlignment),do { if (!(IsValidAlignment(DstAlignment))) { CheckFailed("incorrect alignment of the destination argument"
, Call); return; } } while (false)
4703 "incorrect alignment of the destination argument", Call)do { if (!(IsValidAlignment(DstAlignment))) { CheckFailed("incorrect alignment of the destination argument"
, Call); return; } } while (false)
;
4704 if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
4705 uint64_t SrcAlignment = AMT->getSourceAlignment();
4706 Assert(IsValidAlignment(SrcAlignment),do { if (!(IsValidAlignment(SrcAlignment))) { CheckFailed("incorrect alignment of the source argument"
, Call); return; } } while (false)
4707 "incorrect alignment of the source argument", Call)do { if (!(IsValidAlignment(SrcAlignment))) { CheckFailed("incorrect alignment of the source argument"
, Call); return; } } while (false)
;
4708 }
4709 break;
4710 }
4711 case Intrinsic::call_preallocated_setup: {
4712 auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
4713 Assert(NumArgs != nullptr,do { if (!(NumArgs != nullptr)) { CheckFailed("llvm.call.preallocated.setup argument must be a constant"
); return; } } while (false)
4714 "llvm.call.preallocated.setup argument must be a constant")do { if (!(NumArgs != nullptr)) { CheckFailed("llvm.call.preallocated.setup argument must be a constant"
); return; } } while (false)
;
4715 bool FoundCall = false;
4716 for (User *U : Call.users()) {
4717 auto *UseCall = dyn_cast<CallBase>(U);
4718 Assert(UseCall != nullptr,do { if (!(UseCall != nullptr)) { CheckFailed("Uses of llvm.call.preallocated.setup must be calls"
); return; } } while (false)
4719 "Uses of llvm.call.preallocated.setup must be calls")do { if (!(UseCall != nullptr)) { CheckFailed("Uses of llvm.call.preallocated.setup must be calls"
); return; } } while (false)
;
4720 const Function *Fn = UseCall->getCalledFunction();
4721 if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
4722 auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
4723 Assert(AllocArgIndex != nullptr,do { if (!(AllocArgIndex != nullptr)) { CheckFailed("llvm.call.preallocated.alloc arg index must be a constant"
); return; } } while (false)
4724 "llvm.call.preallocated.alloc arg index must be a constant")do { if (!(AllocArgIndex != nullptr)) { CheckFailed("llvm.call.preallocated.alloc arg index must be a constant"
); return; } } while (false)
;
4725 auto AllocArgIndexInt = AllocArgIndex->getValue();
4726 Assert(AllocArgIndexInt.sge(0) &&do { if (!(AllocArgIndexInt.sge(0) && AllocArgIndexInt
.slt(NumArgs->getValue()))) { CheckFailed("llvm.call.preallocated.alloc arg index must be between 0 and "
"corresponding " "llvm.call.preallocated.setup's argument count"
); return; } } while (false)
4727 AllocArgIndexInt.slt(NumArgs->getValue()),do { if (!(AllocArgIndexInt.sge(0) && AllocArgIndexInt
.slt(NumArgs->getValue()))) { CheckFailed("llvm.call.preallocated.alloc arg index must be between 0 and "
"corresponding " "llvm.call.preallocated.setup's argument count"
); return; } } while (false)
4728 "llvm.call.preallocated.alloc arg index must be between 0 and "do { if (!(AllocArgIndexInt.sge(0) && AllocArgIndexInt
.slt(NumArgs->getValue()))) { CheckFailed("llvm.call.preallocated.alloc arg index must be between 0 and "
"corresponding " "llvm.call.preallocated.setup's argument count"
); return; } } while (false)
4729 "corresponding "do { if (!(AllocArgIndexInt.sge(0) && AllocArgIndexInt
.slt(NumArgs->getValue()))) { CheckFailed("llvm.call.preallocated.alloc arg index must be between 0 and "
"corresponding " "llvm.call.preallocated.setup's argument count"
); return; } } while (false)
4730 "llvm.call.preallocated.setup's argument count")do { if (!(AllocArgIndexInt.sge(0) && AllocArgIndexInt
.slt(NumArgs->getValue()))) { CheckFailed("llvm.call.preallocated.alloc arg index must be between 0 and "
"corresponding " "llvm.call.preallocated.setup's argument count"
); return; } } while (false)
;
4731 } else if (Fn && Fn->getIntrinsicID() ==
4732 Intrinsic::call_preallocated_teardown) {
4733 // nothing to do
4734 } else {
4735 Assert(!FoundCall, "Can have at most one call corresponding to a "do { if (!(!FoundCall)) { CheckFailed("Can have at most one call corresponding to a "
"llvm.call.preallocated.setup"); return; } } while (false)
4736 "llvm.call.preallocated.setup")do { if (!(!FoundCall)) { CheckFailed("Can have at most one call corresponding to a "
"llvm.call.preallocated.setup"); return; } } while (false)
;
4737 FoundCall = true;
4738 size_t NumPreallocatedArgs = 0;
4739 for (unsigned i = 0; i < UseCall->getNumArgOperands(); i++) {
4740 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
4741 ++NumPreallocatedArgs;
4742 }
4743 }
4744 Assert(NumPreallocatedArgs != 0,do { if (!(NumPreallocatedArgs != 0)) { CheckFailed("cannot use preallocated intrinsics on a call without "
"preallocated arguments"); return; } } while (false)
4745 "cannot use preallocated intrinsics on a call without "do { if (!(NumPreallocatedArgs != 0)) { CheckFailed("cannot use preallocated intrinsics on a call without "
"preallocated arguments"); return; } } while (false)
4746 "preallocated arguments")do { if (!(NumPreallocatedArgs != 0)) { CheckFailed("cannot use preallocated intrinsics on a call without "
"preallocated arguments"); return; } } while (false)
;
4747 Assert(NumArgs->equalsInt(NumPreallocatedArgs),do { if (!(NumArgs->equalsInt(NumPreallocatedArgs))) { CheckFailed
("llvm.call.preallocated.setup arg size must be equal to number "
"of preallocated arguments " "at call site", Call, *UseCall)
; return; } } while (false)
4748 "llvm.call.preallocated.setup arg size must be equal to number "do { if (!(NumArgs->equalsInt(NumPreallocatedArgs))) { CheckFailed
("llvm.call.preallocated.setup arg size must be equal to number "
"of preallocated arguments " "at call site", Call, *UseCall)
; return; } } while (false)
4749 "of preallocated arguments "do { if (!(NumArgs->equalsInt(NumPreallocatedArgs))) { CheckFailed
("llvm.call.preallocated.setup arg size must be equal to number "
"of preallocated arguments " "at call site", Call, *UseCall)
; return; } } while (false)
4750 "at call site",do { if (!(NumArgs->equalsInt(NumPreallocatedArgs))) { CheckFailed
("llvm.call.preallocated.setup arg size must be equal to number "
"of preallocated arguments " "at call site", Call, *UseCall)
; return; } } while (false)
4751 Call, *UseCall)do { if (!(NumArgs->equalsInt(NumPreallocatedArgs))) { CheckFailed
("llvm.call.preallocated.setup arg size must be equal to number "
"of preallocated arguments " "at call site", Call, *UseCall)
; return; } } while (false)
;
4752 // getOperandBundle() cannot be called if more than one of the operand
4753 // bundle exists. There is already a check elsewhere for this, so skip
4754 // here if we see more than one.
4755 if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
4756 1) {
4757 return;
4758 }
4759 auto PreallocatedBundle =
4760 UseCall->getOperandBundle(LLVMContext::OB_preallocated);
4761 Assert(PreallocatedBundle,do { if (!(PreallocatedBundle)) { CheckFailed("Use of llvm.call.preallocated.setup outside intrinsics "
"must be in \"preallocated\" operand bundle"); return; } } while
(false)
4762 "Use of llvm.call.preallocated.setup outside intrinsics "do { if (!(PreallocatedBundle)) { CheckFailed("Use of llvm.call.preallocated.setup outside intrinsics "
"must be in \"preallocated\" operand bundle"); return; } } while
(false)
4763 "must be in \"preallocated\" operand bundle")do { if (!(PreallocatedBundle)) { CheckFailed("Use of llvm.call.preallocated.setup outside intrinsics "
"must be in \"preallocated\" operand bundle"); return; } } while
(false)
;
4764 Assert(PreallocatedBundle->Inputs.front().get() == &Call,do { if (!(PreallocatedBundle->Inputs.front().get() == &
Call)) { CheckFailed("preallocated bundle must have token from corresponding "
"llvm.call.preallocated.setup"); return; } } while (false)
4765 "preallocated bundle must have token from corresponding "do { if (!(PreallocatedBundle->Inputs.front().get() == &
Call)) { CheckFailed("preallocated bundle must have token from corresponding "
"llvm.call.preallocated.setup"); return; } } while (false)
4766 "llvm.call.preallocated.setup")do { if (!(PreallocatedBundle->Inputs.front().get() == &
Call)) { CheckFailed("preallocated bundle must have token from corresponding "
"llvm.call.preallocated.setup"); return; } } while (false)
;
4767 }
4768 }
4769 break;
4770 }
4771 case Intrinsic::call_preallocated_arg: {
4772 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4773 Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==do { if (!(Token && Token->getCalledFunction()->
getIntrinsicID() == Intrinsic::call_preallocated_setup)) { CheckFailed
("llvm.call.preallocated.arg token argument must be a " "llvm.call.preallocated.setup"
); return; } } while (false)
4774 Intrinsic::call_preallocated_setup,do { if (!(Token && Token->getCalledFunction()->
getIntrinsicID() == Intrinsic::call_preallocated_setup)) { CheckFailed
("llvm.call.preallocated.arg token argument must be a " "llvm.call.preallocated.setup"
); return; } } while (false)
4775 "llvm.call.preallocated.arg token argument must be a "do { if (!(Token && Token->getCalledFunction()->
getIntrinsicID() == Intrinsic::call_preallocated_setup)) { CheckFailed
("llvm.call.preallocated.arg token argument must be a " "llvm.call.preallocated.setup"
); return; } } while (false)
4776 "llvm.call.preallocated.setup")do { if (!(Token && Token->getCalledFunction()->
getIntrinsicID() == Intrinsic::call_preallocated_setup)) { CheckFailed
("llvm.call.preallocated.arg token argument must be a " "llvm.call.preallocated.setup"
); return; } } while (false)
;
4777 Assert(Call.hasFnAttr(Attribute::Preallocated),do { if (!(Call.hasFnAttr(Attribute::Preallocated))) { CheckFailed
("llvm.call.preallocated.arg must be called with a \"preallocated\" "
"call site attribute"); return; } } while (false)
4778 "llvm.call.preallocated.arg must be called with a \"preallocated\" "do { if (!(Call.hasFnAttr(Attribute::Preallocated))) { CheckFailed
("llvm.call.preallocated.arg must be called with a \"preallocated\" "
"call site attribute"); return; } } while (false)
4779 "call site attribute")do { if (!(Call.hasFnAttr(Attribute::Preallocated))) { CheckFailed
("llvm.call.preallocated.arg must be called with a \"preallocated\" "
"call site attribute"); return; } } while (false)
;
4780 break;
4781 }
4782 case Intrinsic::call_preallocated_teardown: {
4783 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4784 Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==do { if (!(Token && Token->getCalledFunction()->
getIntrinsicID() == Intrinsic::call_preallocated_setup)) { CheckFailed
("llvm.call.preallocated.teardown token argument must be a " "llvm.call.preallocated.setup"
); return; } } while (false)
4785 Intrinsic::call_preallocated_setup,do { if (!(Token && Token->getCalledFunction()->
getIntrinsicID() == Intrinsic::call_preallocated_setup)) { CheckFailed
("llvm.call.preallocated.teardown token argument must be a " "llvm.call.preallocated.setup"
); return; } } while (false)
4786 "llvm.call.preallocated.teardown token argument must be a "do { if (!(Token && Token->getCalledFunction()->
getIntrinsicID() == Intrinsic::call_preallocated_setup)) { CheckFailed
("llvm.call.preallocated.teardown token argument must be a " "llvm.call.preallocated.setup"
); return; } } while (false)
4787 "llvm.call.preallocated.setup")do { if (!(Token && Token->getCalledFunction()->
getIntrinsicID() == Intrinsic::call_preallocated_setup)) { CheckFailed
("llvm.call.preallocated.teardown token argument must be a " "llvm.call.preallocated.setup"
); return; } } while (false)
;
4788 break;
4789 }
4790 case Intrinsic::gcroot:
4791 case Intrinsic::gcwrite:
4792 case Intrinsic::gcread:
4793 if (ID == Intrinsic::gcroot) {
4794 AllocaInst *AI =
4795 dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
4796 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call)do { if (!(AI)) { CheckFailed("llvm.gcroot parameter #1 must be an alloca."
, Call); return; } } while (false)
;
4797 Assert(isa<Constant>(Call.getArgOperand(1)),do { if (!(isa<Constant>(Call.getArgOperand(1)))) { CheckFailed
("llvm.gcroot parameter #2 must be a constant.", Call); return
; } } while (false)
4798 "llvm.gcroot parameter #2 must be a constant.", Call)do { if (!(isa<Constant>(Call.getArgOperand(1)))) { CheckFailed
("llvm.gcroot parameter #2 must be a constant.", Call); return
; } } while (false)
;
4799 if (!AI->getAllocatedType()->isPointerTy()) {
4800 Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)),do { if (!(!isa<ConstantPointerNull>(Call.getArgOperand
(1)))) { CheckFailed("llvm.gcroot parameter #1 must either be a pointer alloca, "
"or argument #2 must be a non-null constant.", Call); return
; } } while (false)
4801 "llvm.gcroot parameter #1 must either be a pointer alloca, "do { if (!(!isa<ConstantPointerNull>(Call.getArgOperand
(1)))) { CheckFailed("llvm.gcroot parameter #1 must either be a pointer alloca, "
"or argument #2 must be a non-null constant.", Call); return
; } } while (false)
4802 "or argument #2 must be a non-null constant.",do { if (!(!isa<ConstantPointerNull>(Call.getArgOperand
(1)))) { CheckFailed("llvm.gcroot parameter #1 must either be a pointer alloca, "
"or argument #2 must be a non-null constant.", Call); return
; } } while (false)
4803 Call)do { if (!(!isa<ConstantPointerNull>(Call.getArgOperand
(1)))) { CheckFailed("llvm.gcroot parameter #1 must either be a pointer alloca, "
"or argument #2 must be a non-null constant.", Call); return
; } } while (false)
;
4804 }
4805 }
4806
4807 Assert(Call.getParent()->getParent()->hasGC(),do { if (!(Call.getParent()->getParent()->hasGC())) { CheckFailed
("Enclosing function does not use GC.", Call); return; } } while
(false)
4808 "Enclosing function does not use GC.", Call)do { if (!(Call.getParent()->getParent()->hasGC())) { CheckFailed
("Enclosing function does not use GC.", Call); return; } } while
(false)
;
4809 break;
4810 case Intrinsic::init_trampoline:
4811 Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),do { if (!(isa<Function>(Call.getArgOperand(1)->stripPointerCasts
()))) { CheckFailed("llvm.init_trampoline parameter #2 must resolve to a function."
, Call); return; } } while (false)
4812 "llvm.init_trampoline parameter #2 must resolve to a function.",do { if (!(isa<Function>(Call.getArgOperand(1)->stripPointerCasts
()))) { CheckFailed("llvm.init_trampoline parameter #2 must resolve to a function."
, Call); return; } } while (false)
4813 Call)do { if (!(isa<Function>(Call.getArgOperand(1)->stripPointerCasts
()))) { CheckFailed("llvm.init_trampoline parameter #2 must resolve to a function."
, Call); return; } } while (false)
;
4814 break;
4815 case Intrinsic::prefetch:
4816 Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 &&do { if (!(cast<ConstantInt>(Call.getArgOperand(1))->
getZExtValue() < 2 && cast<ConstantInt>(Call
.getArgOperand(2))->getZExtValue() < 4)) { CheckFailed(
"invalid arguments to llvm.prefetch", Call); return; } } while
(false)
4817 cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,do { if (!(cast<ConstantInt>(Call.getArgOperand(1))->
getZExtValue() < 2 && cast<ConstantInt>(Call
.getArgOperand(2))->getZExtValue() < 4)) { CheckFailed(
"invalid arguments to llvm.prefetch", Call); return; } } while
(false)
4818 "invalid arguments to llvm.prefetch", Call)do { if (!(cast<ConstantInt>(Call.getArgOperand(1))->
getZExtValue() < 2 && cast<ConstantInt>(Call
.getArgOperand(2))->getZExtValue() < 4)) { CheckFailed(
"invalid arguments to llvm.prefetch", Call); return; } } while
(false)
;
4819 break;
4820 case Intrinsic::stackprotector:
4821 Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),do { if (!(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts
()))) { CheckFailed("llvm.stackprotector parameter #2 must resolve to an alloca."
, Call); return; } } while (false)
4822 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call)do { if (!(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts
()))) { CheckFailed("llvm.stackprotector parameter #2 must resolve to an alloca."
, Call); return; } } while (false)
;
4823 break;
4824 case Intrinsic::localescape: {
4825 BasicBlock *BB = Call.getParent();
4826 Assert(BB == &BB->getParent()->front(),do { if (!(BB == &BB->getParent()->front())) { CheckFailed
("llvm.localescape used outside of entry block", Call); return
; } } while (false)
4827 "llvm.localescape used outside of entry block", Call)do { if (!(BB == &BB->getParent()->front())) { CheckFailed
("llvm.localescape used outside of entry block", Call); return
; } } while (false)
;
4828 Assert(!SawFrameEscape,do { if (!(!SawFrameEscape)) { CheckFailed("multiple calls to llvm.localescape in one function"
, Call); return; } } while (false)
4829 "multiple calls to llvm.localescape in one function", Call)do { if (!(!SawFrameEscape)) { CheckFailed("multiple calls to llvm.localescape in one function"
, Call); return; } } while (false)
;
4830 for (Value *Arg : Call.args()) {
4831 if (isa<ConstantPointerNull>(Arg))
4832 continue; // Null values are allowed as placeholders.
4833 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
4834 Assert(AI && AI->isStaticAlloca(),do { if (!(AI && AI->isStaticAlloca())) { CheckFailed
("llvm.localescape only accepts static allocas", Call); return
; } } while (false)
4835 "llvm.localescape only accepts static allocas", Call)do { if (!(AI && AI->isStaticAlloca())) { CheckFailed
("llvm.localescape only accepts static allocas", Call); return
; } } while (false)
;
4836 }
4837 FrameEscapeInfo[BB->getParent()].first = Call.getNumArgOperands();
4838 SawFrameEscape = true;
4839 break;
4840 }
4841 case Intrinsic::localrecover: {
4842 Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
4843 Function *Fn = dyn_cast<Function>(FnArg);
4844 Assert(Fn && !Fn->isDeclaration(),do { if (!(Fn && !Fn->isDeclaration())) { CheckFailed
("llvm.localrecover first " "argument must be function defined in this module"
, Call); return; } } while (false)
4845 "llvm.localrecover first "do { if (!(Fn && !Fn->isDeclaration())) { CheckFailed
("llvm.localrecover first " "argument must be function defined in this module"
, Call); return; } } while (false)
4846 "argument must be function defined in this module",do { if (!(Fn && !Fn->isDeclaration())) { CheckFailed
("llvm.localrecover first " "argument must be function defined in this module"
, Call); return; } } while (false)
4847 Call)do { if (!(Fn && !Fn->isDeclaration())) { CheckFailed
("llvm.localrecover first " "argument must be function defined in this module"
, Call); return; } } while (false)
;
4848 auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
4849 auto &Entry = FrameEscapeInfo[Fn];
4850 Entry.second = unsigned(
4851 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
4852 break;
4853 }
4854
4855 case Intrinsic::experimental_gc_statepoint:
4856 if (auto *CI = dyn_cast<CallInst>(&Call))
4857 Assert(!CI->isInlineAsm(),do { if (!(!CI->isInlineAsm())) { CheckFailed("gc.statepoint support for inline assembly unimplemented"
, CI); return; } } while (false)
4858 "gc.statepoint support for inline assembly unimplemented", CI)do { if (!(!CI->isInlineAsm())) { CheckFailed("gc.statepoint support for inline assembly unimplemented"
, CI); return; } } while (false)
;
4859 Assert(Call.getParent()->getParent()->hasGC(),do { if (!(Call.getParent()->getParent()->hasGC())) { CheckFailed
("Enclosing function does not use GC.", Call); return; } } while
(false)
4860 "Enclosing function does not use GC.", Call)do { if (!(Call.getParent()->getParent()->hasGC())) { CheckFailed
("Enclosing function does not use GC.", Call); return; } } while
(false)
;
4861
4862 verifyStatepoint(Call);
4863 break;
4864 case Intrinsic::experimental_gc_result: {
4865 Assert(Call.getParent()->getParent()->hasGC(),do { if (!(Call.getParent()->getParent()->hasGC())) { CheckFailed
("Enclosing function does not use GC.", Call); return; } } while
(false)
4866 "Enclosing function does not use GC.", Call)do { if (!(Call.getParent()->getParent()->hasGC())) { CheckFailed
("Enclosing function does not use GC.", Call); return; } } while
(false)
;
4867 // Are we tied to a statepoint properly?
4868 const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0));
4869 const Function *StatepointFn =
4870 StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
4871 Assert(StatepointFn && StatepointFn->isDeclaration() &&do { if (!(StatepointFn && StatepointFn->isDeclaration
() && StatepointFn->getIntrinsicID() == Intrinsic::
experimental_gc_statepoint)) { CheckFailed("gc.result operand #1 must be from a statepoint"
, Call, Call.getArgOperand(0)); return; } } while (false)
4872 StatepointFn->getIntrinsicID() ==do { if (!(StatepointFn && StatepointFn->isDeclaration
() && StatepointFn->getIntrinsicID() == Intrinsic::
experimental_gc_statepoint)) { CheckFailed("gc.result operand #1 must be from a statepoint"
, Call, Call.getArgOperand(0)); return; } } while (false)
4873 Intrinsic::experimental_gc_statepoint,do { if (!(StatepointFn && StatepointFn->isDeclaration
() && StatepointFn->getIntrinsicID() == Intrinsic::
experimental_gc_statepoint)) { CheckFailed("gc.result operand #1 must be from a statepoint"
, Call, Call.getArgOperand(0)); return; } } while (false)
4874 "gc.result operand #1 must be from a statepoint", Call,do { if (!(StatepointFn && StatepointFn->isDeclaration
() && StatepointFn->getIntrinsicID() == Intrinsic::
experimental_gc_statepoint)) { CheckFailed("gc.result operand #1 must be from a statepoint"
, Call, Call.getArgOperand(0)); return; } } while (false)
4875 Call.getArgOperand(0))do { if (!(StatepointFn && StatepointFn->isDeclaration
() && StatepointFn->getIntrinsicID() == Intrinsic::
experimental_gc_statepoint)) { CheckFailed("gc.result operand #1 must be from a statepoint"
, Call, Call.getArgOperand(0)); return; } } while (false)
;
4876
4877 // Assert that result type matches wrapped callee.
4878 const Value *Target = StatepointCall->getArgOperand(2);
4879 auto *PT = cast<PointerType>(Target->getType());
4880 auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
4881 Assert(Call.getType() == TargetFuncType->getReturnType(),do { if (!(Call.getType() == TargetFuncType->getReturnType
())) { CheckFailed("gc.result result type does not match wrapped callee"
, Call); return; } } while (false)
4882 "gc.result result type does not match wrapped callee", Call)do { if (!(Call.getType() == TargetFuncType->getReturnType
())) { CheckFailed("gc.result result type does not match wrapped callee"
, Call); return; } } while (false)
;
4883 break;
4884 }
4885 case Intrinsic::experimental_gc_relocate: {
4886 Assert(Call.getNumArgOperands() == 3, "wrong number of arguments", Call)do { if (!(Call.getNumArgOperands() == 3)) { CheckFailed("wrong number of arguments"
, Call); return; } } while (false)
;
4887
4888 Assert(isa<PointerType>(Call.getType()->getScalarType()),do { if (!(isa<PointerType>(Call.getType()->getScalarType
()))) { CheckFailed("gc.relocate must return a pointer or a vector of pointers"
, Call); return; } } while (false)
4889 "gc.relocate must return a pointer or a vector of pointers", Call)do { if (!(isa<PointerType>(Call.getType()->getScalarType
()))) { CheckFailed("gc.relocate must return a pointer or a vector of pointers"
, Call); return; } } while (false)
;
4890
4891 // Check that this relocate is correctly tied to the statepoint
4892
4893 // This is case for relocate on the unwinding path of an invoke statepoint
4894 if (LandingPadInst *LandingPad =
4895 dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
4896
4897 const BasicBlock *InvokeBB =
4898 LandingPad->getParent()->getUniquePredecessor();
4899
4900 // Landingpad relocates should have only one predecessor with invoke
4901 // statepoint terminator
4902 Assert(InvokeBB, "safepoints should have unique landingpads",do { if (!(InvokeBB)) { CheckFailed("safepoints should have unique landingpads"
, LandingPad->getParent()); return; } } while (false)
4903 LandingPad->getParent())do { if (!(InvokeBB)) { CheckFailed("safepoints should have unique landingpads"
, LandingPad->getParent()); return; } } while (false)
;
4904 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",do { if (!(InvokeBB->getTerminator())) { CheckFailed("safepoint block should be well formed"
, InvokeBB); return; } } while (false)
4905 InvokeBB)do { if (!(InvokeBB->getTerminator())) { CheckFailed("safepoint block should be well formed"
, InvokeBB); return; } } while (false)
;
4906 Assert(isa<GCStatepointInst>(InvokeBB->getTerminator()),do { if (!(isa<GCStatepointInst>(InvokeBB->getTerminator
()))) { CheckFailed("gc relocate should be linked to a statepoint"
, InvokeBB); return; } } while (false)
4907 "gc relocate should be linked to a statepoint", InvokeBB)do { if (!(isa<GCStatepointInst>(InvokeBB->getTerminator
()))) { CheckFailed("gc relocate should be linked to a statepoint"
, InvokeBB); return; } } while (false)
;
4908 } else {
4909 // In all other cases relocate should be tied to the statepoint directly.
4910 // This covers relocates on a normal return path of invoke statepoint and
4911 // relocates of a call statepoint.
4912 auto Token = Call.getArgOperand(0);
4913 Assert(isa<GCStatepointInst>(Token),do { if (!(isa<GCStatepointInst>(Token))) { CheckFailed
("gc relocate is incorrectly tied to the statepoint", Call, Token
); return; } } while (false)
4914 "gc relocate is incorrectly tied to the statepoint", Call, Token)do { if (!(isa<GCStatepointInst>(Token))) { CheckFailed
("gc relocate is incorrectly tied to the statepoint", Call, Token
); return; } } while (false)
;
4915 }
4916
4917 // Verify rest of the relocate arguments.
4918 const CallBase &StatepointCall =
4919 *cast<GCRelocateInst>(Call).getStatepoint();
4920
4921 // Both the base and derived must be piped through the safepoint.
4922 Value *Base = Call.getArgOperand(1);
4923 Assert(isa<ConstantInt>(Base),do { if (!(isa<ConstantInt>(Base))) { CheckFailed("gc.relocate operand #2 must be integer offset"
, Call); return; } } while (false)
4924 "gc.relocate operand #2 must be integer offset", Call)do { if (!(isa<ConstantInt>(Base))) { CheckFailed("gc.relocate operand #2 must be integer offset"
, Call); return; } } while (false)
;
4925
4926 Value *Derived = Call.getArgOperand(2);
4927 Assert(isa<ConstantInt>(Derived),do { if (!(isa<ConstantInt>(Derived))) { CheckFailed("gc.relocate operand #3 must be integer offset"
, Call); return; } } while (false)
4928 "gc.relocate operand #3 must be integer offset", Call)do { if (!(isa<ConstantInt>(Derived))) { CheckFailed("gc.relocate operand #3 must be integer offset"
, Call); return; } } while (false)
;
4929
4930 const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
4931 const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
4932
4933 // Check the bounds
4934 if (auto Opt = StatepointCall.getOperandBundle(LLVMContext::OB_gc_live)) {
4935 Assert(BaseIndex < Opt->Inputs.size(),do { if (!(BaseIndex < Opt->Inputs.size())) { CheckFailed
("gc.relocate: statepoint base index out of bounds", Call); return
; } } while (false)
4936 "gc.relocate: statepoint base index out of bounds", Call)do { if (!(BaseIndex < Opt->Inputs.size())) { CheckFailed
("gc.relocate: statepoint base index out of bounds", Call); return
; } } while (false)
;
4937 Assert(DerivedIndex < Opt->Inputs.size(),do { if (!(DerivedIndex < Opt->Inputs.size())) { CheckFailed
("gc.relocate: statepoint derived index out of bounds", Call)
; return; } } while (false)
4938 "gc.relocate: statepoint derived index out of bounds", Call)do { if (!(DerivedIndex < Opt->Inputs.size())) { CheckFailed
("gc.relocate: statepoint derived index out of bounds", Call)
; return; } } while (false)
;
4939 }
4940
4941 // Relocated value must be either a pointer type or vector-of-pointer type,
4942 // but gc_relocate does not need to return the same pointer type as the
4943 // relocated pointer. It can be casted to the correct type later if it's
4944 // desired. However, they must have the same address space and 'vectorness'
4945 GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
4946 Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(),do { if (!(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy
())) { CheckFailed("gc.relocate: relocated value must be a gc pointer"
, Call); return; } } while (false)
4947 "gc.relocate: relocated value must be a gc pointer", Call)do { if (!(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy
())) { CheckFailed("gc.relocate: relocated value must be a gc pointer"
, Call); return; } } while (false)
;
4948
4949 auto ResultType = Call.getType();
4950 auto DerivedType = Relocate.getDerivedPtr()->getType();
4951 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),do { if (!(ResultType->isVectorTy() == DerivedType->isVectorTy
())) { CheckFailed("gc.relocate: vector relocates to vector and pointer to pointer"
, Call); return; } } while (false)
4952 "gc.relocate: vector relocates to vector and pointer to pointer",do { if (!(ResultType->isVectorTy() == DerivedType->isVectorTy
())) { CheckFailed("gc.relocate: vector relocates to vector and pointer to pointer"
, Call); return; } } while (false)
4953 Call)do { if (!(ResultType->isVectorTy() == DerivedType->isVectorTy
())) { CheckFailed("gc.relocate: vector relocates to vector and pointer to pointer"
, Call); return; } } while (false)
;
4954 Assert(do { if (!(ResultType->getPointerAddressSpace() == DerivedType
->getPointerAddressSpace())) { CheckFailed("gc.relocate: relocating a pointer shouldn't change its address space"
, Call); return; } } while (false)
4955 ResultType->getPointerAddressSpace() ==do { if (!(ResultType->getPointerAddressSpace() == DerivedType
->getPointerAddressSpace())) { CheckFailed("gc.relocate: relocating a pointer shouldn't change its address space"
, Call); return; } } while (false)
4956 DerivedType->getPointerAddressSpace(),do { if (!(ResultType->getPointerAddressSpace() == DerivedType
->getPointerAddressSpace())) { CheckFailed("gc.relocate: relocating a pointer shouldn't change its address space"
, Call); return; } } while (false)
4957 "gc.relocate: relocating a pointer shouldn't change its address space",do { if (!(ResultType->getPointerAddressSpace() == DerivedType
->getPointerAddressSpace())) { CheckFailed("gc.relocate: relocating a pointer shouldn't change its address space"
, Call); return; } } while (false)
4958 Call)do { if (!(ResultType->getPointerAddressSpace() == DerivedType
->getPointerAddressSpace())) { CheckFailed("gc.relocate: relocating a pointer shouldn't change its address space"
, Call); return; } } while (false)
;
4959 break;
4960 }
4961 case Intrinsic::eh_exceptioncode:
4962 case Intrinsic::eh_exceptionpointer: {
4963 Assert(isa<CatchPadInst>(Call.getArgOperand(0)),do { if (!(isa<CatchPadInst>(Call.getArgOperand(0)))) {
CheckFailed("eh.exceptionpointer argument must be a catchpad"
, Call); return; } } while (false)
4964 "eh.exceptionpointer argument must be a catchpad", Call)do { if (!(isa<CatchPadInst>(Call.getArgOperand(0)))) {
CheckFailed("eh.exceptionpointer argument must be a catchpad"
, Call); return; } } while (false)
;
4965 break;
4966 }
4967 case Intrinsic::get_active_lane_mask: {
4968 Assert(Call.getType()->isVectorTy(), "get_active_lane_mask: must return a "do { if (!(Call.getType()->isVectorTy())) { CheckFailed("get_active_lane_mask: must return a "
"vector", Call); return; } } while (false)
4969 "vector", Call)do { if (!(Call.getType()->isVectorTy())) { CheckFailed("get_active_lane_mask: must return a "
"vector", Call); return; } } while (false)
;
4970 auto *ElemTy = Call.getType()->getScalarType();
4971 Assert(ElemTy->isIntegerTy(1), "get_active_lane_mask: element type is not "do { if (!(ElemTy->isIntegerTy(1))) { CheckFailed("get_active_lane_mask: element type is not "
"i1", Call); return; } } while (false)
4972 "i1", Call)do { if (!(ElemTy->isIntegerTy(1))) { CheckFailed("get_active_lane_mask: element type is not "
"i1", Call); return; } } while (false)
;
4973 break;
4974 }
4975 case Intrinsic::masked_load: {
4976 Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector",do { if (!(Call.getType()->isVectorTy())) { CheckFailed("masked_load: must return a vector"
, Call); return; } } while (false)
4977 Call)do { if (!(Call.getType()->isVectorTy())) { CheckFailed("masked_load: must return a vector"
, Call); return; } } while (false)
;
4978
4979 Value *Ptr = Call.getArgOperand(0);
4980 ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
4981 Value *Mask = Call.getArgOperand(2);
4982 Value *PassThru = Call.getArgOperand(3);
4983 Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",do { if (!(Mask->getType()->isVectorTy())) { CheckFailed
("masked_load: mask must be vector", Call); return; } } while
(false)
4984 Call)do { if (!(Mask->getType()->isVectorTy())) { CheckFailed
("masked_load: mask must be vector", Call); return; } } while
(false)
;
4985 Assert(Alignment->getValue().isPowerOf2(),do { if (!(Alignment->getValue().isPowerOf2())) { CheckFailed
("masked_load: alignment must be a power of 2", Call); return
; } } while (false)
4986 "masked_load: alignment must be a power of 2", Call)do { if (!(Alignment->getValue().isPowerOf2())) { CheckFailed
("masked_load: alignment must be a power of 2", Call); return
; } } while (false)
;
4987
4988 PointerType *PtrTy = cast<PointerType>(Ptr->getType());
4989 Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType()),do { if (!(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType
()))) { CheckFailed("masked_load: return must match pointer type"
, Call); return; } } while (false)
4990 "masked_load: return must match pointer type", Call)do { if (!(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType
()))) { CheckFailed("masked_load: return must match pointer type"
, Call); return; } } while (false)
;
4991 Assert(PassThru->getType() == Call.getType(),do { if (!(PassThru->getType() == Call.getType())) { CheckFailed
("masked_load: pass through and return type must match", Call
); return; } } while (false)
4992 "masked_load: pass through and return type must match", Call)do { if (!(PassThru->getType() == Call.getType())) { CheckFailed
("masked_load: pass through and return type must match", Call
); return; } } while (false)
;
4993 Assert(cast<VectorType>(Mask->getType())->getElementCount() ==do { if (!(cast<VectorType>(Mask->getType())->getElementCount
() == cast<VectorType>(Call.getType())->getElementCount
())) { CheckFailed("masked_load: vector mask must be same length as return"
, Call); return; } } while (false)
4994 cast<VectorType>(Call.getType())->getElementCount(),do { if (!(cast<VectorType>(Mask->getType())->getElementCount
() == cast<VectorType>(Call.getType())->getElementCount
())) { CheckFailed("masked_load: vector mask must be same length as return"
, Call); return; } } while (false)
4995 "masked_load: vector mask must be same length as return", Call)do { if (!(cast<VectorType>(Mask->getType())->getElementCount
() == cast<VectorType>(Call.getType())->getElementCount
())) { CheckFailed("masked_load: vector mask must be same length as return"
, Call); return; } } while (false)
;
4996 break;
4997 }
4998 case Intrinsic::masked_store: {
4999 Value *Val = Call.getArgOperand(0);
5000 Value *Ptr = Call.getArgOperand(1);
5001 ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
5002 Value *Mask = Call.getArgOperand(3);
5003 Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",do { if (!(Mask->getType()->isVectorTy())) { CheckFailed
("masked_store: mask must be vector", Call); return; } } while
(false)
5004 Call)do { if (!(Mask->getType()->isVectorTy())) { CheckFailed
("masked_store: mask must be vector", Call); return; } } while
(false)
;
5005 Assert(Alignment->getValue().isPowerOf2(),do { if (!(Alignment->getValue().isPowerOf2())) { CheckFailed
("masked_store: alignment must be a power of 2", Call); return
; } } while (false)
5006 "masked_store: alignment must be a power of 2", Call)do { if (!(Alignment->getValue().isPowerOf2())) { CheckFailed
("masked_store: alignment must be a power of 2", Call); return
; } } while (false)
;
5007
5008 PointerType *PtrTy = cast<PointerType>(Ptr->getType());
5009 Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType()),do { if (!(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType
()))) { CheckFailed("masked_store: storee must match pointer type"
, Call); return; } } while (false)
5010 "masked_store: storee must match pointer type", Call)do { if (!(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType
()))) { CheckFailed("masked_store: storee must match pointer type"
, Call); return; } } while (false)
;
5011 Assert(cast<VectorType>(Mask->getType())->getElementCount() ==do { if (!(cast<VectorType>(Mask->getType())->getElementCount
() == cast<VectorType>(Val->getType())->getElementCount
())) { CheckFailed("masked_store: vector mask must be same length as value"
, Call); return; } } while (false)
5012 cast<VectorType>(Val->getType())->getElementCount(),do { if (!(cast<VectorType>(Mask->getType())->getElementCount
() == cast<VectorType>(Val->getType())->getElementCount
())) { CheckFailed("masked_store: vector mask must be same length as value"
, Call); return; } } while (false)
5013 "masked_store: vector mask must be same length as value", Call)do { if (!(cast<VectorType>(Mask->getType())->getElementCount
() == cast<VectorType>(Val->getType())->getElementCount
())) { CheckFailed("masked_store: vector mask must be same length as value"
, Call); return; } } while (false)
;
5014 break;
5015 }
5016
5017 case Intrinsic::masked_gather: {
5018 const APInt &Alignment =
5019 cast<ConstantInt>(Call.getArgOperand(1))->getValue();
5020 Assert(Alignment.isNullValue() || Alignment.isPowerOf2(),do { if (!(Alignment.isNullValue() || Alignment.isPowerOf2())
) { CheckFailed("masked_gather: alignment must be 0 or a power of 2"
, Call); return; } } while (false)
5021 "masked_gather: alignment must be 0 or a power of 2", Call)do { if (!(Alignment.isNullValue() || Alignment.isPowerOf2())
) { CheckFailed("masked_gather: alignment must be 0 or a power of 2"
, Call); return; } } while (false)
;
5022 break;
5023 }
5024 case Intrinsic::masked_scatter: {
5025 const APInt &Alignment =
5026 cast<ConstantInt>(Call.getArgOperand(2))->getValue();
5027 Assert(Alignment.isNullValue() || Alignment.isPowerOf2(),do { if (!(Alignment.isNullValue() || Alignment.isPowerOf2())
) { CheckFailed("masked_scatter: alignment must be 0 or a power of 2"
, Call); return; } } while (false)
5028 "masked_scatter: alignment must be 0 or a power of 2", Call)do { if (!(Alignment.isNullValue() || Alignment.isPowerOf2())
) { CheckFailed("masked_scatter: alignment must be 0 or a power of 2"
, Call); return; } } while (false)
;
5029 break;
5030 }
5031
5032 case Intrinsic::experimental_guard: {
5033 Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call)do { if (!(isa<CallInst>(Call))) { CheckFailed("experimental_guard cannot be invoked"
, Call); return; } } while (false)
;
5034 Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,do { if (!(Call.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1)) { CheckFailed("experimental_guard must have exactly one "
"\"deopt\" operand bundle"); return; } } while (false)
5035 "experimental_guard must have exactly one "do { if (!(Call.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1)) { CheckFailed("experimental_guard must have exactly one "
"\"deopt\" operand bundle"); return; } } while (false)
5036 "\"deopt\" operand bundle")do { if (!(Call.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1)) { CheckFailed("experimental_guard must have exactly one "
"\"deopt\" operand bundle"); return; } } while (false)
;
5037 break;
5038 }
5039
5040 case Intrinsic::experimental_deoptimize: {
5041 Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",do { if (!(isa<CallInst>(Call))) { CheckFailed("experimental_deoptimize cannot be invoked"
, Call); return; } } while (false)
5042 Call)do { if (!(isa<CallInst>(Call))) { CheckFailed("experimental_deoptimize cannot be invoked"
, Call); return; } } while (false)
;
5043 Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,do { if (!(Call.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1)) { CheckFailed("experimental_deoptimize must have exactly one "
"\"deopt\" operand bundle"); return; } } while (false)
5044 "experimental_deoptimize must have exactly one "do { if (!(Call.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1)) { CheckFailed("experimental_deoptimize must have exactly one "
"\"deopt\" operand bundle"); return; } } while (false)
5045 "\"deopt\" operand bundle")do { if (!(Call.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1)) { CheckFailed("experimental_deoptimize must have exactly one "
"\"deopt\" operand bundle"); return; } } while (false)
;
5046 Assert(Call.getType() == Call.getFunction()->getReturnType(),do { if (!(Call.getType() == Call.getFunction()->getReturnType
())) { CheckFailed("experimental_deoptimize return type must match caller return type"
); return; } } while (false)
5047 "experimental_deoptimize return type must match caller return type")do { if (!(Call.getType() == Call.getFunction()->getReturnType
())) { CheckFailed("experimental_deoptimize return type must match caller return type"
); return; } } while (false)
;
5048
5049 if (isa<CallInst>(Call)) {
5050 auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
5051 Assert(RI,do { if (!(RI)) { CheckFailed("calls to experimental_deoptimize must be followed by a return"
); return; } } while (false)
5052 "calls to experimental_deoptimize must be followed by a return")do { if (!(RI)) { CheckFailed("calls to experimental_deoptimize must be followed by a return"
); return; } } while (false)
;
5053
5054 if (!Call.getType()->isVoidTy() && RI)
5055 Assert(RI->getReturnValue() == &Call,do { if (!(RI->getReturnValue() == &Call)) { CheckFailed
("calls to experimental_deoptimize must be followed by a return "
"of the value computed by experimental_deoptimize"); return;
} } while (false)
5056 "calls to experimental_deoptimize must be followed by a return "do { if (!(RI->getReturnValue() == &Call)) { CheckFailed
("calls to experimental_deoptimize must be followed by a return "
"of the value computed by experimental_deoptimize"); return;
} } while (false)
5057 "of the value computed by experimental_deoptimize")do { if (!(RI->getReturnValue() == &Call)) { CheckFailed
("calls to experimental_deoptimize must be followed by a return "
"of the value computed by experimental_deoptimize"); return;
} } while (false)
;
5058 }
5059
5060 break;
5061 }
5062 case Intrinsic::vector_reduce_and:
5063 case Intrinsic::vector_reduce_or:
5064 case Intrinsic::vector_reduce_xor:
5065 case Intrinsic::vector_reduce_add:
5066 case Intrinsic::vector_reduce_mul:
5067 case Intrinsic::vector_reduce_smax:
5068 case Intrinsic::vector_reduce_smin:
5069 case Intrinsic::vector_reduce_umax:
5070 case Intrinsic::vector_reduce_umin: {
5071 Type *ArgTy = Call.getArgOperand(0)->getType();
5072 Assert(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),do { if (!(ArgTy->isIntOrIntVectorTy() && ArgTy->
isVectorTy())) { CheckFailed("Intrinsic has incorrect argument type!"
); return; } } while (false)
5073 "Intrinsic has incorrect argument type!")do { if (!(ArgTy->isIntOrIntVectorTy() && ArgTy->
isVectorTy())) { CheckFailed("Intrinsic has incorrect argument type!"
); return; } } while (false)
;
5074 break;
5075 }
5076 case Intrinsic::vector_reduce_fmax:
5077 case Intrinsic::vector_reduce_fmin: {
5078 Type *ArgTy = Call.getArgOperand(0)->getType();
5079 Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),do { if (!(ArgTy->isFPOrFPVectorTy() && ArgTy->
isVectorTy())) { CheckFailed("Intrinsic has incorrect argument type!"
); return; } } while (false)
5080 "Intrinsic has incorrect argument type!")do { if (!(ArgTy->isFPOrFPVectorTy() && ArgTy->
isVectorTy())) { CheckFailed("Intrinsic has incorrect argument type!"
); return; } } while (false)
;
5081 break;
5082 }
5083 case Intrinsic::vector_reduce_fadd:
5084 case Intrinsic::vector_reduce_fmul: {
5085 // Unlike the other reductions, the first argument is a start value. The
5086 // second argument is the vector to be reduced.
5087 Type *ArgTy = Call.getArgOperand(1)->getType();
5088 Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),do { if (!(ArgTy->isFPOrFPVectorTy() && ArgTy->
isVectorTy())) { CheckFailed("Intrinsic has incorrect argument type!"
); return; } } while (false)
5089 "Intrinsic has incorrect argument type!")do { if (!(ArgTy->isFPOrFPVectorTy() && ArgTy->
isVectorTy())) { CheckFailed("Intrinsic has incorrect argument type!"
); return; } } while (false)
;
5090 break;
5091 }
5092 case Intrinsic::smul_fix:
5093 case Intrinsic::smul_fix_sat:
5094 case Intrinsic::umul_fix:
5095 case Intrinsic::umul_fix_sat:
5096 case Intrinsic::sdiv_fix:
5097 case Intrinsic::sdiv_fix_sat:
5098 case Intrinsic::udiv_fix:
5099 case Intrinsic::udiv_fix_sat: {
5100 Value *Op1 = Call.getArgOperand(0);
5101 Value *Op2 = Call.getArgOperand(1);
5102 Assert(Op1->getType()->isIntOrIntVectorTy(),do { if (!(Op1->getType()->isIntOrIntVectorTy())) { CheckFailed
("first operand of [us][mul|div]_fix[_sat] must be an int type or "
"vector of ints"); return; } } while (false)
5103 "first operand of [us][mul|div]_fix[_sat] must be an int type or "do { if (!(Op1->getType()->isIntOrIntVectorTy())) { CheckFailed
("first operand of [us][mul|div]_fix[_sat] must be an int type or "
"vector of ints"); return; } } while (false)
5104 "vector of ints")do { if (!(Op1->getType()->isIntOrIntVectorTy())) { CheckFailed
("first operand of [us][mul|div]_fix[_sat] must be an int type or "
"vector of ints"); return; } } while (false)
;
5105 Assert(Op2->getType()->isIntOrIntVectorTy(),do { if (!(Op2->getType()->isIntOrIntVectorTy())) { CheckFailed
("second operand of [us][mul|div]_fix[_sat] must be an int type or "
"vector of ints"); return; } } while (false)
5106 "second operand of [us][mul|div]_fix[_sat] must be an int type or "do { if (!(Op2->getType()->isIntOrIntVectorTy())) { CheckFailed
("second operand of [us][mul|div]_fix[_sat] must be an int type or "
"vector of ints"); return; } } while (false)
5107 "vector of ints")do { if (!(Op2->getType()->isIntOrIntVectorTy())) { CheckFailed
("second operand of [us][mul|div]_fix[_sat] must be an int type or "
"vector of ints"); return; } } while (false)
;
5108
5109 auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
5110 Assert(Op3->getType()->getBitWidth() <= 32,do { if (!(Op3->getType()->getBitWidth() <= 32)) { CheckFailed
("third argument of [us][mul|div]_fix[_sat] must fit within 32 bits"
); return; } } while (false)
5111 "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits")do { if (!(Op3->getType()->getBitWidth() <= 32)) { CheckFailed
("third argument of [us][mul|div]_fix[_sat] must fit within 32 bits"
); return; } } while (false)
;
5112
5113 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
5114 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
5115 Assert(do { if (!(Op3->getZExtValue() < Op1->getType()->
getScalarSizeInBits())) { CheckFailed("the scale of s[mul|div]_fix[_sat] must be less than the width of "
"the operands"); return; } } while (false)
5116 Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),do { if (!(Op3->getZExtValue() < Op1->getType()->
getScalarSizeInBits())) { CheckFailed("the scale of s[mul|div]_fix[_sat] must be less than the width of "
"the operands"); return; } } while (false)
5117 "the scale of s[mul|div]_fix[_sat] must be less than the width of "do { if (!(Op3->getZExtValue() < Op1->getType()->
getScalarSizeInBits())) { CheckFailed("the scale of s[mul|div]_fix[_sat] must be less than the width of "
"the operands"); return; } } while (false)
5118 "the operands")do { if (!(Op3->getZExtValue() < Op1->getType()->
getScalarSizeInBits())) { CheckFailed("the scale of s[mul|div]_fix[_sat] must be less than the width of "
"the operands"); return; } } while (false)
;
5119 } else {
5120 Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),do { if (!(Op3->getZExtValue() <= Op1->getType()->
getScalarSizeInBits())) { CheckFailed("the scale of u[mul|div]_fix[_sat] must be less than or equal "
"to the width of the operands"); return; } } while (false)
5121 "the scale of u[mul|div]_fix[_sat] must be less than or equal "do { if (!(Op3->getZExtValue() <= Op1->getType()->
getScalarSizeInBits())) { CheckFailed("the scale of u[mul|div]_fix[_sat] must be less than or equal "
"to the width of the operands"); return; } } while (false)
5122 "to the width of the operands")do { if (!(Op3->getZExtValue() <= Op1->getType()->
getScalarSizeInBits())) { CheckFailed("the scale of u[mul|div]_fix[_sat] must be less than or equal "
"to the width of the operands"); return; } } while (false)
;
5123 }
5124 break;
5125 }
5126 case Intrinsic::lround:
5127 case Intrinsic::llround:
5128 case Intrinsic::lrint:
5129 case Intrinsic::llrint: {
5130 Type *ValTy = Call.getArgOperand(0)->getType();
5131 Type *ResultTy = Call.getType();
5132 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),do { if (!(!ValTy->isVectorTy() && !ResultTy->isVectorTy
())) { CheckFailed("Intrinsic does not support vectors", &
Call); return; } } while (false)
5133 "Intrinsic does not support vectors", &Call)do { if (!(!ValTy->isVectorTy() && !ResultTy->isVectorTy
())) { CheckFailed("Intrinsic does not support vectors", &
Call); return; } } while (false)
;
5134 break;
5135 }
5136 case Intrinsic::bswap: {
5137 Type *Ty = Call.getType();
5138 unsigned Size = Ty->getScalarSizeInBits();
5139 Assert(Size % 16 == 0, "bswap must be an even number of bytes", &Call)do { if (!(Size % 16 == 0)) { CheckFailed("bswap must be an even number of bytes"
, &Call); return; } } while (false)
;
5140 break;
5141 }
5142 case Intrinsic::invariant_start: {
5143 ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
5144 Assert(InvariantSize &&do { if (!(InvariantSize && (!InvariantSize->isNegative
() || InvariantSize->isMinusOne()))) { CheckFailed("invariant_start parameter must be -1, 0 or a positive number"
, &Call); return; } } while (false)
5145 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),do { if (!(InvariantSize && (!InvariantSize->isNegative
() || InvariantSize->isMinusOne()))) { CheckFailed("invariant_start parameter must be -1, 0 or a positive number"
, &Call); return; } } while (false)
5146 "invariant_start parameter must be -1, 0 or a positive number",do { if (!(InvariantSize && (!InvariantSize->isNegative
() || InvariantSize->isMinusOne()))) { CheckFailed("invariant_start parameter must be -1, 0 or a positive number"
, &Call); return; } } while (false)
5147 &Call)do { if (!(InvariantSize && (!InvariantSize->isNegative
() || InvariantSize->isMinusOne()))) { CheckFailed("invariant_start parameter must be -1, 0 or a positive number"
, &Call); return; } } while (false)
;
5148 break;
5149 }
5150 case Intrinsic::matrix_multiply:
5151 case Intrinsic::matrix_transpose:
5152 case Intrinsic::matrix_column_major_load:
5153 case Intrinsic::matrix_column_major_store: {
5154 Function *IF = Call.getCalledFunction();
5155 ConstantInt *Stride = nullptr;
5156 ConstantInt *NumRows;
5157 ConstantInt *NumColumns;
5158 VectorType *ResultTy;
5159 Type *Op0ElemTy = nullptr;
5160 Type *Op1ElemTy = nullptr;
5161 switch (ID) {
5162 case Intrinsic::matrix_multiply:
5163 NumRows = cast<ConstantInt>(Call.getArgOperand(2));
5164 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5165 ResultTy = cast<VectorType>(Call.getType());
5166 Op0ElemTy =
5167 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5168 Op1ElemTy =
5169 cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
5170 break;
5171 case Intrinsic::matrix_transpose:
5172 NumRows = cast<ConstantInt>(Call.getArgOperand(1));
5173 NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
5174 ResultTy = cast<VectorType>(Call.getType());
5175 Op0ElemTy =
5176 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5177 break;
5178 case Intrinsic::matrix_column_major_load:
5179 Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
5180 NumRows = cast<ConstantInt>(Call.getArgOperand(3));
5181 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5182 ResultTy = cast<VectorType>(Call.getType());
5183 Op0ElemTy =
5184 cast<PointerType>(Call.getArgOperand(0)->getType())->getElementType();
5185 break;
5186 case Intrinsic::matrix_column_major_store:
5187 Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
5188 NumRows = cast<ConstantInt>(Call.getArgOperand(4));
5189 NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
5190 ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
5191 Op0ElemTy =
5192 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5193 Op1ElemTy =
5194 cast<PointerType>(Call.getArgOperand(1)->getType())->getElementType();
5195 break;
5196 default:
5197 llvm_unreachable("unexpected intrinsic")__builtin_unreachable();
5198 }
5199
5200 Assert(ResultTy->getElementType()->isIntegerTy() ||do { if (!(ResultTy->getElementType()->isIntegerTy() ||
ResultTy->getElementType()->isFloatingPointTy())) { CheckFailed
("Result type must be an integer or floating-point type!", IF
); return; } } while (false)
5201 ResultTy->getElementType()->isFloatingPointTy(),do { if (!(ResultTy->getElementType()->isIntegerTy() ||
ResultTy->getElementType()->isFloatingPointTy())) { CheckFailed
("Result type must be an integer or floating-point type!", IF
); return; } } while (false)
5202 "Result type must be an integer or floating-point type!", IF)do { if (!(ResultTy->getElementType()->isIntegerTy() ||
ResultTy->getElementType()->isFloatingPointTy())) { CheckFailed
("Result type must be an integer or floating-point type!", IF
); return; } } while (false)
;
5203
5204 Assert(ResultTy->getElementType() == Op0ElemTy,do { if (!(ResultTy->getElementType() == Op0ElemTy)) { CheckFailed
("Vector element type mismatch of the result and first operand "
"vector!", IF); return; } } while (false)
5205 "Vector element type mismatch of the result and first operand "do { if (!(ResultTy->getElementType() == Op0ElemTy)) { CheckFailed
("Vector element type mismatch of the result and first operand "
"vector!", IF); return; } } while (false)
5206 "vector!", IF)do { if (!(ResultTy->getElementType() == Op0ElemTy)) { CheckFailed
("Vector element type mismatch of the result and first operand "
"vector!", IF); return; } } while (false)
;
5207
5208 if (Op1ElemTy)
5209 Assert(ResultTy->getElementType() == Op1ElemTy,do { if (!(ResultTy->getElementType() == Op1ElemTy)) { CheckFailed
("Vector element type mismatch of the result and second operand "
"vector!", IF); return; } } while (false)
5210 "Vector element type mismatch of the result and second operand "do { if (!(ResultTy->getElementType() == Op1ElemTy)) { CheckFailed
("Vector element type mismatch of the result and second operand "
"vector!", IF); return; } } while (false)
5211 "vector!", IF)do { if (!(ResultTy->getElementType() == Op1ElemTy)) { CheckFailed
("Vector element type mismatch of the result and second operand "
"vector!", IF); return; } } while (false)
;
5212
5213 Assert(cast<FixedVectorType>(ResultTy)->getNumElements() ==do { if (!(cast<FixedVectorType>(ResultTy)->getNumElements
() == NumRows->getZExtValue() * NumColumns->getZExtValue
())) { CheckFailed("Result of a matrix operation does not fit in the returned vector!"
); return; } } while (false)
5214 NumRows->getZExtValue() * NumColumns->getZExtValue(),do { if (!(cast<FixedVectorType>(ResultTy)->getNumElements
() == NumRows->getZExtValue() * NumColumns->getZExtValue
())) { CheckFailed("Result of a matrix operation does not fit in the returned vector!"
); return; } } while (false)
5215 "Result of a matrix operation does not fit in the returned vector!")do { if (!(cast<FixedVectorType>(ResultTy)->getNumElements
() == NumRows->getZExtValue() * NumColumns->getZExtValue
())) { CheckFailed("Result of a matrix operation does not fit in the returned vector!"
); return; } } while (false)
;
5216
5217 if (Stride)
5218 Assert(Stride->getZExtValue() >= NumRows->getZExtValue(),do { if (!(Stride->getZExtValue() >= NumRows->getZExtValue
())) { CheckFailed("Stride must be greater or equal than the number of rows!"
, IF); return; } } while (false)
5219 "Stride must be greater or equal than the number of rows!", IF)do { if (!(Stride->getZExtValue() >= NumRows->getZExtValue
())) { CheckFailed("Stride must be greater or equal than the number of rows!"
, IF); return; } } while (false)
;
5220
5221 break;
5222 }
5223 case Intrinsic::experimental_stepvector: {
5224 VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
5225 Assert(VecTy && VecTy->getScalarType()->isIntegerTy() &&do { if (!(VecTy && VecTy->getScalarType()->isIntegerTy
() && VecTy->getScalarSizeInBits() >= 8)) { CheckFailed
("experimental_stepvector only supported for vectors of integers "
"with a bitwidth of at least 8.", &Call); return; } } while
(false)
5226 VecTy->getScalarSizeInBits() >= 8,do { if (!(VecTy && VecTy->getScalarType()->isIntegerTy
() && VecTy->getScalarSizeInBits() >= 8)) { CheckFailed
("experimental_stepvector only supported for vectors of integers "
"with a bitwidth of at least 8.", &Call); return; } } while
(false)
5227 "experimental_stepvector only supported for vectors of integers "do { if (!(VecTy && VecTy->getScalarType()->isIntegerTy
() && VecTy->getScalarSizeInBits() >= 8)) { CheckFailed
("experimental_stepvector only supported for vectors of integers "
"with a bitwidth of at least 8.", &Call); return; } } while
(false)
5228 "with a bitwidth of at least 8.",do { if (!(VecTy && VecTy->getScalarType()->isIntegerTy
() && VecTy->getScalarSizeInBits() >= 8)) { CheckFailed
("experimental_stepvector only supported for vectors of integers "
"with a bitwidth of at least 8.", &Call); return; } } while
(false)
5229 &Call)do { if (!(VecTy && VecTy->getScalarType()->isIntegerTy
() && VecTy->getScalarSizeInBits() >= 8)) { CheckFailed
("experimental_stepvector only supported for vectors of integers "
"with a bitwidth of at least 8.", &Call); return; } } while
(false)
;
5230 break;
5231 }
5232 case Intrinsic::experimental_vector_insert: {
5233 Value *Vec = Call.getArgOperand(0);
5234 Value *SubVec = Call.getArgOperand(1);
5235 Value *Idx = Call.getArgOperand(2);
5236 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5237
5238 VectorType *VecTy = cast<VectorType>(Vec->getType());
5239 VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
5240
5241 ElementCount VecEC = VecTy->getElementCount();
5242 ElementCount SubVecEC = SubVecTy->getElementCount();
5243 Assert(VecTy->getElementType() == SubVecTy->getElementType(),do { if (!(VecTy->getElementType() == SubVecTy->getElementType
())) { CheckFailed("experimental_vector_insert parameters must have the same element "
"type.", &Call); return; } } while (false)
5244 "experimental_vector_insert parameters must have the same element "do { if (!(VecTy->getElementType() == SubVecTy->getElementType
())) { CheckFailed("experimental_vector_insert parameters must have the same element "
"type.", &Call); return; } } while (false)
5245 "type.",do { if (!(VecTy->getElementType() == SubVecTy->getElementType
())) { CheckFailed("experimental_vector_insert parameters must have the same element "
"type.", &Call); return; } } while (false)
5246 &Call)do { if (!(VecTy->getElementType() == SubVecTy->getElementType
())) { CheckFailed("experimental_vector_insert parameters must have the same element "
"type.", &Call); return; } } while (false)
;
5247 Assert(IdxN % SubVecEC.getKnownMinValue() == 0,do { if (!(IdxN % SubVecEC.getKnownMinValue() == 0)) { CheckFailed
("experimental_vector_insert index must be a constant multiple of "
"the subvector's known minimum vector length."); return; } }
while (false)
5248 "experimental_vector_insert index must be a constant multiple of "do { if (!(IdxN % SubVecEC.getKnownMinValue() == 0)) { CheckFailed
("experimental_vector_insert index must be a constant multiple of "
"the subvector's known minimum vector length."); return; } }
while (false)
5249 "the subvector's known minimum vector length.")do { if (!(IdxN % SubVecEC.getKnownMinValue() == 0)) { CheckFailed
("experimental_vector_insert index must be a constant multiple of "
"the subvector's known minimum vector length."); return; } }
while (false)
;
5250
5251 // If this insertion is not the 'mixed' case where a fixed vector is
5252 // inserted into a scalable vector, ensure that the insertion of the
5253 // subvector does not overrun the parent vector.
5254 if (VecEC.isScalable() == SubVecEC.isScalable()) {
5255 Assert(do { if (!(IdxN < VecEC.getKnownMinValue() && IdxN
+ SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue()
)) { CheckFailed("subvector operand of experimental_vector_insert would overrun the "
"vector being inserted into."); return; } } while (false)
5256 IdxN < VecEC.getKnownMinValue() &&do { if (!(IdxN < VecEC.getKnownMinValue() && IdxN
+ SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue()
)) { CheckFailed("subvector operand of experimental_vector_insert would overrun the "
"vector being inserted into."); return; } } while (false)
5257 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),do { if (!(IdxN < VecEC.getKnownMinValue() && IdxN
+ SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue()
)) { CheckFailed("subvector operand of experimental_vector_insert would overrun the "
"vector being inserted into."); return; } } while (false)
5258 "subvector operand of experimental_vector_insert would overrun the "do { if (!(IdxN < VecEC.getKnownMinValue() && IdxN
+ SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue()
)) { CheckFailed("subvector operand of experimental_vector_insert would overrun the "
"vector being inserted into."); return; } } while (false)
5259 "vector being inserted into.")do { if (!(IdxN < VecEC.getKnownMinValue() && IdxN
+ SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue()
)) { CheckFailed("subvector operand of experimental_vector_insert would overrun the "
"vector being inserted into."); return; } } while (false)
;
5260 }
5261 break;
5262 }
5263 case Intrinsic::experimental_vector_extract: {
5264 Value *Vec = Call.getArgOperand(0);
5265 Value *Idx = Call.getArgOperand(1);
5266 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5267
5268 VectorType *ResultTy = cast<VectorType>(Call.getType());
5269 VectorType *VecTy = cast<VectorType>(Vec->getType());
5270
5271 ElementCount VecEC = VecTy->getElementCount();
5272 ElementCount ResultEC = ResultTy->getElementCount();
5273
5274 Assert(ResultTy->getElementType() == VecTy->getElementType(),do { if (!(ResultTy->getElementType() == VecTy->getElementType
())) { CheckFailed("experimental_vector_extract result must have the same element "
"type as the input vector.", &Call); return; } } while (
false)
5275 "experimental_vector_extract result must have the same element "do { if (!(ResultTy->getElementType() == VecTy->getElementType
())) { CheckFailed("experimental_vector_extract result must have the same element "
"type as the input vector.", &Call); return; } } while (
false)
5276 "type as the input vector.",do { if (!(ResultTy->getElementType() == VecTy->getElementType
())) { CheckFailed("experimental_vector_extract result must have the same element "
"type as the input vector.", &Call); return; } } while (
false)
5277 &Call)do { if (!(ResultTy->getElementType() == VecTy->getElementType
())) { CheckFailed("experimental_vector_extract result must have the same element "
"type as the input vector.", &Call); return; } } while (
false)
;
5278 Assert(IdxN % ResultEC.getKnownMinValue() == 0,do { if (!(IdxN % ResultEC.getKnownMinValue() == 0)) { CheckFailed
("experimental_vector_extract index must be a constant multiple of "
"the result type's known minimum vector length."); return; }
} while (false)
5279 "experimental_vector_extract index must be a constant multiple of "do { if (!(IdxN % ResultEC.getKnownMinValue() == 0)) { CheckFailed
("experimental_vector_extract index must be a constant multiple of "
"the result type's known minimum vector length."); return; }
} while (false)
5280 "the result type's known minimum vector length.")do { if (!(IdxN % ResultEC.getKnownMinValue() == 0)) { CheckFailed
("experimental_vector_extract index must be a constant multiple of "
"the result type's known minimum vector length."); return; }
} while (false)
;
5281
5282 // If this extraction is not the 'mixed' case where a fixed vector is is
5283 // extracted from a scalable vector, ensure that the extraction does not
5284 // overrun the parent vector.
5285 if (VecEC.isScalable() == ResultEC.isScalable()) {
5286 Assert(IdxN < VecEC.getKnownMinValue() &&do { if (!(IdxN < VecEC.getKnownMinValue() && IdxN
+ ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue()
)) { CheckFailed("experimental_vector_extract would overrun."
); return; } } while (false)
5287 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),do { if (!(IdxN < VecEC.getKnownMinValue() && IdxN
+ ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue()
)) { CheckFailed("experimental_vector_extract would overrun."
); return; } } while (false)
5288 "experimental_vector_extract would overrun.")do { if (!(IdxN < VecEC.getKnownMinValue() && IdxN
+ ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue()
)) { CheckFailed("experimental_vector_extract would overrun."
); return; } } while (false)
;
5289 }
5290 break;
5291 }
5292 case Intrinsic::experimental_noalias_scope_decl: {
5293 NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
5294 break;
5295 }
5296 case Intrinsic::preserve_array_access_index:
5297 case Intrinsic::preserve_struct_access_index: {
5298 Type *ElemTy = Call.getAttributes().getParamElementType(0);
5299 Assert(ElemTy,do { if (!(ElemTy)) { CheckFailed("Intrinsic requires elementtype attribute on first argument."
, &Call); return; } } while (false)
5300 "Intrinsic requires elementtype attribute on first argument.",do { if (!(ElemTy)) { CheckFailed("Intrinsic requires elementtype attribute on first argument."
, &Call); return; } } while (false)
5301 &Call)do { if (!(ElemTy)) { CheckFailed("Intrinsic requires elementtype attribute on first argument."
, &Call); return; } } while (false)
;
5302 break;
5303 }
5304 };
5305}
5306
5307/// Carefully grab the subprogram from a local scope.
5308///
5309/// This carefully grabs the subprogram from a local scope, avoiding the
5310/// built-in assertions that would typically fire.
5311static DISubprogram *getSubprogram(Metadata *LocalScope) {
5312 if (!LocalScope)
5313 return nullptr;
5314
5315 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
5316 return SP;
5317
5318 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
5319 return getSubprogram(LB->getRawScope());
5320
5321 // Just return null; broken scope chains are checked elsewhere.
5322 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope")((void)0);
5323 return nullptr;
5324}
5325
5326void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
5327 unsigned NumOperands;
5328 bool HasRoundingMD;
5329 switch (FPI.getIntrinsicID()) {
5330#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
5331 case Intrinsic::INTRINSIC: \
5332 NumOperands = NARG; \
5333 HasRoundingMD = ROUND_MODE; \
5334 break;
5335#include "llvm/IR/ConstrainedOps.def"
5336 default:
5337 llvm_unreachable("Invalid constrained FP intrinsic!")__builtin_unreachable();
5338 }
5339 NumOperands += (1 + HasRoundingMD);
5340 // Compare intrinsics carry an extra predicate metadata operand.
5341 if (isa<ConstrainedFPCmpIntrinsic>(FPI))
5342 NumOperands += 1;
5343 Assert((FPI.getNumArgOperands() == NumOperands),do { if (!((FPI.getNumArgOperands() == NumOperands))) { CheckFailed
("invalid arguments for constrained FP intrinsic", &FPI);
return; } } while (false)
5344 "invalid arguments for constrained FP intrinsic", &FPI)do { if (!((FPI.getNumArgOperands() == NumOperands))) { CheckFailed
("invalid arguments for constrained FP intrinsic", &FPI);
return; } } while (false)
;
5345
5346 switch (FPI.getIntrinsicID()) {
5347 case Intrinsic::experimental_constrained_lrint:
5348 case Intrinsic::experimental_constrained_llrint: {
5349 Type *ValTy = FPI.getArgOperand(0)->getType();
5350 Type *ResultTy = FPI.getType();
5351 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),do { if (!(!ValTy->isVectorTy() && !ResultTy->isVectorTy
())) { CheckFailed("Intrinsic does not support vectors", &
FPI); return; } } while (false)
5352 "Intrinsic does not support vectors", &FPI)do { if (!(!ValTy->isVectorTy() && !ResultTy->isVectorTy
())) { CheckFailed("Intrinsic does not support vectors", &
FPI); return; } } while (false)
;
5353 }
5354 break;
5355
5356 case Intrinsic::experimental_constrained_lround:
5357 case Intrinsic::experimental_constrained_llround: {
5358 Type *ValTy = FPI.getArgOperand(0)->getType();
5359 Type *ResultTy = FPI.getType();
5360 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),do { if (!(!ValTy->isVectorTy() && !ResultTy->isVectorTy
())) { CheckFailed("Intrinsic does not support vectors", &
FPI); return; } } while (false)
5361 "Intrinsic does not support vectors", &FPI)do { if (!(!ValTy->isVectorTy() && !ResultTy->isVectorTy
())) { CheckFailed("Intrinsic does not support vectors", &
FPI); return; } } while (false)
;
5362 break;
5363 }
5364
5365 case Intrinsic::experimental_constrained_fcmp:
5366 case Intrinsic::experimental_constrained_fcmps: {
5367 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
5368 Assert(CmpInst::isFPPredicate(Pred),do { if (!(CmpInst::isFPPredicate(Pred))) { CheckFailed("invalid predicate for constrained FP comparison intrinsic"
, &FPI); return; } } while (false)
5369 "invalid predicate for constrained FP comparison intrinsic", &FPI)do { if (!(CmpInst::isFPPredicate(Pred))) { CheckFailed("invalid predicate for constrained FP comparison intrinsic"
, &FPI); return; } } while (false)
;
5370 break;
5371 }
5372
5373 case Intrinsic::experimental_constrained_fptosi:
5374 case Intrinsic::experimental_constrained_fptoui: {
5375 Value *Operand = FPI.getArgOperand(0);
5376 uint64_t NumSrcElem = 0;
5377 Assert(Operand->getType()->isFPOrFPVectorTy(),do { if (!(Operand->getType()->isFPOrFPVectorTy())) { CheckFailed
("Intrinsic first argument must be floating point", &FPI)
; return; } } while (false)
5378 "Intrinsic first argument must be floating point", &FPI)do { if (!(Operand->getType()->isFPOrFPVectorTy())) { CheckFailed
("Intrinsic first argument must be floating point", &FPI)
; return; } } while (false)
;
5379 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5380 NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5381 }
5382
5383 Operand = &FPI;
5384 Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),do { if (!((NumSrcElem > 0) == Operand->getType()->isVectorTy
())) { CheckFailed("Intrinsic first argument and result disagree on vector use"
, &FPI); return; } } while (false)
5385 "Intrinsic first argument and result disagree on vector use", &FPI)do { if (!((NumSrcElem > 0) == Operand->getType()->isVectorTy
())) { CheckFailed("Intrinsic first argument and result disagree on vector use"
, &FPI); return; } } while (false)
;
5386 Assert(Operand->getType()->isIntOrIntVectorTy(),do { if (!(Operand->getType()->isIntOrIntVectorTy())) {
CheckFailed("Intrinsic result must be an integer", &FPI)
; return; } } while (false)
5387 "Intrinsic result must be an integer", &FPI)do { if (!(Operand->getType()->isIntOrIntVectorTy())) {
CheckFailed("Intrinsic result must be an integer", &FPI)
; return; } } while (false)
;
5388 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5389 Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),do { if (!(NumSrcElem == cast<FixedVectorType>(OperandT
)->getNumElements())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
5390 "Intrinsic first argument and result vector lengths must be equal",do { if (!(NumSrcElem == cast<FixedVectorType>(OperandT
)->getNumElements())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
5391 &FPI)do { if (!(NumSrcElem == cast<FixedVectorType>(OperandT
)->getNumElements())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
;
5392 }
5393 }
5394 break;
5395
5396 case Intrinsic::experimental_constrained_sitofp:
5397 case Intrinsic::experimental_constrained_uitofp: {
5398 Value *Operand = FPI.getArgOperand(0);
5399 uint64_t NumSrcElem = 0;
5400 Assert(Operand->getType()->isIntOrIntVectorTy(),do { if (!(Operand->getType()->isIntOrIntVectorTy())) {
CheckFailed("Intrinsic first argument must be integer", &
FPI); return; } } while (false)
5401 "Intrinsic first argument must be integer", &FPI)do { if (!(Operand->getType()->isIntOrIntVectorTy())) {
CheckFailed("Intrinsic first argument must be integer", &
FPI); return; } } while (false)
;
5402 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5403 NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5404 }
5405
5406 Operand = &FPI;
5407 Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),do { if (!((NumSrcElem > 0) == Operand->getType()->isVectorTy
())) { CheckFailed("Intrinsic first argument and result disagree on vector use"
, &FPI); return; } } while (false)
5408 "Intrinsic first argument and result disagree on vector use", &FPI)do { if (!((NumSrcElem > 0) == Operand->getType()->isVectorTy
())) { CheckFailed("Intrinsic first argument and result disagree on vector use"
, &FPI); return; } } while (false)
;
5409 Assert(Operand->getType()->isFPOrFPVectorTy(),do { if (!(Operand->getType()->isFPOrFPVectorTy())) { CheckFailed
("Intrinsic result must be a floating point", &FPI); return
; } } while (false)
5410 "Intrinsic result must be a floating point", &FPI)do { if (!(Operand->getType()->isFPOrFPVectorTy())) { CheckFailed
("Intrinsic result must be a floating point", &FPI); return
; } } while (false)
;
5411 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5412 Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),do { if (!(NumSrcElem == cast<FixedVectorType>(OperandT
)->getNumElements())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
5413 "Intrinsic first argument and result vector lengths must be equal",do { if (!(NumSrcElem == cast<FixedVectorType>(OperandT
)->getNumElements())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
5414 &FPI)do { if (!(NumSrcElem == cast<FixedVectorType>(OperandT
)->getNumElements())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
;
5415 }
5416 } break;
5417
5418 case Intrinsic::experimental_constrained_fptrunc:
5419 case Intrinsic::experimental_constrained_fpext: {
5420 Value *Operand = FPI.getArgOperand(0);
5421 Type *OperandTy = Operand->getType();
5422 Value *Result = &FPI;
5423 Type *ResultTy = Result->getType();
5424 Assert(OperandTy->isFPOrFPVectorTy(),do { if (!(OperandTy->isFPOrFPVectorTy())) { CheckFailed("Intrinsic first argument must be FP or FP vector"
, &FPI); return; } } while (false)
5425 "Intrinsic first argument must be FP or FP vector", &FPI)do { if (!(OperandTy->isFPOrFPVectorTy())) { CheckFailed("Intrinsic first argument must be FP or FP vector"
, &FPI); return; } } while (false)
;
5426 Assert(ResultTy->isFPOrFPVectorTy(),do { if (!(ResultTy->isFPOrFPVectorTy())) { CheckFailed("Intrinsic result must be FP or FP vector"
, &FPI); return; } } while (false)
5427 "Intrinsic result must be FP or FP vector", &FPI)do { if (!(ResultTy->isFPOrFPVectorTy())) { CheckFailed("Intrinsic result must be FP or FP vector"
, &FPI); return; } } while (false)
;
5428 Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(),do { if (!(OperandTy->isVectorTy() == ResultTy->isVectorTy
())) { CheckFailed("Intrinsic first argument and result disagree on vector use"
, &FPI); return; } } while (false)
5429 "Intrinsic first argument and result disagree on vector use", &FPI)do { if (!(OperandTy->isVectorTy() == ResultTy->isVectorTy
())) { CheckFailed("Intrinsic first argument and result disagree on vector use"
, &FPI); return; } } while (false)
;
5430 if (OperandTy->isVectorTy()) {
5431 Assert(cast<FixedVectorType>(OperandTy)->getNumElements() ==do { if (!(cast<FixedVectorType>(OperandTy)->getNumElements
() == cast<FixedVectorType>(ResultTy)->getNumElements
())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
5432 cast<FixedVectorType>(ResultTy)->getNumElements(),do { if (!(cast<FixedVectorType>(OperandTy)->getNumElements
() == cast<FixedVectorType>(ResultTy)->getNumElements
())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
5433 "Intrinsic first argument and result vector lengths must be equal",do { if (!(cast<FixedVectorType>(OperandTy)->getNumElements
() == cast<FixedVectorType>(ResultTy)->getNumElements
())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
5434 &FPI)do { if (!(cast<FixedVectorType>(OperandTy)->getNumElements
() == cast<FixedVectorType>(ResultTy)->getNumElements
())) { CheckFailed("Intrinsic first argument and result vector lengths must be equal"
, &FPI); return; } } while (false)
;
5435 }
5436 if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
5437 Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),do { if (!(OperandTy->getScalarSizeInBits() > ResultTy->
getScalarSizeInBits())) { CheckFailed("Intrinsic first argument's type must be larger than result type"
, &FPI); return; } } while (false)
5438 "Intrinsic first argument's type must be larger than result type",do { if (!(OperandTy->getScalarSizeInBits() > ResultTy->
getScalarSizeInBits())) { CheckFailed("Intrinsic first argument's type must be larger than result type"
, &FPI); return; } } while (false)
5439 &FPI)do { if (!(OperandTy->getScalarSizeInBits() > ResultTy->
getScalarSizeInBits())) { CheckFailed("Intrinsic first argument's type must be larger than result type"
, &FPI); return; } } while (false)
;
5440 } else {
5441 Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),do { if (!(OperandTy->getScalarSizeInBits() < ResultTy->
getScalarSizeInBits())) { CheckFailed("Intrinsic first argument's type must be smaller than result type"
, &FPI); return; } } while (false)
5442 "Intrinsic first argument's type must be smaller than result type",do { if (!(OperandTy->getScalarSizeInBits() < ResultTy->
getScalarSizeInBits())) { CheckFailed("Intrinsic first argument's type must be smaller than result type"
, &FPI); return; } } while (false)
5443 &FPI)do { if (!(OperandTy->getScalarSizeInBits() < ResultTy->
getScalarSizeInBits())) { CheckFailed("Intrinsic first argument's type must be smaller than result type"
, &FPI); return; } } while (false)
;
5444 }
5445 }
5446 break;
5447
5448 default:
5449 break;
5450 }
5451
5452 // If a non-metadata argument is passed in a metadata slot then the
5453 // error will be caught earlier when the incorrect argument doesn't
5454 // match the specification in the intrinsic call table. Thus, no
5455 // argument type check is needed here.
5456
5457 Assert(FPI.getExceptionBehavior().hasValue(),do { if (!(FPI.getExceptionBehavior().hasValue())) { CheckFailed
("invalid exception behavior argument", &FPI); return; } }
while (false)
5458 "invalid exception behavior argument", &FPI)do { if (!(FPI.getExceptionBehavior().hasValue())) { CheckFailed
("invalid exception behavior argument", &FPI); return; } }
while (false)
;
5459 if (HasRoundingMD) {
5460 Assert(FPI.getRoundingMode().hasValue(),do { if (!(FPI.getRoundingMode().hasValue())) { CheckFailed("invalid rounding mode argument"
, &FPI); return; } } while (false)
5461 "invalid rounding mode argument", &FPI)do { if (!(FPI.getRoundingMode().hasValue())) { CheckFailed("invalid rounding mode argument"
, &FPI); return; } } while (false)
;
5462 }
5463}
5464
5465void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
5466 auto *MD = DII.getRawLocation();
5467 AssertDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||do { if (!(isa<ValueAsMetadata>(MD) || isa<DIArgList
>(MD) || (isa<MDNode>(MD) && !cast<MDNode
>(MD)->getNumOperands()))) { DebugInfoCheckFailed("invalid llvm.dbg."
+ Kind + " intrinsic address/value", &DII, MD); return; }
} while (false)
5468 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),do { if (!(isa<ValueAsMetadata>(MD) || isa<DIArgList
>(MD) || (isa<MDNode>(MD) && !cast<MDNode
>(MD)->getNumOperands()))) { DebugInfoCheckFailed("invalid llvm.dbg."
+ Kind + " intrinsic address/value", &DII, MD); return; }
} while (false)
5469 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD)do { if (!(isa<ValueAsMetadata>(MD) || isa<DIArgList
>(MD) || (isa<MDNode>(MD) && !cast<MDNode
>(MD)->getNumOperands()))) { DebugInfoCheckFailed("invalid llvm.dbg."
+ Kind + " intrinsic address/value", &DII, MD); return; }
} while (false)
;
5470 AssertDI(isa<DILocalVariable>(DII.getRawVariable()),do { if (!(isa<DILocalVariable>(DII.getRawVariable())))
{ DebugInfoCheckFailed("invalid llvm.dbg." + Kind + " intrinsic variable"
, &DII, DII.getRawVariable()); return; } } while (false)
5471 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,do { if (!(isa<DILocalVariable>(DII.getRawVariable())))
{ DebugInfoCheckFailed("invalid llvm.dbg." + Kind + " intrinsic variable"
, &DII, DII.getRawVariable()); return; } } while (false)
5472 DII.getRawVariable())do { if (!(isa<DILocalVariable>(DII.getRawVariable())))
{ DebugInfoCheckFailed("invalid llvm.dbg." + Kind + " intrinsic variable"
, &DII, DII.getRawVariable()); return; } } while (false)
;
5473 AssertDI(isa<DIExpression>(DII.getRawExpression()),do { if (!(isa<DIExpression>(DII.getRawExpression()))) {
DebugInfoCheckFailed("invalid llvm.dbg." + Kind + " intrinsic expression"
, &DII, DII.getRawExpression()); return; } } while (false
)
5474 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,do { if (!(isa<DIExpression>(DII.getRawExpression()))) {
DebugInfoCheckFailed("invalid llvm.dbg." + Kind + " intrinsic expression"
, &DII, DII.getRawExpression()); return; } } while (false
)
5475 DII.getRawExpression())do { if (!(isa<DIExpression>(DII.getRawExpression()))) {
DebugInfoCheckFailed("invalid llvm.dbg." + Kind + " intrinsic expression"
, &DII, DII.getRawExpression()); return; } } while (false
)
;
5476
5477 // Ignore broken !dbg attachments; they're checked elsewhere.
5478 if (MDNode *N = DII.getDebugLoc().getAsMDNode())
5479 if (!isa<DILocation>(N))
5480 return;
5481
5482 BasicBlock *BB = DII.getParent();
5483 Function *F = BB ? BB->getParent() : nullptr;
5484
5485 // The scopes for variables and !dbg attachments must agree.
5486 DILocalVariable *Var = DII.getVariable();
5487 DILocation *Loc = DII.getDebugLoc();
5488 AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",do { if (!(Loc)) { DebugInfoCheckFailed("llvm.dbg." + Kind + " intrinsic requires a !dbg attachment"
, &DII, BB, F); return; } } while (false)
5489 &DII, BB, F)do { if (!(Loc)) { DebugInfoCheckFailed("llvm.dbg." + Kind + " intrinsic requires a !dbg attachment"
, &DII, BB, F); return; } } while (false)
;
5490
5491 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
5492 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
5493 if (!VarSP || !LocSP)
5494 return; // Broken scope chains are checked elsewhere.
5495
5496 AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +do { if (!(VarSP == LocSP)) { DebugInfoCheckFailed("mismatched subprogram between llvm.dbg."
+ Kind + " variable and !dbg attachment", &DII, BB, F, Var
, Var->getScope()->getSubprogram(), Loc, Loc->getScope
()->getSubprogram()); return; } } while (false)
5497 " variable and !dbg attachment",do { if (!(VarSP == LocSP)) { DebugInfoCheckFailed("mismatched subprogram between llvm.dbg."
+ Kind + " variable and !dbg attachment", &DII, BB, F, Var
, Var->getScope()->getSubprogram(), Loc, Loc->getScope
()->getSubprogram()); return; } } while (false)
5498 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,do { if (!(VarSP == LocSP)) { DebugInfoCheckFailed("mismatched subprogram between llvm.dbg."
+ Kind + " variable and !dbg attachment", &DII, BB, F, Var
, Var->getScope()->getSubprogram(), Loc, Loc->getScope
()->getSubprogram()); return; } } while (false)
5499 Loc->getScope()->getSubprogram())do { if (!(VarSP == LocSP)) { DebugInfoCheckFailed("mismatched subprogram between llvm.dbg."
+ Kind + " variable and !dbg attachment", &DII, BB, F, Var
, Var->getScope()->getSubprogram(), Loc, Loc->getScope
()->getSubprogram()); return; } } while (false)
;
5500
5501 // This check is redundant with one in visitLocalVariable().
5502 AssertDI(isType(Var->getRawType()), "invalid type ref", Var,do { if (!(isType(Var->getRawType()))) { DebugInfoCheckFailed
("invalid type ref", Var, Var->getRawType()); return; } } while
(false)
5503 Var->getRawType())do { if (!(isType(Var->getRawType()))) { DebugInfoCheckFailed
("invalid type ref", Var, Var->getRawType()); return; } } while
(false)
;
5504 verifyFnArgs(DII);
5505}
5506
5507void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
5508 AssertDI(isa<DILabel>(DLI.getRawLabel()),do { if (!(isa<DILabel>(DLI.getRawLabel()))) { DebugInfoCheckFailed
("invalid llvm.dbg." + Kind + " intrinsic variable", &DLI
, DLI.getRawLabel()); return; } } while (false)
5509 "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,do { if (!(isa<DILabel>(DLI.getRawLabel()))) { DebugInfoCheckFailed
("invalid llvm.dbg." + Kind + " intrinsic variable", &DLI
, DLI.getRawLabel()); return; } } while (false)
5510 DLI.getRawLabel())do { if (!(isa<DILabel>(DLI.getRawLabel()))) { DebugInfoCheckFailed
("invalid llvm.dbg." + Kind + " intrinsic variable", &DLI
, DLI.getRawLabel()); return; } } while (false)
;
5511
5512 // Ignore broken !dbg attachments; they're checked elsewhere.
5513 if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
5514 if (!isa<DILocation>(N))
5515 return;
5516
5517 BasicBlock *BB = DLI.getParent();
5518 Function *F = BB ? BB->getParent() : nullptr;
5519
5520 // The scopes for variables and !dbg attachments must agree.
5521 DILabel *Label = DLI.getLabel();
5522 DILocation *Loc = DLI.getDebugLoc();
5523 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",do { if (!(Loc)) { CheckFailed("llvm.dbg." + Kind + " intrinsic requires a !dbg attachment"
, &DLI, BB, F); return; } } while (false)
5524 &DLI, BB, F)do { if (!(Loc)) { CheckFailed("llvm.dbg." + Kind + " intrinsic requires a !dbg attachment"
, &DLI, BB, F); return; } } while (false)
;
5525
5526 DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
5527 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
5528 if (!LabelSP || !LocSP)
5529 return;
5530
5531 AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +do { if (!(LabelSP == LocSP)) { DebugInfoCheckFailed("mismatched subprogram between llvm.dbg."
+ Kind + " label and !dbg attachment", &DLI, BB, F, Label
, Label->getScope()->getSubprogram(), Loc, Loc->getScope
()->getSubprogram()); return; } } while (false)
5532 " label and !dbg attachment",do { if (!(LabelSP == LocSP)) { DebugInfoCheckFailed("mismatched subprogram between llvm.dbg."
+ Kind + " label and !dbg attachment", &DLI, BB, F, Label
, Label->getScope()->getSubprogram(), Loc, Loc->getScope
()->getSubprogram()); return; } } while (false)
5533 &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,do { if (!(LabelSP == LocSP)) { DebugInfoCheckFailed("mismatched subprogram between llvm.dbg."
+ Kind + " label and !dbg attachment", &DLI, BB, F, Label
, Label->getScope()->getSubprogram(), Loc, Loc->getScope
()->getSubprogram()); return; } } while (false)
5534 Loc->getScope()->getSubprogram())do { if (!(LabelSP == LocSP)) { DebugInfoCheckFailed("mismatched subprogram between llvm.dbg."
+ Kind + " label and !dbg attachment", &DLI, BB, F, Label
, Label->getScope()->getSubprogram(), Loc, Loc->getScope
()->getSubprogram()); return; } } while (false)
;
5535}
5536
5537void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
5538 DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
5539 DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
5540
5541 // We don't know whether this intrinsic verified correctly.
5542 if (!V || !E || !E->isValid())
5543 return;
5544
5545 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
5546 auto Fragment = E->getFragmentInfo();
5547 if (!Fragment)
5548 return;
5549
5550 // The frontend helps out GDB by emitting the members of local anonymous
5551 // unions as artificial local variables with shared storage. When SROA splits
5552 // the storage for artificial local variables that are smaller than the entire
5553 // union, the overhang piece will be outside of the allotted space for the
5554 // variable and this check fails.
5555 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
5556 if (V->isArtificial())
5557 return;
5558
5559 verifyFragmentExpression(*V, *Fragment, &I);
5560}
5561
5562template <typename ValueOrMetadata>
5563void Verifier::verifyFragmentExpression(const DIVariable &V,
5564 DIExpression::FragmentInfo Fragment,
5565 ValueOrMetadata *Desc) {
5566 // If there's no size, the type is broken, but that should be checked
5567 // elsewhere.
5568 auto VarSize = V.getSizeInBits();
5569 if (!VarSize)
5570 return;
5571
5572 unsigned FragSize = Fragment.SizeInBits;
5573 unsigned FragOffset = Fragment.OffsetInBits;
5574 AssertDI(FragSize + FragOffset <= *VarSize,do { if (!(FragSize + FragOffset <= *VarSize)) { DebugInfoCheckFailed
("fragment is larger than or outside of variable", Desc, &
V); return; } } while (false)
5575 "fragment is larger than or outside of variable", Desc, &V)do { if (!(FragSize + FragOffset <= *VarSize)) { DebugInfoCheckFailed
("fragment is larger than or outside of variable", Desc, &
V); return; } } while (false)
;
5576 AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V)do { if (!(FragSize != *VarSize)) { DebugInfoCheckFailed("fragment covers entire variable"
, Desc, &V); return; } } while (false)
;
5577}
5578
5579void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
5580 // This function does not take the scope of noninlined function arguments into
5581 // account. Don't run it if current function is nodebug, because it may
5582 // contain inlined debug intrinsics.
5583 if (!HasDebugInfo)
5584 return;
5585
5586 // For performance reasons only check non-inlined ones.
5587 if (I.getDebugLoc()->getInlinedAt())
5588 return;
5589
5590 DILocalVariable *Var = I.getVariable();
5591 AssertDI(Var, "dbg intrinsic without variable")do { if (!(Var)) { DebugInfoCheckFailed("dbg intrinsic without variable"
); return; } } while (false)
;
5592
5593 unsigned ArgNo = Var->getArg();
5594 if (!ArgNo)
5595 return;
5596
5597 // Verify there are no duplicate function argument debug info entries.
5598 // These will cause hard-to-debug assertions in the DWARF backend.
5599 if (DebugFnArgs.size() < ArgNo)
5600 DebugFnArgs.resize(ArgNo, nullptr);
5601
5602 auto *Prev = DebugFnArgs[ArgNo - 1];
5603 DebugFnArgs[ArgNo - 1] = Var;
5604 AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,do { if (!(!Prev || (Prev == Var))) { DebugInfoCheckFailed("conflicting debug info for argument"
, &I, Prev, Var); return; } } while (false)
5605 Prev, Var)do { if (!(!Prev || (Prev == Var))) { DebugInfoCheckFailed("conflicting debug info for argument"
, &I, Prev, Var); return; } } while (false)
;
5606}
5607
5608void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
5609 DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
5610
5611 // We don't know whether this intrinsic verified correctly.
5612 if (!E || !E->isValid())
5613 return;
5614
5615 AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I)do { if (!(!E->isEntryValue())) { DebugInfoCheckFailed("Entry values are only allowed in MIR"
, &I); return; } } while (false)
;
5616}
5617
5618void Verifier::verifyCompileUnits() {
5619 // When more than one Module is imported into the same context, such as during
5620 // an LTO build before linking the modules, ODR type uniquing may cause types
5621 // to point to a different CU. This check does not make sense in this case.
5622 if (M.getContext().isODRUniquingDebugTypes())
5623 return;
5624 auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
5625 SmallPtrSet<const Metadata *, 2> Listed;
5626 if (CUs)
5627 Listed.insert(CUs->op_begin(), CUs->op_end());
5628 for (auto *CU : CUVisited)
5629 AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU)do { if (!(Listed.count(CU))) { DebugInfoCheckFailed("DICompileUnit not listed in llvm.dbg.cu"
, CU); return; } } while (false)
;
5630 CUVisited.clear();
5631}
5632
5633void Verifier::verifyDeoptimizeCallingConvs() {
5634 if (DeoptimizeDeclarations.empty())
5635 return;
5636
5637 const Function *First = DeoptimizeDeclarations[0];
5638 for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
5639 Assert(First->getCallingConv() == F->getCallingConv(),do { if (!(First->getCallingConv() == F->getCallingConv
())) { CheckFailed("All llvm.experimental.deoptimize declarations must have the same "
"calling convention", First, F); return; } } while (false)
5640 "All llvm.experimental.deoptimize declarations must have the same "do { if (!(First->getCallingConv() == F->getCallingConv
())) { CheckFailed("All llvm.experimental.deoptimize declarations must have the same "
"calling convention", First, F); return; } } while (false)
5641 "calling convention",do { if (!(First->getCallingConv() == F->getCallingConv
())) { CheckFailed("All llvm.experimental.deoptimize declarations must have the same "
"calling convention", First, F); return; } } while (false)
5642 First, F)do { if (!(First->getCallingConv() == F->getCallingConv
())) { CheckFailed("All llvm.experimental.deoptimize declarations must have the same "
"calling convention", First, F); return; } } while (false)
;
5643 }
5644}
5645
5646void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
5647 bool HasSource = F.getSource().hasValue();
5648 if (!HasSourceDebugInfo.count(&U))
5649 HasSourceDebugInfo[&U] = HasSource;
5650 AssertDI(HasSource == HasSourceDebugInfo[&U],do { if (!(HasSource == HasSourceDebugInfo[&U])) { DebugInfoCheckFailed
("inconsistent use of embedded source"); return; } } while (false
)
5651 "inconsistent use of embedded source")do { if (!(HasSource == HasSourceDebugInfo[&U])) { DebugInfoCheckFailed
("inconsistent use of embedded source"); return; } } while (false
)
;
5652}
5653
5654void Verifier::verifyNoAliasScopeDecl() {
5655 if (NoAliasScopeDecls.empty())
5656 return;
5657
5658 // only a single scope must be declared at a time.
5659 for (auto *II : NoAliasScopeDecls) {
5660 assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&((void)0)
5661 "Not a llvm.experimental.noalias.scope.decl ?")((void)0);
5662 const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
5663 II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5664 Assert(ScopeListMV != nullptr,do { if (!(ScopeListMV != nullptr)) { CheckFailed("llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
"argument", II); return; } } while (false)
5665 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "do { if (!(ScopeListMV != nullptr)) { CheckFailed("llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
"argument", II); return; } } while (false)
5666 "argument",do { if (!(ScopeListMV != nullptr)) { CheckFailed("llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
"argument", II); return; } } while (false)
5667 II)do { if (!(ScopeListMV != nullptr)) { CheckFailed("llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
"argument", II); return; } } while (false)
;
5668
5669 const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
5670 Assert(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode",do { if (!(ScopeListMD != nullptr)) { CheckFailed("!id.scope.list must point to an MDNode"
, II); return; } } while (false)
5671 II)do { if (!(ScopeListMD != nullptr)) { CheckFailed("!id.scope.list must point to an MDNode"
, II); return; } } while (false)
;
5672 Assert(ScopeListMD->getNumOperands() == 1,do { if (!(ScopeListMD->getNumOperands() == 1)) { CheckFailed
("!id.scope.list must point to a list with a single scope", II
); return; } } while (false)
5673 "!id.scope.list must point to a list with a single scope", II)do { if (!(ScopeListMD->getNumOperands() == 1)) { CheckFailed
("!id.scope.list must point to a list with a single scope", II
); return; } } while (false)
;
5674 }
5675
5676 // Only check the domination rule when requested. Once all passes have been
5677 // adapted this option can go away.
5678 if (!VerifyNoAliasScopeDomination)
5679 return;
5680
5681 // Now sort the intrinsics based on the scope MDNode so that declarations of
5682 // the same scopes are next to each other.
5683 auto GetScope = [](IntrinsicInst *II) {
5684 const auto *ScopeListMV = cast<MetadataAsValue>(
5685 II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5686 return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
5687 };
5688
5689 // We are sorting on MDNode pointers here. For valid input IR this is ok.
5690 // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
5691 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
5692 return GetScope(Lhs) < GetScope(Rhs);
5693 };
5694
5695 llvm::sort(NoAliasScopeDecls, Compare);
5696
5697 // Go over the intrinsics and check that for the same scope, they are not
5698 // dominating each other.
5699 auto ItCurrent = NoAliasScopeDecls.begin();
5700 while (ItCurrent != NoAliasScopeDecls.end()) {
5701 auto CurScope = GetScope(*ItCurrent);
5702 auto ItNext = ItCurrent;
5703 do {
5704 ++ItNext;
5705 } while (ItNext != NoAliasScopeDecls.end() &&
5706 GetScope(*ItNext) == CurScope);
5707
5708 // [ItCurrent, ItNext) represents the declarations for the same scope.
5709 // Ensure they are not dominating each other.. but only if it is not too
5710 // expensive.
5711 if (ItNext - ItCurrent < 32)
5712 for (auto *I : llvm::make_range(ItCurrent, ItNext))
5713 for (auto *J : llvm::make_range(ItCurrent, ItNext))
5714 if (I != J)
5715 Assert(!DT.dominates(I, J),do { if (!(!DT.dominates(I, J))) { CheckFailed("llvm.experimental.noalias.scope.decl dominates another one "
"with the same scope", I); return; } } while (false)
5716 "llvm.experimental.noalias.scope.decl dominates another one "do { if (!(!DT.dominates(I, J))) { CheckFailed("llvm.experimental.noalias.scope.decl dominates another one "
"with the same scope", I); return; } } while (false)
5717 "with the same scope",do { if (!(!DT.dominates(I, J))) { CheckFailed("llvm.experimental.noalias.scope.decl dominates another one "
"with the same scope", I); return; } } while (false)
5718 I)do { if (!(!DT.dominates(I, J))) { CheckFailed("llvm.experimental.noalias.scope.decl dominates another one "
"with the same scope", I); return; } } while (false)
;
5719 ItCurrent = ItNext;
5720 }
5721}
5722
5723//===----------------------------------------------------------------------===//
5724// Implement the public interfaces to this file...
5725//===----------------------------------------------------------------------===//
5726
5727bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
5728 Function &F = const_cast<Function &>(f);
5729
5730 // Don't use a raw_null_ostream. Printing IR is expensive.
5731 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
5732
5733 // Note that this function's return value is inverted from what you would
5734 // expect of a function called "verify".
5735 return !V.verify(F);
5736}
5737
5738bool llvm::verifyModule(const Module &M, raw_ostream *OS,
5739 bool *BrokenDebugInfo) {
5740 // Don't use a raw_null_ostream. Printing IR is expensive.
5741 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
5742
5743 bool Broken = false;
5744 for (const Function &F : M)
5745 Broken |= !V.verify(F);
5746
5747 Broken |= !V.verify();
5748 if (BrokenDebugInfo)
5749 *BrokenDebugInfo = V.hasBrokenDebugInfo();
5750 // Note that this function's return value is inverted from what you would
5751 // expect of a function called "verify".
5752 return Broken;
5753}
5754
5755namespace {
5756
5757struct VerifierLegacyPass : public FunctionPass {
5758 static char ID;
5759
5760 std::unique_ptr<Verifier> V;
5761 bool FatalErrors = true;
5762
5763 VerifierLegacyPass() : FunctionPass(ID) {
5764 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5765 }
5766 explicit VerifierLegacyPass(bool FatalErrors)
5767 : FunctionPass(ID),
5768 FatalErrors(FatalErrors) {
5769 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5770 }
5771
5772 bool doInitialization(Module &M) override {
5773 V = std::make_unique<Verifier>(
5774 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
5775 return false;
5776 }
5777
5778 bool runOnFunction(Function &F) override {
5779 if (!V->verify(F) && FatalErrors) {
5780 errs() << "in function " << F.getName() << '\n';
5781 report_fatal_error("Broken function found, compilation aborted!");
5782 }
5783 return false;
5784 }
5785
5786 bool doFinalization(Module &M) override {
5787 bool HasErrors = false;
5788 for (Function &F : M)
5789 if (F.isDeclaration())
5790 HasErrors |= !V->verify(F);
5791
5792 HasErrors |= !V->verify();
5793 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
5794 report_fatal_error("Broken module found, compilation aborted!");
5795 return false;
5796 }
5797
5798 void getAnalysisUsage(AnalysisUsage &AU) const override {
5799 AU.setPreservesAll();
5800 }
5801};
5802
5803} // end anonymous namespace
5804
5805/// Helper to issue failure from the TBAA verification
5806template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
5807 if (Diagnostic)
5808 return Diagnostic->CheckFailed(Args...);
5809}
5810
5811#define AssertTBAA(C, ...)do { if (!(C)) { CheckFailed(...); return false; } } while (false
)
\
5812 do { \
5813 if (!(C)) { \
5814 CheckFailed(__VA_ARGS__); \
5815 return false; \
5816 } \
5817 } while (false)
5818
5819/// Verify that \p BaseNode can be used as the "base type" in the struct-path
5820/// TBAA scheme. This means \p BaseNode is either a scalar node, or a
5821/// struct-type node describing an aggregate data structure (like a struct).
5822TBAAVerifier::TBAABaseNodeSummary
5823TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
5824 bool IsNewFormat) {
5825 if (BaseNode->getNumOperands() < 2) {
5826 CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
5827 return {true, ~0u};
5828 }
5829
5830 auto Itr = TBAABaseNodes.find(BaseNode);
5831 if (Itr != TBAABaseNodes.end())
5832 return Itr->second;
5833
5834 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
5835 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
5836 (void)InsertResult;
5837 assert(InsertResult.second && "We just checked!")((void)0);
5838 return Result;
5839}
5840
5841TBAAVerifier::TBAABaseNodeSummary
5842TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
5843 bool IsNewFormat) {
5844 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
5845
5846 if (BaseNode->getNumOperands() == 2) {
5847 // Scalar nodes can only be accessed at offset 0.
5848 return isValidScalarTBAANode(BaseNode)
5849 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
5850 : InvalidNode;
5851 }
5852
5853 if (IsNewFormat) {
5854 if (BaseNode->getNumOperands() % 3 != 0) {
5855 CheckFailed("Access tag nodes must have the number of operands that is a "
5856 "multiple of 3!", BaseNode);
5857 return InvalidNode;
5858 }
5859 } else {
5860 if (BaseNode->getNumOperands() % 2 != 1) {
5861 CheckFailed("Struct tag nodes must have an odd number of operands!",
5862 BaseNode);
5863 return InvalidNode;
5864 }
5865 }
5866
5867 // Check the type size field.
5868 if (IsNewFormat) {
5869 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
5870 BaseNode->getOperand(1));
5871 if (!TypeSizeNode) {
5872 CheckFailed("Type size nodes must be constants!", &I, BaseNode);
5873 return InvalidNode;
5874 }
5875 }
5876
5877 // Check the type name field. In the new format it can be anything.
5878 if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
5879 CheckFailed("Struct tag nodes have a string as their first operand",
5880 BaseNode);
5881 return InvalidNode;
5882 }
5883
5884 bool Failed = false;
5885
5886 Optional<APInt> PrevOffset;
5887 unsigned BitWidth = ~0u;
5888
5889 // We've already checked that BaseNode is not a degenerate root node with one
5890 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
5891 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
5892 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
5893 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
5894 Idx += NumOpsPerField) {
5895 const MDOperand &FieldTy = BaseNode->getOperand(Idx);
5896 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
5897 if (!isa<MDNode>(FieldTy)) {
5898 CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
5899 Failed = true;
5900 continue;
5901 }
5902
5903 auto *OffsetEntryCI =
5904 mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
5905 if (!OffsetEntryCI) {
5906 CheckFailed("Offset entries must be constants!", &I, BaseNode);
5907 Failed = true;
5908 continue;
5909 }
5910
5911 if (BitWidth == ~0u)
5912 BitWidth = OffsetEntryCI->getBitWidth();
5913
5914 if (OffsetEntryCI->getBitWidth() != BitWidth) {
5915 CheckFailed(
5916 "Bitwidth between the offsets and struct type entries must match", &I,
5917 BaseNode);
5918 Failed = true;
5919 continue;
5920 }
5921
5922 // NB! As far as I can tell, we generate a non-strictly increasing offset
5923 // sequence only from structs that have zero size bit fields. When
5924 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
5925 // pick the field lexically the latest in struct type metadata node. This
5926 // mirrors the actual behavior of the alias analysis implementation.
5927 bool IsAscending =
5928 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
5929
5930 if (!IsAscending) {
5931 CheckFailed("Offsets must be increasing!", &I, BaseNode);
5932 Failed = true;
5933 }
5934
5935 PrevOffset = OffsetEntryCI->getValue();
5936
5937 if (IsNewFormat) {
5938 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
5939 BaseNode->getOperand(Idx + 2));
5940 if (!MemberSizeNode) {
5941 CheckFailed("Member size entries must be constants!", &I, BaseNode);
5942 Failed = true;
5943 continue;
5944 }
5945 }
5946 }
5947
5948 return Failed ? InvalidNode
5949 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
5950}
5951
5952static bool IsRootTBAANode(const MDNode *MD) {
5953 return MD->getNumOperands() < 2;
5954}
5955
5956static bool IsScalarTBAANodeImpl(const MDNode *MD,
5957 SmallPtrSetImpl<const MDNode *> &Visited) {
5958 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
5959 return false;
5960
5961 if (!isa<MDString>(MD->getOperand(0)))
5962 return false;
5963
5964 if (MD->getNumOperands() == 3) {
5965 auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
5966 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
5967 return false;
5968 }
5969
5970 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
5971 return Parent && Visited.insert(Parent).second &&
5972 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
5973}
5974
5975bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
5976 auto ResultIt = TBAAScalarNodes.find(MD);
5977 if (ResultIt != TBAAScalarNodes.end())
5978 return ResultIt->second;
5979
5980 SmallPtrSet<const MDNode *, 4> Visited;
5981 bool Result = IsScalarTBAANodeImpl(MD, Visited);
5982 auto InsertResult = TBAAScalarNodes.insert({MD, Result});
5983 (void)InsertResult;
5984 assert(InsertResult.second && "Just checked!")((void)0);
5985
5986 return Result;
5987}
5988
5989/// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
5990/// Offset in place to be the offset within the field node returned.
5991///
5992/// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
5993MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
5994 const MDNode *BaseNode,
5995 APInt &Offset,
5996 bool IsNewFormat) {
5997 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!")((void)0);
5998
5999 // Scalar nodes have only one possible "field" -- their parent in the access
6000 // hierarchy. Offset must be zero at this point, but our caller is supposed
6001 // to Assert that.
6002 if (BaseNode->getNumOperands() == 2)
6003 return cast<MDNode>(BaseNode->getOperand(1));
6004
6005 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
6006 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
6007 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
6008 Idx += NumOpsPerField) {
6009 auto *OffsetEntryCI =
6010 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
6011 if (OffsetEntryCI->getValue().ugt(Offset)) {
6012 if (Idx == FirstFieldOpNo) {
6013 CheckFailed("Could not find TBAA parent in struct type node", &I,
6014 BaseNode, &Offset);
6015 return nullptr;
6016 }
6017
6018 unsigned PrevIdx = Idx - NumOpsPerField;
6019 auto *PrevOffsetEntryCI =
6020 mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
6021 Offset -= PrevOffsetEntryCI->getValue();
6022 return cast<MDNode>(BaseNode->getOperand(PrevIdx));
6023 }
6024 }
6025
6026 unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
6027 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
6028 BaseNode->getOperand(LastIdx + 1));
6029 Offset -= LastOffsetEntryCI->getValue();
6030 return cast<MDNode>(BaseNode->getOperand(LastIdx));
6031}
6032
6033static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
6034 if (!Type || Type->getNumOperands() < 3)
6035 return false;
6036
6037 // In the new format type nodes shall have a reference to the parent type as
6038 // its first operand.
6039 MDNode *Parent = dyn_cast_or_null<MDNode>(Type->getOperand(0));
6040 if (!Parent)
6041 return false;
6042
6043 return true;
6044}
6045
6046bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
6047 AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||do { if (!(isa<LoadInst>(I) || isa<StoreInst>(I) ||
isa<CallInst>(I) || isa<VAArgInst>(I) || isa<
AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I))) { CheckFailed
("This instruction shall not have a TBAA access tag!", &I
); return false; } } while (false)
6048 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||do { if (!(isa<LoadInst>(I) || isa<StoreInst>(I) ||
isa<CallInst>(I) || isa<VAArgInst>(I) || isa<
AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I))) { CheckFailed
("This instruction shall not have a TBAA access tag!", &I
); return false; } } while (false)
6049 isa<AtomicCmpXchgInst>(I),do { if (!(isa<LoadInst>(I) || isa<StoreInst>(I) ||
isa<CallInst>(I) || isa<VAArgInst>(I) || isa<
AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I))) { CheckFailed
("This instruction shall not have a TBAA access tag!", &I
); return false; } } while (false)
6050 "This instruction shall not have a TBAA access tag!", &I)do { if (!(isa<LoadInst>(I) || isa<StoreInst>(I) ||
isa<CallInst>(I) || isa<VAArgInst>(I) || isa<
AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I))) { CheckFailed
("This instruction shall not have a TBAA access tag!", &I
); return false; } } while (false)
;
6051
6052 bool IsStructPathTBAA =
6053 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
6054
6055 AssertTBAA(do { if (!(IsStructPathTBAA)) { CheckFailed("Old-style TBAA is no longer allowed, use struct-path TBAA instead"
, &I); return false; } } while (false)
6056 IsStructPathTBAA,do { if (!(IsStructPathTBAA)) { CheckFailed("Old-style TBAA is no longer allowed, use struct-path TBAA instead"
, &I); return false; } } while (false)
6057 "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I)do { if (!(IsStructPathTBAA)) { CheckFailed("Old-style TBAA is no longer allowed, use struct-path TBAA instead"
, &I); return false; } } while (false)
;
6058
6059 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
6060 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
6061
6062 bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
6063
6064 if (IsNewFormat) {
6065 AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,do { if (!(MD->getNumOperands() == 4 || MD->getNumOperands
() == 5)) { CheckFailed("Access tag metadata must have either 4 or 5 operands"
, &I, MD); return false; } } while (false)
6066 "Access tag metadata must have either 4 or 5 operands", &I, MD)do { if (!(MD->getNumOperands() == 4 || MD->getNumOperands
() == 5)) { CheckFailed("Access tag metadata must have either 4 or 5 operands"
, &I, MD); return false; } } while (false)
;
6067 } else {
6068 AssertTBAA(MD->getNumOperands() < 5,do { if (!(MD->getNumOperands() < 5)) { CheckFailed("Struct tag metadata must have either 3 or 4 operands"
, &I, MD); return false; } } while (false)
6069 "Struct tag metadata must have either 3 or 4 operands", &I, MD)do { if (!(MD->getNumOperands() < 5)) { CheckFailed("Struct tag metadata must have either 3 or 4 operands"
, &I, MD); return false; } } while (false)
;
6070 }
6071
6072 // Check the access size field.
6073 if (IsNewFormat) {
6074 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6075 MD->getOperand(3));
6076 AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD)do { if (!(AccessSizeNode)) { CheckFailed("Access size field must be a constant"
, &I, MD); return false; } } while (false)
;
6077 }
6078
6079 // Check the immutability flag.
6080 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
6081 if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
6082 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
6083 MD->getOperand(ImmutabilityFlagOpNo));
6084 AssertTBAA(IsImmutableCI,do { if (!(IsImmutableCI)) { CheckFailed("Immutability tag on struct tag metadata must be a constant"
, &I, MD); return false; } } while (false)
6085 "Immutability tag on struct tag metadata must be a constant",do { if (!(IsImmutableCI)) { CheckFailed("Immutability tag on struct tag metadata must be a constant"
, &I, MD); return false; } } while (false)
6086 &I, MD)do { if (!(IsImmutableCI)) { CheckFailed("Immutability tag on struct tag metadata must be a constant"
, &I, MD); return false; } } while (false)
;
6087 AssertTBAA(do { if (!(IsImmutableCI->isZero() || IsImmutableCI->isOne
())) { CheckFailed("Immutability part of the struct tag metadata must be either 0 or 1"
, &I, MD); return false; } } while (false)
6088 IsImmutableCI->isZero() || IsImmutableCI->isOne(),do { if (!(IsImmutableCI->isZero() || IsImmutableCI->isOne
())) { CheckFailed("Immutability part of the struct tag metadata must be either 0 or 1"
, &I, MD); return false; } } while (false)
6089 "Immutability part of the struct tag metadata must be either 0 or 1",do { if (!(IsImmutableCI->isZero() || IsImmutableCI->isOne
())) { CheckFailed("Immutability part of the struct tag metadata must be either 0 or 1"
, &I, MD); return false; } } while (false)
6090 &I, MD)do { if (!(IsImmutableCI->isZero() || IsImmutableCI->isOne
())) { CheckFailed("Immutability part of the struct tag metadata must be either 0 or 1"
, &I, MD); return false; } } while (false)
;
6091 }
6092
6093 AssertTBAA(BaseNode && AccessType,do { if (!(BaseNode && AccessType)) { CheckFailed("Malformed struct tag metadata: base and access-type "
"should be non-null and point to Metadata nodes", &I, MD
, BaseNode, AccessType); return false; } } while (false)
6094 "Malformed struct tag metadata: base and access-type "do { if (!(BaseNode && AccessType)) { CheckFailed("Malformed struct tag metadata: base and access-type "
"should be non-null and point to Metadata nodes", &I, MD
, BaseNode, AccessType); return false; } } while (false)
6095 "should be non-null and point to Metadata nodes",do { if (!(BaseNode && AccessType)) { CheckFailed("Malformed struct tag metadata: base and access-type "
"should be non-null and point to Metadata nodes", &I, MD
, BaseNode, AccessType); return false; } } while (false)
6096 &I, MD, BaseNode, AccessType)do { if (!(BaseNode && AccessType)) { CheckFailed("Malformed struct tag metadata: base and access-type "
"should be non-null and point to Metadata nodes", &I, MD
, BaseNode, AccessType); return false; } } while (false)
;
6097
6098 if (!IsNewFormat) {
6099 AssertTBAA(isValidScalarTBAANode(AccessType),do { if (!(isValidScalarTBAANode(AccessType))) { CheckFailed(
"Access type node must be a valid scalar type", &I, MD, AccessType
); return false; } } while (false)
6100 "Access type node must be a valid scalar type", &I, MD,do { if (!(isValidScalarTBAANode(AccessType))) { CheckFailed(
"Access type node must be a valid scalar type", &I, MD, AccessType
); return false; } } while (false)
6101 AccessType)do { if (!(isValidScalarTBAANode(AccessType))) { CheckFailed(
"Access type node must be a valid scalar type", &I, MD, AccessType
); return false; } } while (false)
;
6102 }
6103
6104 auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
6105 AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD)do { if (!(OffsetCI)) { CheckFailed("Offset must be constant integer"
, &I, MD); return false; } } while (false)
;
6106
6107 APInt Offset = OffsetCI->getValue();
6108 bool SeenAccessTypeInPath = false;
6109
6110 SmallPtrSet<MDNode *, 4> StructPath;
6111
6112 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
6113 BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
6114 IsNewFormat)) {
6115 if (!StructPath.insert(BaseNode).second) {
6116 CheckFailed("Cycle detected in struct path", &I, MD);
6117 return false;
6118 }
6119
6120 bool Invalid;
6121 unsigned BaseNodeBitWidth;
6122 std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
6123 IsNewFormat);
6124
6125 // If the base node is invalid in itself, then we've already printed all the
6126 // errors we wanted to print.
6127 if (Invalid)
6128 return false;
6129
6130 SeenAccessTypeInPath |= BaseNode == AccessType;
6131
6132 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
6133 AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",do { if (!(Offset == 0)) { CheckFailed("Offset not zero at the point of scalar access"
, &I, MD, &Offset); return false; } } while (false)
6134 &I, MD, &Offset)do { if (!(Offset == 0)) { CheckFailed("Offset not zero at the point of scalar access"
, &I, MD, &Offset); return false; } } while (false)
;
6135
6136 AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||do { if (!(BaseNodeBitWidth == Offset.getBitWidth() || (BaseNodeBitWidth
== 0 && Offset == 0) || (IsNewFormat && BaseNodeBitWidth
== ~0u))) { CheckFailed("Access bit-width not the same as description bit-width"
, &I, MD, BaseNodeBitWidth, Offset.getBitWidth()); return
false; } } while (false)
6137 (BaseNodeBitWidth == 0 && Offset == 0) ||do { if (!(BaseNodeBitWidth == Offset.getBitWidth() || (BaseNodeBitWidth
== 0 && Offset == 0) || (IsNewFormat && BaseNodeBitWidth
== ~0u))) { CheckFailed("Access bit-width not the same as description bit-width"
, &I, MD, BaseNodeBitWidth, Offset.getBitWidth()); return
false; } } while (false)
6138 (IsNewFormat && BaseNodeBitWidth == ~0u),do { if (!(BaseNodeBitWidth == Offset.getBitWidth() || (BaseNodeBitWidth
== 0 && Offset == 0) || (IsNewFormat && BaseNodeBitWidth
== ~0u))) { CheckFailed("Access bit-width not the same as description bit-width"
, &I, MD, BaseNodeBitWidth, Offset.getBitWidth()); return
false; } } while (false)
6139 "Access bit-width not the same as description bit-width", &I, MD,do { if (!(BaseNodeBitWidth == Offset.getBitWidth() || (BaseNodeBitWidth
== 0 && Offset == 0) || (IsNewFormat && BaseNodeBitWidth
== ~0u))) { CheckFailed("Access bit-width not the same as description bit-width"
, &I, MD, BaseNodeBitWidth, Offset.getBitWidth()); return
false; } } while (false)
6140 BaseNodeBitWidth, Offset.getBitWidth())do { if (!(BaseNodeBitWidth == Offset.getBitWidth() || (BaseNodeBitWidth
== 0 && Offset == 0) || (IsNewFormat && BaseNodeBitWidth
== ~0u))) { CheckFailed("Access bit-width not the same as description bit-width"
, &I, MD, BaseNodeBitWidth, Offset.getBitWidth()); return
false; } } while (false)
;
6141
6142 if (IsNewFormat && SeenAccessTypeInPath)
6143 break;
6144 }
6145
6146 AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",do { if (!(SeenAccessTypeInPath)) { CheckFailed("Did not see access type in access path!"
, &I, MD); return false; } } while (false)
6147 &I, MD)do { if (!(SeenAccessTypeInPath)) { CheckFailed("Did not see access type in access path!"
, &I, MD); return false; } } while (false)
;
6148 return true;
6149}
6150
6151char VerifierLegacyPass::ID = 0;
6152INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)static void *initializeVerifierLegacyPassPassOnce(PassRegistry
&Registry) { PassInfo *PI = new PassInfo( "Module Verifier"
, "verify", &VerifierLegacyPass::ID, PassInfo::NormalCtor_t
(callDefaultCtor<VerifierLegacyPass>), false, false); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeVerifierLegacyPassPassFlag; void llvm::initializeVerifierLegacyPassPass
(PassRegistry &Registry) { llvm::call_once(InitializeVerifierLegacyPassPassFlag
, initializeVerifierLegacyPassPassOnce, std::ref(Registry)); }
6153
6154FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
6155 return new VerifierLegacyPass(FatalErrors);
6156}
6157
6158AnalysisKey VerifierAnalysis::Key;
6159VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
6160 ModuleAnalysisManager &) {
6161 Result Res;
6162 Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
6163 return Res;
6164}
6165
6166VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
6167 FunctionAnalysisManager &) {
6168 return { llvm::verifyFunction(F, &dbgs()), false };
6169}
6170
6171PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
6172 auto Res = AM.getResult<VerifierAnalysis>(M);
6173 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
6174 report_fatal_error("Broken module found, compilation aborted!");
6175
6176 return PreservedAnalyses::all();
6177}
6178
6179PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
6180 auto res = AM.getResult<VerifierAnalysis>(F);
6181 if (res.IRBroken && FatalErrors)
6182 report_fatal_error("Broken function found, compilation aborted!");
6183
6184 return PreservedAnalyses::all();
6185}

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IR/Instructions.h

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

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/Alignment.h

1//===-- llvm/Support/Alignment.h - Useful alignment functions ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains types to represent alignments.
10// They are instrumented to guarantee some invariants are preserved and prevent
11// invalid manipulations.
12//
13// - Align represents an alignment in bytes, it is always set and always a valid
14// power of two, its minimum value is 1 which means no alignment requirements.
15//
16// - MaybeAlign is an optional type, it may be undefined or set. When it's set
17// you can get the underlying Align type by using the getValue() method.
18//
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_SUPPORT_ALIGNMENT_H_
22#define LLVM_SUPPORT_ALIGNMENT_H_
23
24#include "llvm/ADT/Optional.h"
25#include "llvm/Support/MathExtras.h"
26#include <cassert>
27#ifndef NDEBUG1
28#include <string>
29#endif // NDEBUG
30
31namespace llvm {
32
33#define ALIGN_CHECK_ISPOSITIVE(decl) \
34 assert(decl > 0 && (#decl " should be defined"))((void)0)
35
36/// This struct is a compact representation of a valid (non-zero power of two)
37/// alignment.
38/// It is suitable for use as static global constants.
39struct Align {
40private:
41 uint8_t ShiftValue = 0; /// The log2 of the required alignment.
42 /// ShiftValue is less than 64 by construction.
43
44 friend struct MaybeAlign;
45 friend unsigned Log2(Align);
46 friend bool operator==(Align Lhs, Align Rhs);
47 friend bool operator!=(Align Lhs, Align Rhs);
48 friend bool operator<=(Align Lhs, Align Rhs);
49 friend bool operator>=(Align Lhs, Align Rhs);
50 friend bool operator<(Align Lhs, Align Rhs);
51 friend bool operator>(Align Lhs, Align Rhs);
52 friend unsigned encode(struct MaybeAlign A);
53 friend struct MaybeAlign decodeMaybeAlign(unsigned Value);
54
55 /// A trivial type to allow construction of constexpr Align.
56 /// This is currently needed to workaround a bug in GCC 5.3 which prevents
57 /// definition of constexpr assign operators.
58 /// https://stackoverflow.com/questions/46756288/explicitly-defaulted-function-cannot-be-declared-as-constexpr-because-the-implic
59 /// FIXME: Remove this, make all assign operators constexpr and introduce user
60 /// defined literals when we don't have to support GCC 5.3 anymore.
61 /// https://llvm.org/docs/GettingStarted.html#getting-a-modern-host-c-toolchain
62 struct LogValue {
63 uint8_t Log;
64 };
65
66public:
67 /// Default is byte-aligned.
68 constexpr Align() = default;
69 /// Do not perform checks in case of copy/move construct/assign, because the
70 /// checks have been performed when building `Other`.
71 constexpr Align(const Align &Other) = default;
72 constexpr Align(Align &&Other) = default;
73 Align &operator=(const Align &Other) = default;
74 Align &operator=(Align &&Other) = default;
75
76 explicit Align(uint64_t Value) {
77 assert(Value > 0 && "Value must not be 0")((void)0);
78 assert(llvm::isPowerOf2_64(Value) && "Alignment is not a power of 2")((void)0);
79 ShiftValue = Log2_64(Value);
7
Calling 'Log2_64'
9
Returning from 'Log2_64'
10
The value 255 is assigned to field 'ShiftValue'
80 assert(ShiftValue < 64 && "Broken invariant")((void)0);
81 }
82
83 /// This is a hole in the type system and should not be abused.
84 /// Needed to interact with C for instance.
85 uint64_t value() const { return uint64_t(1) << ShiftValue; }
14
The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'uint64_t'
86
87 /// Allow constructions of constexpr Align.
88 template <size_t kValue> constexpr static LogValue Constant() {
89 return LogValue{static_cast<uint8_t>(CTLog2<kValue>())};
90 }
91
92 /// Allow constructions of constexpr Align from types.
93 /// Compile time equivalent to Align(alignof(T)).
94 template <typename T> constexpr static LogValue Of() {
95 return Constant<std::alignment_of<T>::value>();
96 }
97
98 /// Constexpr constructor from LogValue type.
99 constexpr Align(LogValue CA) : ShiftValue(CA.Log) {}
100};
101
102/// Treats the value 0 as a 1, so Align is always at least 1.
103inline Align assumeAligned(uint64_t Value) {
104 return Value ? Align(Value) : Align();
105}
106
107/// This struct is a compact representation of a valid (power of two) or
108/// undefined (0) alignment.
109struct MaybeAlign : public llvm::Optional<Align> {
110private:
111 using UP = llvm::Optional<Align>;
112
113public:
114 /// Default is undefined.
115 MaybeAlign() = default;
116 /// Do not perform checks in case of copy/move construct/assign, because the
117 /// checks have been performed when building `Other`.
118 MaybeAlign(const MaybeAlign &Other) = default;
119 MaybeAlign &operator=(const MaybeAlign &Other) = default;
120 MaybeAlign(MaybeAlign &&Other) = default;
121 MaybeAlign &operator=(MaybeAlign &&Other) = default;
122
123 /// Use llvm::Optional<Align> constructor.
124 using UP::UP;
125
126 explicit MaybeAlign(uint64_t Value) {
127 assert((Value == 0 || llvm::isPowerOf2_64(Value)) &&((void)0)
128 "Alignment is neither 0 nor a power of 2")((void)0);
129 if (Value)
130 emplace(Value);
131 }
132
133 /// For convenience, returns a valid alignment or 1 if undefined.
134 Align valueOrOne() const { return hasValue() ? getValue() : Align(); }
135};
136
137/// Checks that SizeInBytes is a multiple of the alignment.
138inline bool isAligned(Align Lhs, uint64_t SizeInBytes) {
139 return SizeInBytes % Lhs.value() == 0;
140}
141
142/// Checks that Addr is a multiple of the alignment.
143inline bool isAddrAligned(Align Lhs, const void *Addr) {
144 return isAligned(Lhs, reinterpret_cast<uintptr_t>(Addr));
145}
146
147/// Returns a multiple of A needed to store `Size` bytes.
148inline uint64_t alignTo(uint64_t Size, Align A) {
149 const uint64_t Value = A.value();
150 // The following line is equivalent to `(Size + Value - 1) / Value * Value`.
151
152 // The division followed by a multiplication can be thought of as a right
153 // shift followed by a left shift which zeros out the extra bits produced in
154 // the bump; `~(Value - 1)` is a mask where all those bits being zeroed out
155 // are just zero.
156
157 // Most compilers can generate this code but the pattern may be missed when
158 // multiple functions gets inlined.
159 return (Size + Value - 1) & ~(Value - 1U);
160}
161
162/// If non-zero \p Skew is specified, the return value will be a minimal integer
163/// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
164/// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
165/// Skew mod \p A'.
166///
167/// Examples:
168/// \code
169/// alignTo(5, Align(8), 7) = 7
170/// alignTo(17, Align(8), 1) = 17
171/// alignTo(~0LL, Align(8), 3) = 3
172/// \endcode
173inline uint64_t alignTo(uint64_t Size, Align A, uint64_t Skew) {
174 const uint64_t Value = A.value();
175 Skew %= Value;
176 return ((Size + Value - 1 - Skew) & ~(Value - 1U)) + Skew;
177}
178
179/// Returns a multiple of A needed to store `Size` bytes.
180/// Returns `Size` if current alignment is undefined.
181inline uint64_t alignTo(uint64_t Size, MaybeAlign A) {
182 return A ? alignTo(Size, A.getValue()) : Size;
183}
184
185/// Aligns `Addr` to `Alignment` bytes, rounding up.
186inline uintptr_t alignAddr(const void *Addr, Align Alignment) {
187 uintptr_t ArithAddr = reinterpret_cast<uintptr_t>(Addr);
188 assert(static_cast<uintptr_t>(ArithAddr + Alignment.value() - 1) >=((void)0)
189 ArithAddr &&((void)0)
190 "Overflow")((void)0);
191 return alignTo(ArithAddr, Alignment);
192}
193
194/// Returns the offset to the next integer (mod 2**64) that is greater than
195/// or equal to \p Value and is a multiple of \p Align.
196inline uint64_t offsetToAlignment(uint64_t Value, Align Alignment) {
197 return alignTo(Value, Alignment) - Value;
198}
199
200/// Returns the necessary adjustment for aligning `Addr` to `Alignment`
201/// bytes, rounding up.
202inline uint64_t offsetToAlignedAddr(const void *Addr, Align Alignment) {
203 return offsetToAlignment(reinterpret_cast<uintptr_t>(Addr), Alignment);
204}
205
206/// Returns the log2 of the alignment.
207inline unsigned Log2(Align A) { return A.ShiftValue; }
208
209/// Returns the alignment that satisfies both alignments.
210/// Same semantic as MinAlign.
211inline Align commonAlignment(Align A, Align B) { return std::min(A, B); }
212
213/// Returns the alignment that satisfies both alignments.
214/// Same semantic as MinAlign.
215inline Align commonAlignment(Align A, uint64_t Offset) {
216 return Align(MinAlign(A.value(), Offset));
217}
218
219/// Returns the alignment that satisfies both alignments.
220/// Same semantic as MinAlign.
221inline MaybeAlign commonAlignment(MaybeAlign A, MaybeAlign B) {
222 return A && B ? commonAlignment(*A, *B) : A ? A : B;
223}
224
225/// Returns the alignment that satisfies both alignments.
226/// Same semantic as MinAlign.
227inline MaybeAlign commonAlignment(MaybeAlign A, uint64_t Offset) {
228 return MaybeAlign(MinAlign((*A).value(), Offset));
229}
230
231/// Returns a representation of the alignment that encodes undefined as 0.
232inline unsigned encode(MaybeAlign A) { return A ? A->ShiftValue + 1 : 0; }
233
234/// Dual operation of the encode function above.
235inline MaybeAlign decodeMaybeAlign(unsigned Value) {
236 if (Value == 0)
237 return MaybeAlign();
238 Align Out;
239 Out.ShiftValue = Value - 1;
240 return Out;
241}
242
243/// Returns a representation of the alignment, the encoded value is positive by
244/// definition.
245inline unsigned encode(Align A) { return encode(MaybeAlign(A)); }
246
247/// Comparisons between Align and scalars. Rhs must be positive.
248inline bool operator==(Align Lhs, uint64_t Rhs) {
249 ALIGN_CHECK_ISPOSITIVE(Rhs);
250 return Lhs.value() == Rhs;
251}
252inline bool operator!=(Align Lhs, uint64_t Rhs) {
253 ALIGN_CHECK_ISPOSITIVE(Rhs);
254 return Lhs.value() != Rhs;
255}
256inline bool operator<=(Align Lhs, uint64_t Rhs) {
257 ALIGN_CHECK_ISPOSITIVE(Rhs);
258 return Lhs.value() <= Rhs;
259}
260inline bool operator>=(Align Lhs, uint64_t Rhs) {
261 ALIGN_CHECK_ISPOSITIVE(Rhs);
262 return Lhs.value() >= Rhs;
263}
264inline bool operator<(Align Lhs, uint64_t Rhs) {
265 ALIGN_CHECK_ISPOSITIVE(Rhs);
266 return Lhs.value() < Rhs;
267}
268inline bool operator>(Align Lhs, uint64_t Rhs) {
269 ALIGN_CHECK_ISPOSITIVE(Rhs);
270 return Lhs.value() > Rhs;
271}
272
273/// Comparisons between MaybeAlign and scalars.
274inline bool operator==(MaybeAlign Lhs, uint64_t Rhs) {
275 return Lhs ? (*Lhs).value() == Rhs : Rhs == 0;
276}
277inline bool operator!=(MaybeAlign Lhs, uint64_t Rhs) {
278 return Lhs ? (*Lhs).value() != Rhs : Rhs != 0;
279}
280
281/// Comparisons operators between Align.
282inline bool operator==(Align Lhs, Align Rhs) {
283 return Lhs.ShiftValue == Rhs.ShiftValue;
284}
285inline bool operator!=(Align Lhs, Align Rhs) {
286 return Lhs.ShiftValue != Rhs.ShiftValue;
287}
288inline bool operator<=(Align Lhs, Align Rhs) {
289 return Lhs.ShiftValue <= Rhs.ShiftValue;
290}
291inline bool operator>=(Align Lhs, Align Rhs) {
292 return Lhs.ShiftValue >= Rhs.ShiftValue;
293}
294inline bool operator<(Align Lhs, Align Rhs) {
295 return Lhs.ShiftValue < Rhs.ShiftValue;
296}
297inline bool operator>(Align Lhs, Align Rhs) {
298 return Lhs.ShiftValue > Rhs.ShiftValue;
299}
300
301// Don't allow relational comparisons with MaybeAlign.
302bool operator<=(Align Lhs, MaybeAlign Rhs) = delete;
303bool operator>=(Align Lhs, MaybeAlign Rhs) = delete;
304bool operator<(Align Lhs, MaybeAlign Rhs) = delete;
305bool operator>(Align Lhs, MaybeAlign Rhs) = delete;
306
307bool operator<=(MaybeAlign Lhs, Align Rhs) = delete;
308bool operator>=(MaybeAlign Lhs, Align Rhs) = delete;
309bool operator<(MaybeAlign Lhs, Align Rhs) = delete;
310bool operator>(MaybeAlign Lhs, Align Rhs) = delete;
311
312bool operator<=(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
313bool operator>=(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
314bool operator<(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
315bool operator>(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
316
317inline Align operator*(Align Lhs, uint64_t Rhs) {
318 assert(Rhs > 0 && "Rhs must be positive")((void)0);
319 return Align(Lhs.value() * Rhs);
320}
321
322inline MaybeAlign operator*(MaybeAlign Lhs, uint64_t Rhs) {
323 assert(Rhs > 0 && "Rhs must be positive")((void)0);
324 return Lhs ? Lhs.getValue() * Rhs : MaybeAlign();
325}
326
327inline Align operator/(Align Lhs, uint64_t Divisor) {
328 assert(llvm::isPowerOf2_64(Divisor) &&((void)0)
329 "Divisor must be positive and a power of 2")((void)0);
330 assert(Lhs != 1 && "Can't halve byte alignment")((void)0);
331 return Align(Lhs.value() / Divisor);
332}
333
334inline MaybeAlign operator/(MaybeAlign Lhs, uint64_t Divisor) {
335 assert(llvm::isPowerOf2_64(Divisor) &&((void)0)
336 "Divisor must be positive and a power of 2")((void)0);
337 return Lhs ? Lhs.getValue() / Divisor : MaybeAlign();
338}
339
340inline Align max(MaybeAlign Lhs, Align Rhs) {
341 return Lhs && *Lhs > Rhs ? *Lhs : Rhs;
342}
343
344inline Align max(Align Lhs, MaybeAlign Rhs) {
345 return Rhs && *Rhs > Lhs ? *Rhs : Lhs;
346}
347
348#ifndef NDEBUG1
349// For usage in LLVM_DEBUG macros.
350inline std::string DebugStr(const Align &A) {
351 return std::to_string(A.value());
352}
353// For usage in LLVM_DEBUG macros.
354inline std::string DebugStr(const MaybeAlign &MA) {
355 if (MA)
356 return std::to_string(MA->value());
357 return "None";
358}
359#endif // NDEBUG
360
361#undef ALIGN_CHECK_ISPOSITIVE
362
363} // namespace llvm
364
365#endif // LLVM_SUPPORT_ALIGNMENT_H_

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/MathExtras.h

1//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains some functions that are useful for math stuff.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_MATHEXTRAS_H
14#define LLVM_SUPPORT_MATHEXTRAS_H
15
16#include "llvm/Support/Compiler.h"
17#include <cassert>
18#include <climits>
19#include <cmath>
20#include <cstdint>
21#include <cstring>
22#include <limits>
23#include <type_traits>
24
25#ifdef __ANDROID_NDK__
26#include <android/api-level.h>
27#endif
28
29#ifdef _MSC_VER
30// Declare these intrinsics manually rather including intrin.h. It's very
31// expensive, and MathExtras.h is popular.
32// #include <intrin.h>
33extern "C" {
34unsigned char _BitScanForward(unsigned long *_Index, unsigned long _Mask);
35unsigned char _BitScanForward64(unsigned long *_Index, unsigned __int64 _Mask);
36unsigned char _BitScanReverse(unsigned long *_Index, unsigned long _Mask);
37unsigned char _BitScanReverse64(unsigned long *_Index, unsigned __int64 _Mask);
38}
39#endif
40
41namespace llvm {
42
43/// The behavior an operation has on an input of 0.
44enum ZeroBehavior {
45 /// The returned value is undefined.
46 ZB_Undefined,
47 /// The returned value is numeric_limits<T>::max()
48 ZB_Max,
49 /// The returned value is numeric_limits<T>::digits
50 ZB_Width
51};
52
53/// Mathematical constants.
54namespace numbers {
55// TODO: Track C++20 std::numbers.
56// TODO: Favor using the hexadecimal FP constants (requires C++17).
57constexpr double e = 2.7182818284590452354, // (0x1.5bf0a8b145749P+1) https://oeis.org/A001113
58 egamma = .57721566490153286061, // (0x1.2788cfc6fb619P-1) https://oeis.org/A001620
59 ln2 = .69314718055994530942, // (0x1.62e42fefa39efP-1) https://oeis.org/A002162
60 ln10 = 2.3025850929940456840, // (0x1.24bb1bbb55516P+1) https://oeis.org/A002392
61 log2e = 1.4426950408889634074, // (0x1.71547652b82feP+0)
62 log10e = .43429448190325182765, // (0x1.bcb7b1526e50eP-2)
63 pi = 3.1415926535897932385, // (0x1.921fb54442d18P+1) https://oeis.org/A000796
64 inv_pi = .31830988618379067154, // (0x1.45f306bc9c883P-2) https://oeis.org/A049541
65 sqrtpi = 1.7724538509055160273, // (0x1.c5bf891b4ef6bP+0) https://oeis.org/A002161
66 inv_sqrtpi = .56418958354775628695, // (0x1.20dd750429b6dP-1) https://oeis.org/A087197
67 sqrt2 = 1.4142135623730950488, // (0x1.6a09e667f3bcdP+0) https://oeis.org/A00219
68 inv_sqrt2 = .70710678118654752440, // (0x1.6a09e667f3bcdP-1)
69 sqrt3 = 1.7320508075688772935, // (0x1.bb67ae8584caaP+0) https://oeis.org/A002194
70 inv_sqrt3 = .57735026918962576451, // (0x1.279a74590331cP-1)
71 phi = 1.6180339887498948482; // (0x1.9e3779b97f4a8P+0) https://oeis.org/A001622
72constexpr float ef = 2.71828183F, // (0x1.5bf0a8P+1) https://oeis.org/A001113
73 egammaf = .577215665F, // (0x1.2788d0P-1) https://oeis.org/A001620
74 ln2f = .693147181F, // (0x1.62e430P-1) https://oeis.org/A002162
75 ln10f = 2.30258509F, // (0x1.26bb1cP+1) https://oeis.org/A002392
76 log2ef = 1.44269504F, // (0x1.715476P+0)
77 log10ef = .434294482F, // (0x1.bcb7b2P-2)
78 pif = 3.14159265F, // (0x1.921fb6P+1) https://oeis.org/A000796
79 inv_pif = .318309886F, // (0x1.45f306P-2) https://oeis.org/A049541
80 sqrtpif = 1.77245385F, // (0x1.c5bf8aP+0) https://oeis.org/A002161
81 inv_sqrtpif = .564189584F, // (0x1.20dd76P-1) https://oeis.org/A087197
82 sqrt2f = 1.41421356F, // (0x1.6a09e6P+0) https://oeis.org/A002193
83 inv_sqrt2f = .707106781F, // (0x1.6a09e6P-1)
84 sqrt3f = 1.73205081F, // (0x1.bb67aeP+0) https://oeis.org/A002194
85 inv_sqrt3f = .577350269F, // (0x1.279a74P-1)
86 phif = 1.61803399F; // (0x1.9e377aP+0) https://oeis.org/A001622
87} // namespace numbers
88
89namespace detail {
90template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
91 static unsigned count(T Val, ZeroBehavior) {
92 if (!Val)
93 return std::numeric_limits<T>::digits;
94 if (Val & 0x1)
95 return 0;
96
97 // Bisection method.
98 unsigned ZeroBits = 0;
99 T Shift = std::numeric_limits<T>::digits >> 1;
100 T Mask = std::numeric_limits<T>::max() >> Shift;
101 while (Shift) {
102 if ((Val & Mask) == 0) {
103 Val >>= Shift;
104 ZeroBits |= Shift;
105 }
106 Shift >>= 1;
107 Mask >>= Shift;
108 }
109 return ZeroBits;
110 }
111};
112
113#if defined(__GNUC__4) || defined(_MSC_VER)
114template <typename T> struct TrailingZerosCounter<T, 4> {
115 static unsigned count(T Val, ZeroBehavior ZB) {
116 if (ZB != ZB_Undefined && Val == 0)
117 return 32;
118
119#if __has_builtin(__builtin_ctz)1 || defined(__GNUC__4)
120 return __builtin_ctz(Val);
121#elif defined(_MSC_VER)
122 unsigned long Index;
123 _BitScanForward(&Index, Val);
124 return Index;
125#endif
126 }
127};
128
129#if !defined(_MSC_VER) || defined(_M_X64)
130template <typename T> struct TrailingZerosCounter<T, 8> {
131 static unsigned count(T Val, ZeroBehavior ZB) {
132 if (ZB != ZB_Undefined && Val == 0)
133 return 64;
134
135#if __has_builtin(__builtin_ctzll)1 || defined(__GNUC__4)
136 return __builtin_ctzll(Val);
137#elif defined(_MSC_VER)
138 unsigned long Index;
139 _BitScanForward64(&Index, Val);
140 return Index;
141#endif
142 }
143};
144#endif
145#endif
146} // namespace detail
147
148/// Count number of 0's from the least significant bit to the most
149/// stopping at the first 1.
150///
151/// Only unsigned integral types are allowed.
152///
153/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
154/// valid arguments.
155template <typename T>
156unsigned countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
157 static_assert(std::numeric_limits<T>::is_integer &&
158 !std::numeric_limits<T>::is_signed,
159 "Only unsigned integral types are allowed.");
160 return llvm::detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
161}
162
163namespace detail {
164template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
165 static unsigned count(T Val, ZeroBehavior) {
166 if (!Val)
167 return std::numeric_limits<T>::digits;
168
169 // Bisection method.
170 unsigned ZeroBits = 0;
171 for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
172 T Tmp = Val >> Shift;
173 if (Tmp)
174 Val = Tmp;
175 else
176 ZeroBits |= Shift;
177 }
178 return ZeroBits;
179 }
180};
181
182#if defined(__GNUC__4) || defined(_MSC_VER)
183template <typename T> struct LeadingZerosCounter<T, 4> {
184 static unsigned count(T Val, ZeroBehavior ZB) {
185 if (ZB != ZB_Undefined && Val == 0)
186 return 32;
187
188#if __has_builtin(__builtin_clz)1 || defined(__GNUC__4)
189 return __builtin_clz(Val);
190#elif defined(_MSC_VER)
191 unsigned long Index;
192 _BitScanReverse(&Index, Val);
193 return Index ^ 31;
194#endif
195 }
196};
197
198#if !defined(_MSC_VER) || defined(_M_X64)
199template <typename T> struct LeadingZerosCounter<T, 8> {
200 static unsigned count(T Val, ZeroBehavior ZB) {
201 if (ZB != ZB_Undefined && Val == 0)
202 return 64;
203
204#if __has_builtin(__builtin_clzll)1 || defined(__GNUC__4)
205 return __builtin_clzll(Val);
206#elif defined(_MSC_VER)
207 unsigned long Index;
208 _BitScanReverse64(&Index, Val);
209 return Index ^ 63;
210#endif
211 }
212};
213#endif
214#endif
215} // namespace detail
216
217/// Count number of 0's from the most significant bit to the least
218/// stopping at the first 1.
219///
220/// Only unsigned integral types are allowed.
221///
222/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
223/// valid arguments.
224template <typename T>
225unsigned countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
226 static_assert(std::numeric_limits<T>::is_integer &&
227 !std::numeric_limits<T>::is_signed,
228 "Only unsigned integral types are allowed.");
229 return llvm::detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
230}
231
232/// Get the index of the first set bit starting from the least
233/// significant bit.
234///
235/// Only unsigned integral types are allowed.
236///
237/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
238/// valid arguments.
239template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
240 if (ZB == ZB_Max && Val == 0)
241 return std::numeric_limits<T>::max();
242
243 return countTrailingZeros(Val, ZB_Undefined);
244}
245
246/// Create a bitmask with the N right-most bits set to 1, and all other
247/// bits set to 0. Only unsigned types are allowed.
248template <typename T> T maskTrailingOnes(unsigned N) {
249 static_assert(std::is_unsigned<T>::value, "Invalid type!");
250 const unsigned Bits = CHAR_BIT8 * sizeof(T);
251 assert(N <= Bits && "Invalid bit index")((void)0);
252 return N == 0 ? 0 : (T(-1) >> (Bits - N));
253}
254
255/// Create a bitmask with the N left-most bits set to 1, and all other
256/// bits set to 0. Only unsigned types are allowed.
257template <typename T> T maskLeadingOnes(unsigned N) {
258 return ~maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
259}
260
261/// Create a bitmask with the N right-most bits set to 0, and all other
262/// bits set to 1. Only unsigned types are allowed.
263template <typename T> T maskTrailingZeros(unsigned N) {
264 return maskLeadingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
265}
266
267/// Create a bitmask with the N left-most bits set to 0, and all other
268/// bits set to 1. Only unsigned types are allowed.
269template <typename T> T maskLeadingZeros(unsigned N) {
270 return maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
271}
272
273/// Get the index of the last set bit starting from the least
274/// significant bit.
275///
276/// Only unsigned integral types are allowed.
277///
278/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
279/// valid arguments.
280template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
281 if (ZB == ZB_Max && Val == 0)
282 return std::numeric_limits<T>::max();
283
284 // Use ^ instead of - because both gcc and llvm can remove the associated ^
285 // in the __builtin_clz intrinsic on x86.
286 return countLeadingZeros(Val, ZB_Undefined) ^
287 (std::numeric_limits<T>::digits - 1);
288}
289
290/// Macro compressed bit reversal table for 256 bits.
291///
292/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
293static const unsigned char BitReverseTable256[256] = {
294#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
295#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
296#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
297 R6(0), R6(2), R6(1), R6(3)
298#undef R2
299#undef R4
300#undef R6
301};
302
303/// Reverse the bits in \p Val.
304template <typename T>
305T reverseBits(T Val) {
306 unsigned char in[sizeof(Val)];
307 unsigned char out[sizeof(Val)];
308 std::memcpy(in, &Val, sizeof(Val));
309 for (unsigned i = 0; i < sizeof(Val); ++i)
310 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
311 std::memcpy(&Val, out, sizeof(Val));
312 return Val;
313}
314
315#if __has_builtin(__builtin_bitreverse8)1
316template<>
317inline uint8_t reverseBits<uint8_t>(uint8_t Val) {
318 return __builtin_bitreverse8(Val);
319}
320#endif
321
322#if __has_builtin(__builtin_bitreverse16)1
323template<>
324inline uint16_t reverseBits<uint16_t>(uint16_t Val) {
325 return __builtin_bitreverse16(Val);
326}
327#endif
328
329#if __has_builtin(__builtin_bitreverse32)1
330template<>
331inline uint32_t reverseBits<uint32_t>(uint32_t Val) {
332 return __builtin_bitreverse32(Val);
333}
334#endif
335
336#if __has_builtin(__builtin_bitreverse64)1
337template<>
338inline uint64_t reverseBits<uint64_t>(uint64_t Val) {
339 return __builtin_bitreverse64(Val);
340}
341#endif
342
343// NOTE: The following support functions use the _32/_64 extensions instead of
344// type overloading so that signed and unsigned integers can be used without
345// ambiguity.
346
347/// Return the high 32 bits of a 64 bit value.
348constexpr inline uint32_t Hi_32(uint64_t Value) {
349 return static_cast<uint32_t>(Value >> 32);
350}
351
352/// Return the low 32 bits of a 64 bit value.
353constexpr inline uint32_t Lo_32(uint64_t Value) {
354 return static_cast<uint32_t>(Value);
355}
356
357/// Make a 64-bit integer from a high / low pair of 32-bit integers.
358constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
359 return ((uint64_t)High << 32) | (uint64_t)Low;
360}
361
362/// Checks if an integer fits into the given bit width.
363template <unsigned N> constexpr inline bool isInt(int64_t x) {
364 return N >= 64 || (-(INT64_C(1)1LL<<(N-1)) <= x && x < (INT64_C(1)1LL<<(N-1)));
365}
366// Template specializations to get better code for common cases.
367template <> constexpr inline bool isInt<8>(int64_t x) {
368 return static_cast<int8_t>(x) == x;
369}
370template <> constexpr inline bool isInt<16>(int64_t x) {
371 return static_cast<int16_t>(x) == x;
372}
373template <> constexpr inline bool isInt<32>(int64_t x) {
374 return static_cast<int32_t>(x) == x;
375}
376
377/// Checks if a signed integer is an N bit number shifted left by S.
378template <unsigned N, unsigned S>
379constexpr inline bool isShiftedInt(int64_t x) {
380 static_assert(
381 N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
382 static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
383 return isInt<N + S>(x) && (x % (UINT64_C(1)1ULL << S) == 0);
384}
385
386/// Checks if an unsigned integer fits into the given bit width.
387///
388/// This is written as two functions rather than as simply
389///
390/// return N >= 64 || X < (UINT64_C(1) << N);
391///
392/// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting
393/// left too many places.
394template <unsigned N>
395constexpr inline std::enable_if_t<(N < 64), bool> isUInt(uint64_t X) {
396 static_assert(N > 0, "isUInt<0> doesn't make sense");
397 return X < (UINT64_C(1)1ULL << (N));
398}
399template <unsigned N>
400constexpr inline std::enable_if_t<N >= 64, bool> isUInt(uint64_t) {
401 return true;
402}
403
404// Template specializations to get better code for common cases.
405template <> constexpr inline bool isUInt<8>(uint64_t x) {
406 return static_cast<uint8_t>(x) == x;
407}
408template <> constexpr inline bool isUInt<16>(uint64_t x) {
409 return static_cast<uint16_t>(x) == x;
410}
411template <> constexpr inline bool isUInt<32>(uint64_t x) {
412 return static_cast<uint32_t>(x) == x;
413}
414
415/// Checks if a unsigned integer is an N bit number shifted left by S.
416template <unsigned N, unsigned S>
417constexpr inline bool isShiftedUInt(uint64_t x) {
418 static_assert(
419 N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
420 static_assert(N + S <= 64,
421 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
422 // Per the two static_asserts above, S must be strictly less than 64. So
423 // 1 << S is not undefined behavior.
424 return isUInt<N + S>(x) && (x % (UINT64_C(1)1ULL << S) == 0);
425}
426
427/// Gets the maximum value for a N-bit unsigned integer.
428inline uint64_t maxUIntN(uint64_t N) {
429 assert(N > 0 && N <= 64 && "integer width out of range")((void)0);
430
431 // uint64_t(1) << 64 is undefined behavior, so we can't do
432 // (uint64_t(1) << N) - 1
433 // without checking first that N != 64. But this works and doesn't have a
434 // branch.
435 return UINT64_MAX0xffffffffffffffffULL >> (64 - N);
436}
437
438/// Gets the minimum value for a N-bit signed integer.
439inline int64_t minIntN(int64_t N) {
440 assert(N > 0 && N <= 64 && "integer width out of range")((void)0);
441
442 return UINT64_C(1)1ULL + ~(UINT64_C(1)1ULL << (N - 1));
443}
444
445/// Gets the maximum value for a N-bit signed integer.
446inline int64_t maxIntN(int64_t N) {
447 assert(N > 0 && N <= 64 && "integer width out of range")((void)0);
448
449 // This relies on two's complement wraparound when N == 64, so we convert to
450 // int64_t only at the very end to avoid UB.
451 return (UINT64_C(1)1ULL << (N - 1)) - 1;
452}
453
454/// Checks if an unsigned integer fits into the given (dynamic) bit width.
455inline bool isUIntN(unsigned N, uint64_t x) {
456 return N >= 64 || x <= maxUIntN(N);
457}
458
459/// Checks if an signed integer fits into the given (dynamic) bit width.
460inline bool isIntN(unsigned N, int64_t x) {
461 return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
462}
463
464/// Return true if the argument is a non-empty sequence of ones starting at the
465/// least significant bit with the remainder zero (32 bit version).
466/// Ex. isMask_32(0x0000FFFFU) == true.
467constexpr inline bool isMask_32(uint32_t Value) {
468 return Value && ((Value + 1) & Value) == 0;
469}
470
471/// Return true if the argument is a non-empty sequence of ones starting at the
472/// least significant bit with the remainder zero (64 bit version).
473constexpr inline bool isMask_64(uint64_t Value) {
474 return Value && ((Value + 1) & Value) == 0;
475}
476
477/// Return true if the argument contains a non-empty sequence of ones with the
478/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
479constexpr inline bool isShiftedMask_32(uint32_t Value) {
480 return Value && isMask_32((Value - 1) | Value);
481}
482
483/// Return true if the argument contains a non-empty sequence of ones with the
484/// remainder zero (64 bit version.)
485constexpr inline bool isShiftedMask_64(uint64_t Value) {
486 return Value && isMask_64((Value - 1) | Value);
487}
488
489/// Return true if the argument is a power of two > 0.
490/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
491constexpr inline bool isPowerOf2_32(uint32_t Value) {
492 return Value && !(Value & (Value - 1));
493}
494
495/// Return true if the argument is a power of two > 0 (64 bit edition.)
496constexpr inline bool isPowerOf2_64(uint64_t Value) {
497 return Value && !(Value & (Value - 1));
498}
499
500/// Count the number of ones from the most significant bit to the first
501/// zero bit.
502///
503/// Ex. countLeadingOnes(0xFF0FFF00) == 8.
504/// Only unsigned integral types are allowed.
505///
506/// \param ZB the behavior on an input of all ones. Only ZB_Width and
507/// ZB_Undefined are valid arguments.
508template <typename T>
509unsigned countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
510 static_assert(std::numeric_limits<T>::is_integer &&
511 !std::numeric_limits<T>::is_signed,
512 "Only unsigned integral types are allowed.");
513 return countLeadingZeros<T>(~Value, ZB);
514}
515
516/// Count the number of ones from the least significant bit to the first
517/// zero bit.
518///
519/// Ex. countTrailingOnes(0x00FF00FF) == 8.
520/// Only unsigned integral types are allowed.
521///
522/// \param ZB the behavior on an input of all ones. Only ZB_Width and
523/// ZB_Undefined are valid arguments.
524template <typename T>
525unsigned countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
526 static_assert(std::numeric_limits<T>::is_integer &&
527 !std::numeric_limits<T>::is_signed,
528 "Only unsigned integral types are allowed.");
529 return countTrailingZeros<T>(~Value, ZB);
530}
531
532namespace detail {
533template <typename T, std::size_t SizeOfT> struct PopulationCounter {
534 static unsigned count(T Value) {
535 // Generic version, forward to 32 bits.
536 static_assert(SizeOfT <= 4, "Not implemented!");
537#if defined(__GNUC__4)
538 return __builtin_popcount(Value);
539#else
540 uint32_t v = Value;
541 v = v - ((v >> 1) & 0x55555555);
542 v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
543 return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
544#endif
545 }
546};
547
548template <typename T> struct PopulationCounter<T, 8> {
549 static unsigned count(T Value) {
550#if defined(__GNUC__4)
551 return __builtin_popcountll(Value);
552#else
553 uint64_t v = Value;
554 v = v - ((v >> 1) & 0x5555555555555555ULL);
555 v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
556 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
557 return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
558#endif
559 }
560};
561} // namespace detail
562
563/// Count the number of set bits in a value.
564/// Ex. countPopulation(0xF000F000) = 8
565/// Returns 0 if the word is zero.
566template <typename T>
567inline unsigned countPopulation(T Value) {
568 static_assert(std::numeric_limits<T>::is_integer &&
569 !std::numeric_limits<T>::is_signed,
570 "Only unsigned integral types are allowed.");
571 return detail::PopulationCounter<T, sizeof(T)>::count(Value);
572}
573
574/// Compile time Log2.
575/// Valid only for positive powers of two.
576template <size_t kValue> constexpr inline size_t CTLog2() {
577 static_assert(kValue > 0 && llvm::isPowerOf2_64(kValue),
578 "Value is not a valid power of 2");
579 return 1 + CTLog2<kValue / 2>();
580}
581
582template <> constexpr inline size_t CTLog2<1>() { return 0; }
583
584/// Return the log base 2 of the specified value.
585inline double Log2(double Value) {
586#if defined(__ANDROID_API__) && __ANDROID_API__ < 18
587 return __builtin_log(Value) / __builtin_log(2.0);
588#else
589 return log2(Value);
590#endif
591}
592
593/// Return the floor log base 2 of the specified value, -1 if the value is zero.
594/// (32 bit edition.)
595/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
596inline unsigned Log2_32(uint32_t Value) {
597 return 31 - countLeadingZeros(Value);
598}
599
600/// Return the floor log base 2 of the specified value, -1 if the value is zero.
601/// (64 bit edition.)
602inline unsigned Log2_64(uint64_t Value) {
603 return 63 - countLeadingZeros(Value);
8
Returning the value 4294967295
604}
605
606/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
607/// (32 bit edition).
608/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
609inline unsigned Log2_32_Ceil(uint32_t Value) {
610 return 32 - countLeadingZeros(Value - 1);
611}
612
613/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
614/// (64 bit edition.)
615inline unsigned Log2_64_Ceil(uint64_t Value) {
616 return 64 - countLeadingZeros(Value - 1);
617}
618
619/// Return the greatest common divisor of the values using Euclid's algorithm.
620template <typename T>
621inline T greatestCommonDivisor(T A, T B) {
622 while (B) {
623 T Tmp = B;
624 B = A % B;
625 A = Tmp;
626 }
627 return A;
628}
629
630inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
631 return greatestCommonDivisor<uint64_t>(A, B);
632}
633
634/// This function takes a 64-bit integer and returns the bit equivalent double.
635inline double BitsToDouble(uint64_t Bits) {
636 double D;
637 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
638 memcpy(&D, &Bits, sizeof(Bits));
639 return D;
640}
641
642/// This function takes a 32-bit integer and returns the bit equivalent float.
643inline float BitsToFloat(uint32_t Bits) {
644 float F;
645 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
646 memcpy(&F, &Bits, sizeof(Bits));
647 return F;
648}
649
650/// This function takes a double and returns the bit equivalent 64-bit integer.
651/// Note that copying doubles around changes the bits of NaNs on some hosts,
652/// notably x86, so this routine cannot be used if these bits are needed.
653inline uint64_t DoubleToBits(double Double) {
654 uint64_t Bits;
655 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
656 memcpy(&Bits, &Double, sizeof(Double));
657 return Bits;
658}
659
660/// This function takes a float and returns the bit equivalent 32-bit integer.
661/// Note that copying floats around changes the bits of NaNs on some hosts,
662/// notably x86, so this routine cannot be used if these bits are needed.
663inline uint32_t FloatToBits(float Float) {
664 uint32_t Bits;
665 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
666 memcpy(&Bits, &Float, sizeof(Float));
667 return Bits;
668}
669
670/// A and B are either alignments or offsets. Return the minimum alignment that
671/// may be assumed after adding the two together.
672constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
673 // The largest power of 2 that divides both A and B.
674 //
675 // Replace "-Value" by "1+~Value" in the following commented code to avoid
676 // MSVC warning C4146
677 // return (A | B) & -(A | B);
678 return (A | B) & (1 + ~(A | B));
679}
680
681/// Returns the next power of two (in 64-bits) that is strictly greater than A.
682/// Returns zero on overflow.
683inline uint64_t NextPowerOf2(uint64_t A) {
684 A |= (A >> 1);
685 A |= (A >> 2);
686 A |= (A >> 4);
687 A |= (A >> 8);
688 A |= (A >> 16);
689 A |= (A >> 32);
690 return A + 1;
691}
692
693/// Returns the power of two which is less than or equal to the given value.
694/// Essentially, it is a floor operation across the domain of powers of two.
695inline uint64_t PowerOf2Floor(uint64_t A) {
696 if (!A) return 0;
697 return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
698}
699
700/// Returns the power of two which is greater than or equal to the given value.
701/// Essentially, it is a ceil operation across the domain of powers of two.
702inline uint64_t PowerOf2Ceil(uint64_t A) {
703 if (!A)
704 return 0;
705 return NextPowerOf2(A - 1);
706}
707
708/// Returns the next integer (mod 2**64) that is greater than or equal to
709/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
710///
711/// If non-zero \p Skew is specified, the return value will be a minimal
712/// integer that is greater than or equal to \p Value and equal to
713/// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
714/// \p Align, its value is adjusted to '\p Skew mod \p Align'.
715///
716/// Examples:
717/// \code
718/// alignTo(5, 8) = 8
719/// alignTo(17, 8) = 24
720/// alignTo(~0LL, 8) = 0
721/// alignTo(321, 255) = 510
722///
723/// alignTo(5, 8, 7) = 7
724/// alignTo(17, 8, 1) = 17
725/// alignTo(~0LL, 8, 3) = 3
726/// alignTo(321, 255, 42) = 552
727/// \endcode
728inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
729 assert(Align != 0u && "Align can't be 0.")((void)0);
730 Skew %= Align;
731 return (Value + Align - 1 - Skew) / Align * Align + Skew;
732}
733
734/// Returns the next integer (mod 2**64) that is greater than or equal to
735/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
736template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
737 static_assert(Align != 0u, "Align must be non-zero");
738 return (Value + Align - 1) / Align * Align;
739}
740
741/// Returns the integer ceil(Numerator / Denominator).
742inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
743 return alignTo(Numerator, Denominator) / Denominator;
744}
745
746/// Returns the integer nearest(Numerator / Denominator).
747inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
748 return (Numerator + (Denominator / 2)) / Denominator;
749}
750
751/// Returns the largest uint64_t less than or equal to \p Value and is
752/// \p Skew mod \p Align. \p Align must be non-zero
753inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
754 assert(Align != 0u && "Align can't be 0.")((void)0);
755 Skew %= Align;
756 return (Value - Skew) / Align * Align + Skew;
757}
758
759/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
760/// Requires 0 < B <= 32.
761template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
762 static_assert(B > 0, "Bit width can't be 0.");
763 static_assert(B <= 32, "Bit width out of range.");
764 return int32_t(X << (32 - B)) >> (32 - B);
765}
766
767/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
768/// Requires 0 < B <= 32.
769inline int32_t SignExtend32(uint32_t X, unsigned B) {
770 assert(B > 0 && "Bit width can't be 0.")((void)0);
771 assert(B <= 32 && "Bit width out of range.")((void)0);
772 return int32_t(X << (32 - B)) >> (32 - B);
773}
774
775/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
776/// Requires 0 < B <= 64.
777template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
778 static_assert(B > 0, "Bit width can't be 0.");
779 static_assert(B <= 64, "Bit width out of range.");
780 return int64_t(x << (64 - B)) >> (64 - B);
781}
782
783/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
784/// Requires 0 < B <= 64.
785inline int64_t SignExtend64(uint64_t X, unsigned B) {
786 assert(B > 0 && "Bit width can't be 0.")((void)0);
787 assert(B <= 64 && "Bit width out of range.")((void)0);
788 return int64_t(X << (64 - B)) >> (64 - B);
789}
790
791/// Subtract two unsigned integers, X and Y, of type T and return the absolute
792/// value of the result.
793template <typename T>
794std::enable_if_t<std::is_unsigned<T>::value, T> AbsoluteDifference(T X, T Y) {
795 return X > Y ? (X - Y) : (Y - X);
796}
797
798/// Add two unsigned integers, X and Y, of type T. Clamp the result to the
799/// maximum representable value of T on overflow. ResultOverflowed indicates if
800/// the result is larger than the maximum representable value of type T.
801template <typename T>
802std::enable_if_t<std::is_unsigned<T>::value, T>
803SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
804 bool Dummy;
805 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
806 // Hacker's Delight, p. 29
807 T Z = X + Y;
808 Overflowed = (Z < X || Z < Y);
809 if (Overflowed)
810 return std::numeric_limits<T>::max();
811 else
812 return Z;
813}
814
815/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
816/// maximum representable value of T on overflow. ResultOverflowed indicates if
817/// the result is larger than the maximum representable value of type T.
818template <typename T>
819std::enable_if_t<std::is_unsigned<T>::value, T>
820SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
821 bool Dummy;
822 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
823
824 // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
825 // because it fails for uint16_t (where multiplication can have undefined
826 // behavior due to promotion to int), and requires a division in addition
827 // to the multiplication.
828
829 Overflowed = false;
830
831 // Log2(Z) would be either Log2Z or Log2Z + 1.
832 // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
833 // will necessarily be less than Log2Max as desired.
834 int Log2Z = Log2_64(X) + Log2_64(Y);
835 const T Max = std::numeric_limits<T>::max();
836 int Log2Max = Log2_64(Max);
837 if (Log2Z < Log2Max) {
838 return X * Y;
839 }
840 if (Log2Z > Log2Max) {
841 Overflowed = true;
842 return Max;
843 }
844
845 // We're going to use the top bit, and maybe overflow one
846 // bit past it. Multiply all but the bottom bit then add
847 // that on at the end.
848 T Z = (X >> 1) * Y;
849 if (Z & ~(Max >> 1)) {
850 Overflowed = true;
851 return Max;
852 }
853 Z <<= 1;
854 if (X & 1)
855 return SaturatingAdd(Z, Y, ResultOverflowed);
856
857 return Z;
858}
859
860/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
861/// the product. Clamp the result to the maximum representable value of T on
862/// overflow. ResultOverflowed indicates if the result is larger than the
863/// maximum representable value of type T.
864template <typename T>
865std::enable_if_t<std::is_unsigned<T>::value, T>
866SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
867 bool Dummy;
868 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
869
870 T Product = SaturatingMultiply(X, Y, &Overflowed);
871 if (Overflowed)
872 return Product;
873
874 return SaturatingAdd(A, Product, &Overflowed);
875}
876
877/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
878extern const float huge_valf;
879
880
881/// Add two signed integers, computing the two's complement truncated result,
882/// returning true if overflow occured.
883template <typename T>
884std::enable_if_t<std::is_signed<T>::value, T> AddOverflow(T X, T Y, T &Result) {
885#if __has_builtin(__builtin_add_overflow)1
886 return __builtin_add_overflow(X, Y, &Result);
887#else
888 // Perform the unsigned addition.
889 using U = std::make_unsigned_t<T>;
890 const U UX = static_cast<U>(X);
891 const U UY = static_cast<U>(Y);
892 const U UResult = UX + UY;
893
894 // Convert to signed.
895 Result = static_cast<T>(UResult);
896
897 // Adding two positive numbers should result in a positive number.
898 if (X > 0 && Y > 0)
899 return Result <= 0;
900 // Adding two negatives should result in a negative number.
901 if (X < 0 && Y < 0)
902 return Result >= 0;
903 return false;
904#endif
905}
906
907/// Subtract two signed integers, computing the two's complement truncated
908/// result, returning true if an overflow ocurred.
909template <typename T>
910std::enable_if_t<std::is_signed<T>::value, T> SubOverflow(T X, T Y, T &Result) {
911#if __has_builtin(__builtin_sub_overflow)1
912 return __builtin_sub_overflow(X, Y, &Result);
913#else
914 // Perform the unsigned addition.
915 using U = std::make_unsigned_t<T>;
916 const U UX = static_cast<U>(X);
917 const U UY = static_cast<U>(Y);
918 const U UResult = UX - UY;
919
920 // Convert to signed.
921 Result = static_cast<T>(UResult);
922
923 // Subtracting a positive number from a negative results in a negative number.
924 if (X <= 0 && Y > 0)
925 return Result >= 0;
926 // Subtracting a negative number from a positive results in a positive number.
927 if (X >= 0 && Y < 0)
928 return Result <= 0;
929 return false;
930#endif
931}
932
933/// Multiply two signed integers, computing the two's complement truncated
934/// result, returning true if an overflow ocurred.
935template <typename T>
936std::enable_if_t<std::is_signed<T>::value, T> MulOverflow(T X, T Y, T &Result) {
937 // Perform the unsigned multiplication on absolute values.
938 using U = std::make_unsigned_t<T>;
939 const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
940 const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
941 const U UResult = UX * UY;
942
943 // Convert to signed.
944 const bool IsNegative = (X < 0) ^ (Y < 0);
945 Result = IsNegative ? (0 - UResult) : UResult;
946
947 // If any of the args was 0, result is 0 and no overflow occurs.
948 if (UX == 0 || UY == 0)
949 return false;
950
951 // UX and UY are in [1, 2^n], where n is the number of digits.
952 // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
953 // positive) divided by an argument compares to the other.
954 if (IsNegative)
955 return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
956 else
957 return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
958}
959
960} // End llvm namespace
961
962#endif