Bug Summary

File:clang/lib/CodeGen/CGCUDANV.cpp
Warning:line 980, column 13
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGCUDANV.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-02-23-121308-24221-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp

/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp

1//===----- CGCUDANV.cpp - Interface to NVIDIA CUDA Runtime ----------------===//
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 provides a class for CUDA code generation targeting the NVIDIA CUDA
10// runtime library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGCUDARuntime.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/Decl.h"
18#include "clang/Basic/Cuda.h"
19#include "clang/CodeGen/CodeGenABITypes.h"
20#include "clang/CodeGen/ConstantInitBuilder.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/ReplaceConstant.h"
25#include "llvm/Support/Format.h"
26
27using namespace clang;
28using namespace CodeGen;
29
30namespace {
31constexpr unsigned CudaFatMagic = 0x466243b1;
32constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"
33
34class CGNVCUDARuntime : public CGCUDARuntime {
35
36private:
37 llvm::IntegerType *IntTy, *SizeTy;
38 llvm::Type *VoidTy;
39 llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
40
41 /// Convenience reference to LLVM Context
42 llvm::LLVMContext &Context;
43 /// Convenience reference to the current module
44 llvm::Module &TheModule;
45 /// Keeps track of kernel launch stubs emitted in this module
46 struct KernelInfo {
47 llvm::Function *Kernel;
48 const Decl *D;
49 };
50 llvm::SmallVector<KernelInfo, 16> EmittedKernels;
51 struct VarInfo {
52 llvm::GlobalVariable *Var;
53 const VarDecl *D;
54 DeviceVarFlags Flags;
55 };
56 llvm::SmallVector<VarInfo, 16> DeviceVars;
57 /// Keeps track of variable containing handle of GPU binary. Populated by
58 /// ModuleCtorFunction() and used to create corresponding cleanup calls in
59 /// ModuleDtorFunction()
60 llvm::GlobalVariable *GpuBinaryHandle = nullptr;
61 /// Whether we generate relocatable device code.
62 bool RelocatableDeviceCode;
63 /// Mangle context for device.
64 std::unique_ptr<MangleContext> DeviceMC;
65
66 llvm::FunctionCallee getSetupArgumentFn() const;
67 llvm::FunctionCallee getLaunchFn() const;
68
69 llvm::FunctionType *getRegisterGlobalsFnTy() const;
70 llvm::FunctionType *getCallbackFnTy() const;
71 llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;
72 std::string addPrefixToName(StringRef FuncName) const;
73 std::string addUnderscoredPrefixToName(StringRef FuncName) const;
74
75 /// Creates a function to register all kernel stubs generated in this module.
76 llvm::Function *makeRegisterGlobalsFn();
77
78 /// Helper function that generates a constant string and returns a pointer to
79 /// the start of the string. The result of this function can be used anywhere
80 /// where the C code specifies const char*.
81 llvm::Constant *makeConstantString(const std::string &Str,
82 const std::string &Name = "",
83 const std::string &SectionName = "",
84 unsigned Alignment = 0) {
85 llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
86 llvm::ConstantInt::get(SizeTy, 0)};
87 auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
88 llvm::GlobalVariable *GV =
89 cast<llvm::GlobalVariable>(ConstStr.getPointer());
90 if (!SectionName.empty()) {
91 GV->setSection(SectionName);
92 // Mark the address as used which make sure that this section isn't
93 // merged and we will really have it in the object file.
94 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
95 }
96 if (Alignment)
97 GV->setAlignment(llvm::Align(Alignment));
98
99 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
100 ConstStr.getPointer(), Zeros);
101 }
102
103 /// Helper function that generates an empty dummy function returning void.
104 llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
105 assert(FnTy->getReturnType()->isVoidTy() &&((FnTy->getReturnType()->isVoidTy() && "Can only generate dummy functions returning void!"
) ? static_cast<void> (0) : __assert_fail ("FnTy->getReturnType()->isVoidTy() && \"Can only generate dummy functions returning void!\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 106, __PRETTY_FUNCTION__))
106 "Can only generate dummy functions returning void!")((FnTy->getReturnType()->isVoidTy() && "Can only generate dummy functions returning void!"
) ? static_cast<void> (0) : __assert_fail ("FnTy->getReturnType()->isVoidTy() && \"Can only generate dummy functions returning void!\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 106, __PRETTY_FUNCTION__))
;
107 llvm::Function *DummyFunc = llvm::Function::Create(
108 FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
109
110 llvm::BasicBlock *DummyBlock =
111 llvm::BasicBlock::Create(Context, "", DummyFunc);
112 CGBuilderTy FuncBuilder(CGM, Context);
113 FuncBuilder.SetInsertPoint(DummyBlock);
114 FuncBuilder.CreateRetVoid();
115
116 return DummyFunc;
117 }
118
119 void emitDeviceStubBodyLegacy(CodeGenFunction &CGF, FunctionArgList &Args);
120 void emitDeviceStubBodyNew(CodeGenFunction &CGF, FunctionArgList &Args);
121 std::string getDeviceSideName(const NamedDecl *ND) override;
122
123 void registerDeviceVar(const VarDecl *VD, llvm::GlobalVariable &Var,
124 bool Extern, bool Constant) {
125 DeviceVars.push_back({&Var,
126 VD,
127 {DeviceVarFlags::Variable, Extern, Constant,
128 VD->hasAttr<HIPManagedAttr>(),
129 /*Normalized*/ false, 0}});
130 }
131 void registerDeviceSurf(const VarDecl *VD, llvm::GlobalVariable &Var,
132 bool Extern, int Type) {
133 DeviceVars.push_back({&Var,
134 VD,
135 {DeviceVarFlags::Surface, Extern, /*Constant*/ false,
136 /*Managed*/ false,
137 /*Normalized*/ false, Type}});
138 }
139 void registerDeviceTex(const VarDecl *VD, llvm::GlobalVariable &Var,
140 bool Extern, int Type, bool Normalized) {
141 DeviceVars.push_back({&Var,
142 VD,
143 {DeviceVarFlags::Texture, Extern, /*Constant*/ false,
144 /*Managed*/ false, Normalized, Type}});
145 }
146
147public:
148 CGNVCUDARuntime(CodeGenModule &CGM);
149
150 void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
151 void handleVarRegistration(const VarDecl *VD,
152 llvm::GlobalVariable &Var) override;
153
154 /// Creates module constructor function
155 llvm::Function *makeModuleCtorFunction() override;
156 /// Creates module destructor function
157 llvm::Function *makeModuleDtorFunction() override;
158 void
159 internalizeDeviceSideVar(const VarDecl *D,
160 llvm::GlobalValue::LinkageTypes &Linkage) override;
161};
162
163}
164
165std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
166 if (CGM.getLangOpts().HIP)
167 return ((Twine("hip") + Twine(FuncName)).str());
168 return ((Twine("cuda") + Twine(FuncName)).str());
169}
170std::string
171CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
172 if (CGM.getLangOpts().HIP)
173 return ((Twine("__hip") + Twine(FuncName)).str());
174 return ((Twine("__cuda") + Twine(FuncName)).str());
175}
176
177CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
178 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
179 TheModule(CGM.getModule()),
180 RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode),
181 DeviceMC(CGM.getContext().createMangleContext(
182 CGM.getContext().getAuxTargetInfo())) {
183 CodeGen::CodeGenTypes &Types = CGM.getTypes();
184 ASTContext &Ctx = CGM.getContext();
185
186 IntTy = CGM.IntTy;
187 SizeTy = CGM.SizeTy;
188 VoidTy = CGM.VoidTy;
189
190 CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy));
191 VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy));
192 VoidPtrPtrTy = VoidPtrTy->getPointerTo();
193 if (CGM.getContext().getAuxTargetInfo()) {
194 // If the host and device have different C++ ABIs, mark it as the device
195 // mangle context so that the mangling needs to retrieve the additonal
196 // device lambda mangling number instead of the regular host one.
197 DeviceMC->setDeviceMangleContext(
198 CGM.getContext().getTargetInfo().getCXXABI().isMicrosoft() &&
199 CGM.getContext().getAuxTargetInfo()->getCXXABI().isItaniumFamily());
200 }
201}
202
203llvm::FunctionCallee CGNVCUDARuntime::getSetupArgumentFn() const {
204 // cudaError_t cudaSetupArgument(void *, size_t, size_t)
205 llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy};
206 return CGM.CreateRuntimeFunction(
207 llvm::FunctionType::get(IntTy, Params, false),
208 addPrefixToName("SetupArgument"));
209}
210
211llvm::FunctionCallee CGNVCUDARuntime::getLaunchFn() const {
212 if (CGM.getLangOpts().HIP) {
213 // hipError_t hipLaunchByPtr(char *);
214 return CGM.CreateRuntimeFunction(
215 llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
216 } else {
217 // cudaError_t cudaLaunch(char *);
218 return CGM.CreateRuntimeFunction(
219 llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
220 }
221}
222
223llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
224 return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false);
225}
226
227llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
228 return llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
229}
230
231llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
232 auto CallbackFnTy = getCallbackFnTy();
233 auto RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
234 llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy,
235 VoidPtrTy, CallbackFnTy->getPointerTo()};
236 return llvm::FunctionType::get(VoidTy, Params, false);
237}
238
239std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) {
240 GlobalDecl GD;
241 // D could be either a kernel or a variable.
242 if (auto *FD = dyn_cast<FunctionDecl>(ND))
243 GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
244 else
245 GD = GlobalDecl(ND);
246 std::string DeviceSideName;
247 if (DeviceMC->shouldMangleDeclName(ND)) {
248 SmallString<256> Buffer;
249 llvm::raw_svector_ostream Out(Buffer);
250 DeviceMC->mangleName(GD, Out);
251 DeviceSideName = std::string(Out.str());
252 } else
253 DeviceSideName = std::string(ND->getIdentifier()->getName());
254 return DeviceSideName;
255}
256
257void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
258 FunctionArgList &Args) {
259 EmittedKernels.push_back({CGF.CurFn, CGF.CurFuncDecl});
260 if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),
261 CudaFeature::CUDA_USES_NEW_LAUNCH) ||
262 (CGF.getLangOpts().HIP && CGF.getLangOpts().HIPUseNewLaunchAPI))
263 emitDeviceStubBodyNew(CGF, Args);
264 else
265 emitDeviceStubBodyLegacy(CGF, Args);
266}
267
268// CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local
269// array and kernels are launched using cudaLaunchKernel().
270void CGNVCUDARuntime::emitDeviceStubBodyNew(CodeGenFunction &CGF,
271 FunctionArgList &Args) {
272 // Build the shadow stack entry at the very start of the function.
273
274 // Calculate amount of space we will need for all arguments. If we have no
275 // args, allocate a single pointer so we still have a valid pointer to the
276 // argument array that we can pass to runtime, even if it will be unused.
277 Address KernelArgs = CGF.CreateTempAlloca(
278 VoidPtrTy, CharUnits::fromQuantity(16), "kernel_args",
279 llvm::ConstantInt::get(SizeTy, std::max<size_t>(1, Args.size())));
280 // Store pointers to the arguments in a locally allocated launch_args.
281 for (unsigned i = 0; i < Args.size(); ++i) {
282 llvm::Value* VarPtr = CGF.GetAddrOfLocalVar(Args[i]).getPointer();
283 llvm::Value *VoidVarPtr = CGF.Builder.CreatePointerCast(VarPtr, VoidPtrTy);
284 CGF.Builder.CreateDefaultAlignedStore(
285 VoidVarPtr, CGF.Builder.CreateConstGEP1_32(KernelArgs.getPointer(), i));
286 }
287
288 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
289
290 // Lookup cudaLaunchKernel/hipLaunchKernel function.
291 // cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
292 // void **args, size_t sharedMem,
293 // cudaStream_t stream);
294 // hipError_t hipLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
295 // void **args, size_t sharedMem,
296 // hipStream_t stream);
297 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
298 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
299 auto LaunchKernelName = addPrefixToName("LaunchKernel");
300 IdentifierInfo &cudaLaunchKernelII =
301 CGM.getContext().Idents.get(LaunchKernelName);
302 FunctionDecl *cudaLaunchKernelFD = nullptr;
303 for (const auto &Result : DC->lookup(&cudaLaunchKernelII)) {
304 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Result))
305 cudaLaunchKernelFD = FD;
306 }
307
308 if (cudaLaunchKernelFD == nullptr) {
309 CGM.Error(CGF.CurFuncDecl->getLocation(),
310 "Can't find declaration for " + LaunchKernelName);
311 return;
312 }
313 // Create temporary dim3 grid_dim, block_dim.
314 ParmVarDecl *GridDimParam = cudaLaunchKernelFD->getParamDecl(1);
315 QualType Dim3Ty = GridDimParam->getType();
316 Address GridDim =
317 CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "grid_dim");
318 Address BlockDim =
319 CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "block_dim");
320 Address ShmemSize =
321 CGF.CreateTempAlloca(SizeTy, CGM.getSizeAlign(), "shmem_size");
322 Address Stream =
323 CGF.CreateTempAlloca(VoidPtrTy, CGM.getPointerAlign(), "stream");
324 llvm::FunctionCallee cudaPopConfigFn = CGM.CreateRuntimeFunction(
325 llvm::FunctionType::get(IntTy,
326 {/*gridDim=*/GridDim.getType(),
327 /*blockDim=*/BlockDim.getType(),
328 /*ShmemSize=*/ShmemSize.getType(),
329 /*Stream=*/Stream.getType()},
330 /*isVarArg=*/false),
331 addUnderscoredPrefixToName("PopCallConfiguration"));
332
333 CGF.EmitRuntimeCallOrInvoke(cudaPopConfigFn,
334 {GridDim.getPointer(), BlockDim.getPointer(),
335 ShmemSize.getPointer(), Stream.getPointer()});
336
337 // Emit the call to cudaLaunch
338 llvm::Value *Kernel = CGF.Builder.CreatePointerCast(CGF.CurFn, VoidPtrTy);
339 CallArgList LaunchKernelArgs;
340 LaunchKernelArgs.add(RValue::get(Kernel),
341 cudaLaunchKernelFD->getParamDecl(0)->getType());
342 LaunchKernelArgs.add(RValue::getAggregate(GridDim), Dim3Ty);
343 LaunchKernelArgs.add(RValue::getAggregate(BlockDim), Dim3Ty);
344 LaunchKernelArgs.add(RValue::get(KernelArgs.getPointer()),
345 cudaLaunchKernelFD->getParamDecl(3)->getType());
346 LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(ShmemSize)),
347 cudaLaunchKernelFD->getParamDecl(4)->getType());
348 LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(Stream)),
349 cudaLaunchKernelFD->getParamDecl(5)->getType());
350
351 QualType QT = cudaLaunchKernelFD->getType();
352 QualType CQT = QT.getCanonicalType();
353 llvm::Type *Ty = CGM.getTypes().ConvertType(CQT);
354 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(Ty);
355
356 const CGFunctionInfo &FI =
357 CGM.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);
358 llvm::FunctionCallee cudaLaunchKernelFn =
359 CGM.CreateRuntimeFunction(FTy, LaunchKernelName);
360 CGF.EmitCall(FI, CGCallee::forDirect(cudaLaunchKernelFn), ReturnValueSlot(),
361 LaunchKernelArgs);
362 CGF.EmitBranch(EndBlock);
363
364 CGF.EmitBlock(EndBlock);
365}
366
367void CGNVCUDARuntime::emitDeviceStubBodyLegacy(CodeGenFunction &CGF,
368 FunctionArgList &Args) {
369 // Emit a call to cudaSetupArgument for each arg in Args.
370 llvm::FunctionCallee cudaSetupArgFn = getSetupArgumentFn();
371 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
372 CharUnits Offset = CharUnits::Zero();
373 for (const VarDecl *A : Args) {
374 auto TInfo = CGM.getContext().getTypeInfoInChars(A->getType());
375 Offset = Offset.alignTo(TInfo.Align);
376 llvm::Value *Args[] = {
377 CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(),
378 VoidPtrTy),
379 llvm::ConstantInt::get(SizeTy, TInfo.Width.getQuantity()),
380 llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
381 };
382 llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
383 llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
384 llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero);
385 llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
386 CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock);
387 CGF.EmitBlock(NextBlock);
388 Offset += TInfo.Width;
389 }
390
391 // Emit the call to cudaLaunch
392 llvm::FunctionCallee cudaLaunchFn = getLaunchFn();
393 llvm::Value *Arg = CGF.Builder.CreatePointerCast(CGF.CurFn, CharPtrTy);
394 CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
395 CGF.EmitBranch(EndBlock);
396
397 CGF.EmitBlock(EndBlock);
398}
399
400// Replace the original variable Var with the address loaded from variable
401// ManagedVar populated by HIP runtime.
402static void replaceManagedVar(llvm::GlobalVariable *Var,
403 llvm::GlobalVariable *ManagedVar) {
404 SmallVector<SmallVector<llvm::User *, 8>, 8> WorkList;
405 for (auto &&VarUse : Var->uses()) {
406 WorkList.push_back({VarUse.getUser()});
407 }
408 while (!WorkList.empty()) {
409 auto &&WorkItem = WorkList.pop_back_val();
410 auto *U = WorkItem.back();
411 if (isa<llvm::ConstantExpr>(U)) {
412 for (auto &&UU : U->uses()) {
413 WorkItem.push_back(UU.getUser());
414 WorkList.push_back(WorkItem);
415 WorkItem.pop_back();
416 }
417 continue;
418 }
419 if (auto *I = dyn_cast<llvm::Instruction>(U)) {
420 llvm::Value *OldV = Var;
421 llvm::Instruction *NewV =
422 new llvm::LoadInst(Var->getType(), ManagedVar, "ld.managed", false,
423 llvm::Align(Var->getAlignment()), I);
424 WorkItem.pop_back();
425 // Replace constant expressions directly or indirectly using the managed
426 // variable with instructions.
427 for (auto &&Op : WorkItem) {
428 auto *CE = cast<llvm::ConstantExpr>(Op);
429 auto *NewInst = llvm::createReplacementInstr(CE, I);
430 NewInst->replaceUsesOfWith(OldV, NewV);
431 OldV = CE;
432 NewV = NewInst;
433 }
434 I->replaceUsesOfWith(OldV, NewV);
435 } else {
436 llvm_unreachable("Invalid use of managed variable")::llvm::llvm_unreachable_internal("Invalid use of managed variable"
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 436)
;
437 }
438 }
439}
440
441/// Creates a function that sets up state on the host side for CUDA objects that
442/// have a presence on both the host and device sides. Specifically, registers
443/// the host side of kernel functions and device global variables with the CUDA
444/// runtime.
445/// \code
446/// void __cuda_register_globals(void** GpuBinaryHandle) {
447/// __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
448/// ...
449/// __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
450/// __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
451/// ...
452/// __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
453/// }
454/// \endcode
455llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
456 // No need to register anything
457 if (EmittedKernels.empty() && DeviceVars.empty())
458 return nullptr;
459
460 llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
461 getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
462 addUnderscoredPrefixToName("_register_globals"), &TheModule);
463 llvm::BasicBlock *EntryBB =
464 llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
465 CGBuilderTy Builder(CGM, Context);
466 Builder.SetInsertPoint(EntryBB);
467
468 // void __cudaRegisterFunction(void **, const char *, char *, const char *,
469 // int, uint3*, uint3*, dim3*, dim3*, int*)
470 llvm::Type *RegisterFuncParams[] = {
471 VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
472 VoidPtrTy, VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()};
473 llvm::FunctionCallee RegisterFunc = CGM.CreateRuntimeFunction(
474 llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
475 addUnderscoredPrefixToName("RegisterFunction"));
476
477 // Extract GpuBinaryHandle passed as the first argument passed to
478 // __cuda_register_globals() and generate __cudaRegisterFunction() call for
479 // each emitted kernel.
480 llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
481 for (auto &&I : EmittedKernels) {
482 llvm::Constant *KernelName =
483 makeConstantString(getDeviceSideName(cast<NamedDecl>(I.D)));
484 llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
485 llvm::Value *Args[] = {
486 &GpuBinaryHandlePtr,
487 Builder.CreateBitCast(I.Kernel, VoidPtrTy),
488 KernelName,
489 KernelName,
490 llvm::ConstantInt::get(IntTy, -1),
491 NullPtr,
492 NullPtr,
493 NullPtr,
494 NullPtr,
495 llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
496 Builder.CreateCall(RegisterFunc, Args);
497 }
498
499 llvm::Type *VarSizeTy = IntTy;
500 // For HIP or CUDA 9.0+, device variable size is type of `size_t`.
501 if (CGM.getLangOpts().HIP ||
502 ToCudaVersion(CGM.getTarget().getSDKVersion()) >= CudaVersion::CUDA_90)
503 VarSizeTy = SizeTy;
504
505 // void __cudaRegisterVar(void **, char *, char *, const char *,
506 // int, int, int, int)
507 llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
508 CharPtrTy, IntTy, VarSizeTy,
509 IntTy, IntTy};
510 llvm::FunctionCallee RegisterVar = CGM.CreateRuntimeFunction(
511 llvm::FunctionType::get(VoidTy, RegisterVarParams, false),
512 addUnderscoredPrefixToName("RegisterVar"));
513 // void __hipRegisterManagedVar(void **, char *, char *, const char *,
514 // size_t, unsigned)
515 llvm::Type *RegisterManagedVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
516 CharPtrTy, VarSizeTy, IntTy};
517 llvm::FunctionCallee RegisterManagedVar = CGM.CreateRuntimeFunction(
518 llvm::FunctionType::get(VoidTy, RegisterManagedVarParams, false),
519 addUnderscoredPrefixToName("RegisterManagedVar"));
520 // void __cudaRegisterSurface(void **, const struct surfaceReference *,
521 // const void **, const char *, int, int);
522 llvm::FunctionCallee RegisterSurf = CGM.CreateRuntimeFunction(
523 llvm::FunctionType::get(
524 VoidTy, {VoidPtrPtrTy, VoidPtrTy, CharPtrTy, CharPtrTy, IntTy, IntTy},
525 false),
526 addUnderscoredPrefixToName("RegisterSurface"));
527 // void __cudaRegisterTexture(void **, const struct textureReference *,
528 // const void **, const char *, int, int, int)
529 llvm::FunctionCallee RegisterTex = CGM.CreateRuntimeFunction(
530 llvm::FunctionType::get(
531 VoidTy,
532 {VoidPtrPtrTy, VoidPtrTy, CharPtrTy, CharPtrTy, IntTy, IntTy, IntTy},
533 false),
534 addUnderscoredPrefixToName("RegisterTexture"));
535 for (auto &&Info : DeviceVars) {
536 llvm::GlobalVariable *Var = Info.Var;
537 llvm::Constant *VarName = makeConstantString(getDeviceSideName(Info.D));
538 switch (Info.Flags.getKind()) {
539 case DeviceVarFlags::Variable: {
540 uint64_t VarSize =
541 CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
542 if (Info.Flags.isManaged()) {
543 auto ManagedVar = new llvm::GlobalVariable(
544 CGM.getModule(), Var->getType(),
545 /*isConstant=*/false, Var->getLinkage(),
546 /*Init=*/llvm::ConstantPointerNull::get(Var->getType()),
547 Twine(Var->getName() + ".managed"), /*InsertBefore=*/nullptr,
548 llvm::GlobalVariable::NotThreadLocal);
549 ManagedVar->setDSOLocal(Var->isDSOLocal());
550 ManagedVar->setVisibility(Var->getVisibility());
551 replaceManagedVar(Var, ManagedVar);
552 llvm::Value *Args[] = {
553 &GpuBinaryHandlePtr,
554 Builder.CreateBitCast(ManagedVar, VoidPtrTy),
555 Builder.CreateBitCast(Var, VoidPtrTy),
556 VarName,
557 llvm::ConstantInt::get(VarSizeTy, VarSize),
558 llvm::ConstantInt::get(IntTy, Var->getAlignment())};
559 Builder.CreateCall(RegisterManagedVar, Args);
560 } else {
561 llvm::Value *Args[] = {
562 &GpuBinaryHandlePtr,
563 Builder.CreateBitCast(Var, VoidPtrTy),
564 VarName,
565 VarName,
566 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern()),
567 llvm::ConstantInt::get(VarSizeTy, VarSize),
568 llvm::ConstantInt::get(IntTy, Info.Flags.isConstant()),
569 llvm::ConstantInt::get(IntTy, 0)};
570 Builder.CreateCall(RegisterVar, Args);
571 }
572 break;
573 }
574 case DeviceVarFlags::Surface:
575 Builder.CreateCall(
576 RegisterSurf,
577 {&GpuBinaryHandlePtr, Builder.CreateBitCast(Var, VoidPtrTy), VarName,
578 VarName, llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
579 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
580 break;
581 case DeviceVarFlags::Texture:
582 Builder.CreateCall(
583 RegisterTex,
584 {&GpuBinaryHandlePtr, Builder.CreateBitCast(Var, VoidPtrTy), VarName,
585 VarName, llvm::ConstantInt::get(IntTy, Info.Flags.getSurfTexType()),
586 llvm::ConstantInt::get(IntTy, Info.Flags.isNormalized()),
587 llvm::ConstantInt::get(IntTy, Info.Flags.isExtern())});
588 break;
589 }
590 }
591
592 Builder.CreateRetVoid();
593 return RegisterKernelsFunc;
594}
595
596/// Creates a global constructor function for the module:
597///
598/// For CUDA:
599/// \code
600/// void __cuda_module_ctor(void*) {
601/// Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
602/// __cuda_register_globals(Handle);
603/// }
604/// \endcode
605///
606/// For HIP:
607/// \code
608/// void __hip_module_ctor(void*) {
609/// if (__hip_gpubin_handle == 0) {
610/// __hip_gpubin_handle = __hipRegisterFatBinary(GpuBinaryBlob);
611/// __hip_register_globals(__hip_gpubin_handle);
612/// }
613/// }
614/// \endcode
615llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
616 bool IsHIP = CGM.getLangOpts().HIP;
617 bool IsCUDA = CGM.getLangOpts().CUDA;
618 // No need to generate ctors/dtors if there is no GPU binary.
619 StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
620 if (CudaGpuBinaryFileName.empty() && !IsHIP)
621 return nullptr;
622 if ((IsHIP || (IsCUDA && !RelocatableDeviceCode)) && EmittedKernels.empty() &&
623 DeviceVars.empty())
624 return nullptr;
625
626 // void __{cuda|hip}_register_globals(void* handle);
627 llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
628 // We always need a function to pass in as callback. Create a dummy
629 // implementation if we don't need to register anything.
630 if (RelocatableDeviceCode && !RegisterGlobalsFunc)
631 RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
632
633 // void ** __{cuda|hip}RegisterFatBinary(void *);
634 llvm::FunctionCallee RegisterFatbinFunc = CGM.CreateRuntimeFunction(
635 llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false),
636 addUnderscoredPrefixToName("RegisterFatBinary"));
637 // struct { int magic, int version, void * gpu_binary, void * dont_care };
638 llvm::StructType *FatbinWrapperTy =
639 llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
640
641 // Register GPU binary with the CUDA runtime, store returned handle in a
642 // global variable and save a reference in GpuBinaryHandle to be cleaned up
643 // in destructor on exit. Then associate all known kernels with the GPU binary
644 // handle so CUDA runtime can figure out what to call on the GPU side.
645 std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr;
646 if (!CudaGpuBinaryFileName.empty()) {
647 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CudaGpuBinaryOrErr =
648 llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName);
649 if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
650 CGM.getDiags().Report(diag::err_cannot_open_file)
651 << CudaGpuBinaryFileName << EC.message();
652 return nullptr;
653 }
654 CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
655 }
656
657 llvm::Function *ModuleCtorFunc = llvm::Function::Create(
658 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
659 llvm::GlobalValue::InternalLinkage,
660 addUnderscoredPrefixToName("_module_ctor"), &TheModule);
661 llvm::BasicBlock *CtorEntryBB =
662 llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
663 CGBuilderTy CtorBuilder(CGM, Context);
664
665 CtorBuilder.SetInsertPoint(CtorEntryBB);
666
667 const char *FatbinConstantName;
668 const char *FatbinSectionName;
669 const char *ModuleIDSectionName;
670 StringRef ModuleIDPrefix;
671 llvm::Constant *FatBinStr;
672 unsigned FatMagic;
673 if (IsHIP) {
674 FatbinConstantName = ".hip_fatbin";
675 FatbinSectionName = ".hipFatBinSegment";
676
677 ModuleIDSectionName = "__hip_module_id";
678 ModuleIDPrefix = "__hip_";
679
680 if (CudaGpuBinary) {
681 // If fatbin is available from early finalization, create a string
682 // literal containing the fat binary loaded from the given file.
683 const unsigned HIPCodeObjectAlign = 4096;
684 FatBinStr =
685 makeConstantString(std::string(CudaGpuBinary->getBuffer()), "",
686 FatbinConstantName, HIPCodeObjectAlign);
687 } else {
688 // If fatbin is not available, create an external symbol
689 // __hip_fatbin in section .hip_fatbin. The external symbol is supposed
690 // to contain the fat binary but will be populated somewhere else,
691 // e.g. by lld through link script.
692 FatBinStr = new llvm::GlobalVariable(
693 CGM.getModule(), CGM.Int8Ty,
694 /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
695 "__hip_fatbin", nullptr,
696 llvm::GlobalVariable::NotThreadLocal);
697 cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
698 }
699
700 FatMagic = HIPFatMagic;
701 } else {
702 if (RelocatableDeviceCode)
703 FatbinConstantName = CGM.getTriple().isMacOSX()
704 ? "__NV_CUDA,__nv_relfatbin"
705 : "__nv_relfatbin";
706 else
707 FatbinConstantName =
708 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
709 // NVIDIA's cuobjdump looks for fatbins in this section.
710 FatbinSectionName =
711 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
712
713 ModuleIDSectionName = CGM.getTriple().isMacOSX()
714 ? "__NV_CUDA,__nv_module_id"
715 : "__nv_module_id";
716 ModuleIDPrefix = "__nv_";
717
718 // For CUDA, create a string literal containing the fat binary loaded from
719 // the given file.
720 FatBinStr = makeConstantString(std::string(CudaGpuBinary->getBuffer()), "",
721 FatbinConstantName, 8);
722 FatMagic = CudaFatMagic;
723 }
724
725 // Create initialized wrapper structure that points to the loaded GPU binary
726 ConstantInitBuilder Builder(CGM);
727 auto Values = Builder.beginStruct(FatbinWrapperTy);
728 // Fatbin wrapper magic.
729 Values.addInt(IntTy, FatMagic);
730 // Fatbin version.
731 Values.addInt(IntTy, 1);
732 // Data.
733 Values.add(FatBinStr);
734 // Unused in fatbin v1.
735 Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
736 llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
737 addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
738 /*constant*/ true);
739 FatbinWrapper->setSection(FatbinSectionName);
740
741 // There is only one HIP fat binary per linked module, however there are
742 // multiple constructor functions. Make sure the fat binary is registered
743 // only once. The constructor functions are executed by the dynamic loader
744 // before the program gains control. The dynamic loader cannot execute the
745 // constructor functions concurrently since doing that would not guarantee
746 // thread safety of the loaded program. Therefore we can assume sequential
747 // execution of constructor functions here.
748 if (IsHIP) {
749 auto Linkage = CudaGpuBinary ? llvm::GlobalValue::InternalLinkage :
750 llvm::GlobalValue::LinkOnceAnyLinkage;
751 llvm::BasicBlock *IfBlock =
752 llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
753 llvm::BasicBlock *ExitBlock =
754 llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);
755 // The name, size, and initialization pattern of this variable is part
756 // of HIP ABI.
757 GpuBinaryHandle = new llvm::GlobalVariable(
758 TheModule, VoidPtrPtrTy, /*isConstant=*/false,
759 Linkage,
760 /*Initializer=*/llvm::ConstantPointerNull::get(VoidPtrPtrTy),
761 "__hip_gpubin_handle");
762 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
763 // Prevent the weak symbol in different shared libraries being merged.
764 if (Linkage != llvm::GlobalValue::InternalLinkage)
765 GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility);
766 Address GpuBinaryAddr(
767 GpuBinaryHandle,
768 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
769 {
770 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
771 llvm::Constant *Zero =
772 llvm::Constant::getNullValue(HandleValue->getType());
773 llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
774 CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
775 }
776 {
777 CtorBuilder.SetInsertPoint(IfBlock);
778 // GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper);
779 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
780 RegisterFatbinFunc,
781 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
782 CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
783 CtorBuilder.CreateBr(ExitBlock);
784 }
785 {
786 CtorBuilder.SetInsertPoint(ExitBlock);
787 // Call __hip_register_globals(GpuBinaryHandle);
788 if (RegisterGlobalsFunc) {
789 auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
790 CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
791 }
792 }
793 } else if (!RelocatableDeviceCode) {
794 // Register binary with CUDA runtime. This is substantially different in
795 // default mode vs. separate compilation!
796 // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
797 llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
798 RegisterFatbinFunc,
799 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
800 GpuBinaryHandle = new llvm::GlobalVariable(
801 TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage,
802 llvm::ConstantPointerNull::get(VoidPtrPtrTy), "__cuda_gpubin_handle");
803 GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getAsAlign());
804 CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
805 CGM.getPointerAlign());
806
807 // Call __cuda_register_globals(GpuBinaryHandle);
808 if (RegisterGlobalsFunc)
809 CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
810
811 // Call __cudaRegisterFatBinaryEnd(Handle) if this CUDA version needs it.
812 if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),
813 CudaFeature::CUDA_USES_FATBIN_REGISTER_END)) {
814 // void __cudaRegisterFatBinaryEnd(void **);
815 llvm::FunctionCallee RegisterFatbinEndFunc = CGM.CreateRuntimeFunction(
816 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
817 "__cudaRegisterFatBinaryEnd");
818 CtorBuilder.CreateCall(RegisterFatbinEndFunc, RegisterFatbinCall);
819 }
820 } else {
821 // Generate a unique module ID.
822 SmallString<64> ModuleID;
823 llvm::raw_svector_ostream OS(ModuleID);
824 OS << ModuleIDPrefix << llvm::format("%" PRIx64"l" "x", FatbinWrapper->getGUID());
825 llvm::Constant *ModuleIDConstant = makeConstantString(
826 std::string(ModuleID.str()), "", ModuleIDSectionName, 32);
827
828 // Create an alias for the FatbinWrapper that nvcc will look for.
829 llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
830 Twine("__fatbinwrap") + ModuleID, FatbinWrapper);
831
832 // void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *,
833 // void *, void (*)(void **))
834 SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary");
835 RegisterLinkedBinaryName += ModuleID;
836 llvm::FunctionCallee RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
837 getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
838
839 assert(RegisterGlobalsFunc && "Expecting at least dummy function!")((RegisterGlobalsFunc && "Expecting at least dummy function!"
) ? static_cast<void> (0) : __assert_fail ("RegisterGlobalsFunc && \"Expecting at least dummy function!\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 839, __PRETTY_FUNCTION__))
;
840 llvm::Value *Args[] = {RegisterGlobalsFunc,
841 CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
842 ModuleIDConstant,
843 makeDummyFunction(getCallbackFnTy())};
844 CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
845 }
846
847 // Create destructor and register it with atexit() the way NVCC does it. Doing
848 // it during regular destructor phase worked in CUDA before 9.2 but results in
849 // double-free in 9.2.
850 if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
851 // extern "C" int atexit(void (*f)(void));
852 llvm::FunctionType *AtExitTy =
853 llvm::FunctionType::get(IntTy, CleanupFn->getType(), false);
854 llvm::FunctionCallee AtExitFunc =
855 CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(),
856 /*Local=*/true);
857 CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
858 }
859
860 CtorBuilder.CreateRetVoid();
861 return ModuleCtorFunc;
862}
863
864/// Creates a global destructor function that unregisters the GPU code blob
865/// registered by constructor.
866///
867/// For CUDA:
868/// \code
869/// void __cuda_module_dtor(void*) {
870/// __cudaUnregisterFatBinary(Handle);
871/// }
872/// \endcode
873///
874/// For HIP:
875/// \code
876/// void __hip_module_dtor(void*) {
877/// if (__hip_gpubin_handle) {
878/// __hipUnregisterFatBinary(__hip_gpubin_handle);
879/// __hip_gpubin_handle = 0;
880/// }
881/// }
882/// \endcode
883llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
884 // No need for destructor if we don't have a handle to unregister.
885 if (!GpuBinaryHandle)
886 return nullptr;
887
888 // void __cudaUnregisterFatBinary(void ** handle);
889 llvm::FunctionCallee UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
890 llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
891 addUnderscoredPrefixToName("UnregisterFatBinary"));
892
893 llvm::Function *ModuleDtorFunc = llvm::Function::Create(
894 llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
895 llvm::GlobalValue::InternalLinkage,
896 addUnderscoredPrefixToName("_module_dtor"), &TheModule);
897
898 llvm::BasicBlock *DtorEntryBB =
899 llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
900 CGBuilderTy DtorBuilder(CGM, Context);
901 DtorBuilder.SetInsertPoint(DtorEntryBB);
902
903 Address GpuBinaryAddr(GpuBinaryHandle, CharUnits::fromQuantity(
904 GpuBinaryHandle->getAlignment()));
905 auto HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
906 // There is only one HIP fat binary per linked module, however there are
907 // multiple destructor functions. Make sure the fat binary is unregistered
908 // only once.
909 if (CGM.getLangOpts().HIP) {
910 llvm::BasicBlock *IfBlock =
911 llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc);
912 llvm::BasicBlock *ExitBlock =
913 llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc);
914 llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
915 llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
916 DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
917
918 DtorBuilder.SetInsertPoint(IfBlock);
919 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
920 DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
921 DtorBuilder.CreateBr(ExitBlock);
922
923 DtorBuilder.SetInsertPoint(ExitBlock);
924 } else {
925 DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
926 }
927 DtorBuilder.CreateRetVoid();
928 return ModuleDtorFunc;
929}
930
931CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
932 return new CGNVCUDARuntime(CGM);
933}
934
935void CGNVCUDARuntime::internalizeDeviceSideVar(
936 const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage) {
937 // For -fno-gpu-rdc, host-side shadows of external declarations of device-side
938 // global variables become internal definitions. These have to be internal in
939 // order to prevent name conflicts with global host variables with the same
940 // name in a different TUs.
941 //
942 // For -fgpu-rdc, the shadow variables should not be internalized because
943 // they may be accessed by different TU.
944 if (CGM.getLangOpts().GPURelocatableDeviceCode)
945 return;
946
947 // __shared__ variables are odd. Shadows do get created, but
948 // they are not registered with the CUDA runtime, so they
949 // can't really be used to access their device-side
950 // counterparts. It's not clear yet whether it's nvcc's bug or
951 // a feature, but we've got to do the same for compatibility.
952 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
953 D->hasAttr<CUDASharedAttr>() ||
954 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
955 D->getType()->isCUDADeviceBuiltinTextureType()) {
956 Linkage = llvm::GlobalValue::InternalLinkage;
957 }
958}
959
960void CGNVCUDARuntime::handleVarRegistration(const VarDecl *D,
961 llvm::GlobalVariable &GV) {
962 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
1
Calling 'Decl::hasAttr'
4
Returning from 'Decl::hasAttr'
5
Calling 'Decl::hasAttr'
7
Returning from 'Decl::hasAttr'
8
Taking false branch
963 // Shadow variables and their properties must be registered with CUDA
964 // runtime. Skip Extern global variables, which will be registered in
965 // the TU where they are defined.
966 //
967 // Don't register a C++17 inline variable. The local symbol can be
968 // discarded and referencing a discarded local symbol from outside the
969 // comdat (__cuda_register_globals) is disallowed by the ELF spec.
970 // TODO: Reject __device__ constexpr and __device__ inline in Sema.
971 if (!D->hasExternalStorage() && !D->isInline())
972 registerDeviceVar(D, GV, !D->hasDefinition(),
973 D->hasAttr<CUDAConstantAttr>());
974 } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
9
Assuming the condition is true
10
Taking true branch
975 D->getType()->isCUDADeviceBuiltinTextureType()) {
976 // Builtin surfaces and textures and their template arguments are
977 // also registered with CUDA runtime.
978 const ClassTemplateSpecializationDecl *TD =
979 cast<ClassTemplateSpecializationDecl>(
980 D->getType()->getAs<RecordType>()->getDecl());
11
Assuming the object is not a 'RecordType'
12
Called C++ object pointer is null
981 const TemplateArgumentList &Args = TD->getTemplateArgs();
982 if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {
983 assert(Args.size() == 2 &&((Args.size() == 2 && "Unexpected number of template arguments of CUDA device "
"builtin surface type.") ? static_cast<void> (0) : __assert_fail
("Args.size() == 2 && \"Unexpected number of template arguments of CUDA device \" \"builtin surface type.\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 985, __PRETTY_FUNCTION__))
984 "Unexpected number of template arguments of CUDA device "((Args.size() == 2 && "Unexpected number of template arguments of CUDA device "
"builtin surface type.") ? static_cast<void> (0) : __assert_fail
("Args.size() == 2 && \"Unexpected number of template arguments of CUDA device \" \"builtin surface type.\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 985, __PRETTY_FUNCTION__))
985 "builtin surface type.")((Args.size() == 2 && "Unexpected number of template arguments of CUDA device "
"builtin surface type.") ? static_cast<void> (0) : __assert_fail
("Args.size() == 2 && \"Unexpected number of template arguments of CUDA device \" \"builtin surface type.\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 985, __PRETTY_FUNCTION__))
;
986 auto SurfType = Args[1].getAsIntegral();
987 if (!D->hasExternalStorage())
988 registerDeviceSurf(D, GV, !D->hasDefinition(), SurfType.getSExtValue());
989 } else {
990 assert(Args.size() == 3 &&((Args.size() == 3 && "Unexpected number of template arguments of CUDA device "
"builtin texture type.") ? static_cast<void> (0) : __assert_fail
("Args.size() == 3 && \"Unexpected number of template arguments of CUDA device \" \"builtin texture type.\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 992, __PRETTY_FUNCTION__))
991 "Unexpected number of template arguments of CUDA device "((Args.size() == 3 && "Unexpected number of template arguments of CUDA device "
"builtin texture type.") ? static_cast<void> (0) : __assert_fail
("Args.size() == 3 && \"Unexpected number of template arguments of CUDA device \" \"builtin texture type.\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 992, __PRETTY_FUNCTION__))
992 "builtin texture type.")((Args.size() == 3 && "Unexpected number of template arguments of CUDA device "
"builtin texture type.") ? static_cast<void> (0) : __assert_fail
("Args.size() == 3 && \"Unexpected number of template arguments of CUDA device \" \"builtin texture type.\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/CodeGen/CGCUDANV.cpp"
, 992, __PRETTY_FUNCTION__))
;
993 auto TexType = Args[1].getAsIntegral();
994 auto Normalized = Args[2].getAsIntegral();
995 if (!D->hasExternalStorage())
996 registerDeviceTex(D, GV, !D->hasDefinition(), TexType.getSExtValue(),
997 Normalized.getZExtValue());
998 }
999 }
1000}

/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Decl and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TemplateParameterList;
70class TranslationUnitDecl;
71class UsingDirectiveDecl;
72
73/// Captures the result of checking the availability of a
74/// declaration.
75enum AvailabilityResult {
76 AR_Available = 0,
77 AR_NotYetIntroduced,
78 AR_Deprecated,
79 AR_Unavailable
80};
81
82/// Decl - This represents one declaration (or definition), e.g. a variable,
83/// typedef, function, struct, etc.
84///
85/// Note: There are objects tacked on before the *beginning* of Decl
86/// (and its subclasses) in its Decl::operator new(). Proper alignment
87/// of all subclasses (not requiring more than the alignment of Decl) is
88/// asserted in DeclBase.cpp.
89class alignas(8) Decl {
90public:
91 /// Lists the kind of concrete classes of Decl.
92 enum Kind {
93#define DECL(DERIVED, BASE) DERIVED,
94#define ABSTRACT_DECL(DECL)
95#define DECL_RANGE(BASE, START, END) \
96 first##BASE = START, last##BASE = END,
97#define LAST_DECL_RANGE(BASE, START, END) \
98 first##BASE = START, last##BASE = END
99#include "clang/AST/DeclNodes.inc"
100 };
101
102 /// A placeholder type used to construct an empty shell of a
103 /// decl-derived type that will be filled in later (e.g., by some
104 /// deserialization method).
105 struct EmptyShell {};
106
107 /// IdentifierNamespace - The different namespaces in which
108 /// declarations may appear. According to C99 6.2.3, there are
109 /// four namespaces, labels, tags, members and ordinary
110 /// identifiers. C++ describes lookup completely differently:
111 /// certain lookups merely "ignore" certain kinds of declarations,
112 /// usually based on whether the declaration is of a type, etc.
113 ///
114 /// These are meant as bitmasks, so that searches in
115 /// C++ can look into the "tag" namespace during ordinary lookup.
116 ///
117 /// Decl currently provides 15 bits of IDNS bits.
118 enum IdentifierNamespace {
119 /// Labels, declared with 'x:' and referenced with 'goto x'.
120 IDNS_Label = 0x0001,
121
122 /// Tags, declared with 'struct foo;' and referenced with
123 /// 'struct foo'. All tags are also types. This is what
124 /// elaborated-type-specifiers look for in C.
125 /// This also contains names that conflict with tags in the
126 /// same scope but that are otherwise ordinary names (non-type
127 /// template parameters and indirect field declarations).
128 IDNS_Tag = 0x0002,
129
130 /// Types, declared with 'struct foo', typedefs, etc.
131 /// This is what elaborated-type-specifiers look for in C++,
132 /// but note that it's ill-formed to find a non-tag.
133 IDNS_Type = 0x0004,
134
135 /// Members, declared with object declarations within tag
136 /// definitions. In C, these can only be found by "qualified"
137 /// lookup in member expressions. In C++, they're found by
138 /// normal lookup.
139 IDNS_Member = 0x0008,
140
141 /// Namespaces, declared with 'namespace foo {}'.
142 /// Lookup for nested-name-specifiers find these.
143 IDNS_Namespace = 0x0010,
144
145 /// Ordinary names. In C, everything that's not a label, tag,
146 /// member, or function-local extern ends up here.
147 IDNS_Ordinary = 0x0020,
148
149 /// Objective C \@protocol.
150 IDNS_ObjCProtocol = 0x0040,
151
152 /// This declaration is a friend function. A friend function
153 /// declaration is always in this namespace but may also be in
154 /// IDNS_Ordinary if it was previously declared.
155 IDNS_OrdinaryFriend = 0x0080,
156
157 /// This declaration is a friend class. A friend class
158 /// declaration is always in this namespace but may also be in
159 /// IDNS_Tag|IDNS_Type if it was previously declared.
160 IDNS_TagFriend = 0x0100,
161
162 /// This declaration is a using declaration. A using declaration
163 /// *introduces* a number of other declarations into the current
164 /// scope, and those declarations use the IDNS of their targets,
165 /// but the actual using declarations go in this namespace.
166 IDNS_Using = 0x0200,
167
168 /// This declaration is a C++ operator declared in a non-class
169 /// context. All such operators are also in IDNS_Ordinary.
170 /// C++ lexical operator lookup looks for these.
171 IDNS_NonMemberOperator = 0x0400,
172
173 /// This declaration is a function-local extern declaration of a
174 /// variable or function. This may also be IDNS_Ordinary if it
175 /// has been declared outside any function. These act mostly like
176 /// invisible friend declarations, but are also visible to unqualified
177 /// lookup within the scope of the declaring function.
178 IDNS_LocalExtern = 0x0800,
179
180 /// This declaration is an OpenMP user defined reduction construction.
181 IDNS_OMPReduction = 0x1000,
182
183 /// This declaration is an OpenMP user defined mapper.
184 IDNS_OMPMapper = 0x2000,
185 };
186
187 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
188 /// parameter types in method declarations. Other than remembering
189 /// them and mangling them into the method's signature string, these
190 /// are ignored by the compiler; they are consumed by certain
191 /// remote-messaging frameworks.
192 ///
193 /// in, inout, and out are mutually exclusive and apply only to
194 /// method parameters. bycopy and byref are mutually exclusive and
195 /// apply only to method parameters (?). oneway applies only to
196 /// results. All of these expect their corresponding parameter to
197 /// have a particular type. None of this is currently enforced by
198 /// clang.
199 ///
200 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
201 enum ObjCDeclQualifier {
202 OBJC_TQ_None = 0x0,
203 OBJC_TQ_In = 0x1,
204 OBJC_TQ_Inout = 0x2,
205 OBJC_TQ_Out = 0x4,
206 OBJC_TQ_Bycopy = 0x8,
207 OBJC_TQ_Byref = 0x10,
208 OBJC_TQ_Oneway = 0x20,
209
210 /// The nullability qualifier is set when the nullability of the
211 /// result or parameter was expressed via a context-sensitive
212 /// keyword.
213 OBJC_TQ_CSNullability = 0x40
214 };
215
216 /// The kind of ownership a declaration has, for visibility purposes.
217 /// This enumeration is designed such that higher values represent higher
218 /// levels of name hiding.
219 enum class ModuleOwnershipKind : unsigned {
220 /// This declaration is not owned by a module.
221 Unowned,
222
223 /// This declaration has an owning module, but is globally visible
224 /// (typically because its owning module is visible and we know that
225 /// modules cannot later become hidden in this compilation).
226 /// After serialization and deserialization, this will be converted
227 /// to VisibleWhenImported.
228 Visible,
229
230 /// This declaration has an owning module, and is visible when that
231 /// module is imported.
232 VisibleWhenImported,
233
234 /// This declaration has an owning module, but is only visible to
235 /// lookups that occur within that module.
236 ModulePrivate
237 };
238
239protected:
240 /// The next declaration within the same lexical
241 /// DeclContext. These pointers form the linked list that is
242 /// traversed via DeclContext's decls_begin()/decls_end().
243 ///
244 /// The extra two bits are used for the ModuleOwnershipKind.
245 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
246
247private:
248 friend class DeclContext;
249
250 struct MultipleDC {
251 DeclContext *SemanticDC;
252 DeclContext *LexicalDC;
253 };
254
255 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
256 /// For declarations that don't contain C++ scope specifiers, it contains
257 /// the DeclContext where the Decl was declared.
258 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
259 /// with the context where it semantically belongs (SemanticDC) and the
260 /// context where it was lexically declared (LexicalDC).
261 /// e.g.:
262 ///
263 /// namespace A {
264 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
265 /// }
266 /// void A::f(); // SemanticDC == namespace 'A'
267 /// // LexicalDC == global namespace
268 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
269
270 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
271 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
272
273 MultipleDC *getMultipleDC() const {
274 return DeclCtx.get<MultipleDC*>();
275 }
276
277 DeclContext *getSemanticDC() const {
278 return DeclCtx.get<DeclContext*>();
279 }
280
281 /// Loc - The location of this decl.
282 SourceLocation Loc;
283
284 /// DeclKind - This indicates which class this is.
285 unsigned DeclKind : 7;
286
287 /// InvalidDecl - This indicates a semantic error occurred.
288 unsigned InvalidDecl : 1;
289
290 /// HasAttrs - This indicates whether the decl has attributes or not.
291 unsigned HasAttrs : 1;
292
293 /// Implicit - Whether this declaration was implicitly generated by
294 /// the implementation rather than explicitly written by the user.
295 unsigned Implicit : 1;
296
297 /// Whether this declaration was "used", meaning that a definition is
298 /// required.
299 unsigned Used : 1;
300
301 /// Whether this declaration was "referenced".
302 /// The difference with 'Used' is whether the reference appears in a
303 /// evaluated context or not, e.g. functions used in uninstantiated templates
304 /// are regarded as "referenced" but not "used".
305 unsigned Referenced : 1;
306
307 /// Whether this declaration is a top-level declaration (function,
308 /// global variable, etc.) that is lexically inside an objc container
309 /// definition.
310 unsigned TopLevelDeclInObjCContainer : 1;
311
312 /// Whether statistic collection is enabled.
313 static bool StatisticsEnabled;
314
315protected:
316 friend class ASTDeclReader;
317 friend class ASTDeclWriter;
318 friend class ASTNodeImporter;
319 friend class ASTReader;
320 friend class CXXClassMemberWrapper;
321 friend class LinkageComputer;
322 template<typename decl_type> friend class Redeclarable;
323
324 /// Access - Used by C++ decls for the access specifier.
325 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
326 unsigned Access : 2;
327
328 /// Whether this declaration was loaded from an AST file.
329 unsigned FromASTFile : 1;
330
331 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
332 unsigned IdentifierNamespace : 14;
333
334 /// If 0, we have not computed the linkage of this declaration.
335 /// Otherwise, it is the linkage + 1.
336 mutable unsigned CacheValidAndLinkage : 3;
337
338 /// Allocate memory for a deserialized declaration.
339 ///
340 /// This routine must be used to allocate memory for any declaration that is
341 /// deserialized from a module file.
342 ///
343 /// \param Size The size of the allocated object.
344 /// \param Ctx The context in which we will allocate memory.
345 /// \param ID The global ID of the deserialized declaration.
346 /// \param Extra The amount of extra space to allocate after the object.
347 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
348 std::size_t Extra = 0);
349
350 /// Allocate memory for a non-deserialized declaration.
351 void *operator new(std::size_t Size, const ASTContext &Ctx,
352 DeclContext *Parent, std::size_t Extra = 0);
353
354private:
355 bool AccessDeclContextSanity() const;
356
357 /// Get the module ownership kind to use for a local lexical child of \p DC,
358 /// which may be either a local or (rarely) an imported declaration.
359 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
360 if (DC) {
361 auto *D = cast<Decl>(DC);
362 auto MOK = D->getModuleOwnershipKind();
363 if (MOK != ModuleOwnershipKind::Unowned &&
364 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
365 return MOK;
366 // If D is not local and we have no local module storage, then we don't
367 // need to track module ownership at all.
368 }
369 return ModuleOwnershipKind::Unowned;
370 }
371
372public:
373 Decl() = delete;
374 Decl(const Decl&) = delete;
375 Decl(Decl &&) = delete;
376 Decl &operator=(const Decl&) = delete;
377 Decl &operator=(Decl&&) = delete;
378
379protected:
380 Decl(Kind DK, DeclContext *DC, SourceLocation L)
381 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
382 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
383 Implicit(false), Used(false), Referenced(false),
384 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
385 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
386 CacheValidAndLinkage(0) {
387 if (StatisticsEnabled) add(DK);
388 }
389
390 Decl(Kind DK, EmptyShell Empty)
391 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
392 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
393 Access(AS_none), FromASTFile(0),
394 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
395 CacheValidAndLinkage(0) {
396 if (StatisticsEnabled) add(DK);
397 }
398
399 virtual ~Decl();
400
401 /// Update a potentially out-of-date declaration.
402 void updateOutOfDate(IdentifierInfo &II) const;
403
404 Linkage getCachedLinkage() const {
405 return Linkage(CacheValidAndLinkage - 1);
406 }
407
408 void setCachedLinkage(Linkage L) const {
409 CacheValidAndLinkage = L + 1;
410 }
411
412 bool hasCachedLinkage() const {
413 return CacheValidAndLinkage;
414 }
415
416public:
417 /// Source range that this declaration covers.
418 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
419 return SourceRange(getLocation(), getLocation());
420 }
421
422 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
423 return getSourceRange().getBegin();
424 }
425
426 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
427 return getSourceRange().getEnd();
428 }
429
430 SourceLocation getLocation() const { return Loc; }
431 void setLocation(SourceLocation L) { Loc = L; }
432
433 Kind getKind() const { return static_cast<Kind>(DeclKind); }
434 const char *getDeclKindName() const;
435
436 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
437 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
438
439 DeclContext *getDeclContext() {
440 if (isInSemaDC())
441 return getSemanticDC();
442 return getMultipleDC()->SemanticDC;
443 }
444 const DeclContext *getDeclContext() const {
445 return const_cast<Decl*>(this)->getDeclContext();
446 }
447
448 /// Find the innermost non-closure ancestor of this declaration,
449 /// walking up through blocks, lambdas, etc. If that ancestor is
450 /// not a code context (!isFunctionOrMethod()), returns null.
451 ///
452 /// A declaration may be its own non-closure context.
453 Decl *getNonClosureContext();
454 const Decl *getNonClosureContext() const {
455 return const_cast<Decl*>(this)->getNonClosureContext();
456 }
457
458 TranslationUnitDecl *getTranslationUnitDecl();
459 const TranslationUnitDecl *getTranslationUnitDecl() const {
460 return const_cast<Decl*>(this)->getTranslationUnitDecl();
461 }
462
463 bool isInAnonymousNamespace() const;
464
465 bool isInStdNamespace() const;
466
467 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
468
469 /// Helper to get the language options from the ASTContext.
470 /// Defined out of line to avoid depending on ASTContext.h.
471 const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__));
472
473 void setAccess(AccessSpecifier AS) {
474 Access = AS;
475 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 475, __PRETTY_FUNCTION__))
;
476 }
477
478 AccessSpecifier getAccess() const {
479 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 479, __PRETTY_FUNCTION__))
;
480 return AccessSpecifier(Access);
481 }
482
483 /// Retrieve the access specifier for this declaration, even though
484 /// it may not yet have been properly set.
485 AccessSpecifier getAccessUnsafe() const {
486 return AccessSpecifier(Access);
487 }
488
489 bool hasAttrs() const { return HasAttrs; }
490
491 void setAttrs(const AttrVec& Attrs) {
492 return setAttrsImpl(Attrs, getASTContext());
493 }
494
495 AttrVec &getAttrs() {
496 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
497 }
498
499 const AttrVec &getAttrs() const;
500 void dropAttrs();
501 void addAttr(Attr *A);
502
503 using attr_iterator = AttrVec::const_iterator;
504 using attr_range = llvm::iterator_range<attr_iterator>;
505
506 attr_range attrs() const {
507 return attr_range(attr_begin(), attr_end());
508 }
509
510 attr_iterator attr_begin() const {
511 return hasAttrs() ? getAttrs().begin() : nullptr;
512 }
513 attr_iterator attr_end() const {
514 return hasAttrs() ? getAttrs().end() : nullptr;
515 }
516
517 template <typename T>
518 void dropAttr() {
519 if (!HasAttrs) return;
520
521 AttrVec &Vec = getAttrs();
522 llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); });
523
524 if (Vec.empty())
525 HasAttrs = false;
526 }
527
528 template <typename T>
529 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
530 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_begin() const {
535 return specific_attr_iterator<T>(attr_begin());
536 }
537
538 template <typename T>
539 specific_attr_iterator<T> specific_attr_end() const {
540 return specific_attr_iterator<T>(attr_end());
541 }
542
543 template<typename T> T *getAttr() const {
544 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
545 }
546
547 template<typename T> bool hasAttr() const {
548 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
2
Assuming the condition is false
3
Returning zero, which participates in a condition later
6
Returning zero, which participates in a condition later
549 }
550
551 /// getMaxAlignment - return the maximum alignment specified by attributes
552 /// on this decl, 0 if there are none.
553 unsigned getMaxAlignment() const;
554
555 /// setInvalidDecl - Indicates the Decl had a semantic error. This
556 /// allows for graceful error recovery.
557 void setInvalidDecl(bool Invalid = true);
558 bool isInvalidDecl() const { return (bool) InvalidDecl; }
559
560 /// isImplicit - Indicates whether the declaration was implicitly
561 /// generated by the implementation. If false, this declaration
562 /// was written explicitly in the source code.
563 bool isImplicit() const { return Implicit; }
564 void setImplicit(bool I = true) { Implicit = I; }
565
566 /// Whether *any* (re-)declaration of the entity was used, meaning that
567 /// a definition is required.
568 ///
569 /// \param CheckUsedAttr When true, also consider the "used" attribute
570 /// (in addition to the "used" bit set by \c setUsed()) when determining
571 /// whether the function is used.
572 bool isUsed(bool CheckUsedAttr = true) const;
573
574 /// Set whether the declaration is used, in the sense of odr-use.
575 ///
576 /// This should only be used immediately after creating a declaration.
577 /// It intentionally doesn't notify any listeners.
578 void setIsUsed() { getCanonicalDecl()->Used = true; }
579
580 /// Mark the declaration used, in the sense of odr-use.
581 ///
582 /// This notifies any mutation listeners in addition to setting a bit
583 /// indicating the declaration is used.
584 void markUsed(ASTContext &C);
585
586 /// Whether any declaration of this entity was referenced.
587 bool isReferenced() const;
588
589 /// Whether this declaration was referenced. This should not be relied
590 /// upon for anything other than debugging.
591 bool isThisDeclarationReferenced() const { return Referenced; }
592
593 void setReferenced(bool R = true) { Referenced = R; }
594
595 /// Whether this declaration is a top-level declaration (function,
596 /// global variable, etc.) that is lexically inside an objc container
597 /// definition.
598 bool isTopLevelDeclInObjCContainer() const {
599 return TopLevelDeclInObjCContainer;
600 }
601
602 void setTopLevelDeclInObjCContainer(bool V = true) {
603 TopLevelDeclInObjCContainer = V;
604 }
605
606 /// Looks on this and related declarations for an applicable
607 /// external source symbol attribute.
608 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
609
610 /// Whether this declaration was marked as being private to the
611 /// module in which it was defined.
612 bool isModulePrivate() const {
613 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
614 }
615
616 /// Return true if this declaration has an attribute which acts as
617 /// definition of the entity, such as 'alias' or 'ifunc'.
618 bool hasDefiningAttr() const;
619
620 /// Return this declaration's defining attribute if it has one.
621 const Attr *getDefiningAttr() const;
622
623protected:
624 /// Specify that this declaration was marked as being private
625 /// to the module in which it was defined.
626 void setModulePrivate() {
627 // The module-private specifier has no effect on unowned declarations.
628 // FIXME: We should track this in some way for source fidelity.
629 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
630 return;
631 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
632 }
633
634public:
635 /// Set the FromASTFile flag. This indicates that this declaration
636 /// was deserialized and not parsed from source code and enables
637 /// features such as module ownership information.
638 void setFromASTFile() {
639 FromASTFile = true;
640 }
641
642 /// Set the owning module ID. This may only be called for
643 /// deserialized Decls.
644 void setOwningModuleID(unsigned ID) {
645 assert(isFromASTFile() && "Only works on a deserialized declaration")((isFromASTFile() && "Only works on a deserialized declaration"
) ? static_cast<void> (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 645, __PRETTY_FUNCTION__))
;
646 *((unsigned*)this - 2) = ID;
647 }
648
649public:
650 /// Determine the availability of the given declaration.
651 ///
652 /// This routine will determine the most restrictive availability of
653 /// the given declaration (e.g., preferring 'unavailable' to
654 /// 'deprecated').
655 ///
656 /// \param Message If non-NULL and the result is not \c
657 /// AR_Available, will be set to a (possibly empty) message
658 /// describing why the declaration has not been introduced, is
659 /// deprecated, or is unavailable.
660 ///
661 /// \param EnclosingVersion The version to compare with. If empty, assume the
662 /// deployment target version.
663 ///
664 /// \param RealizedPlatform If non-NULL and the availability result is found
665 /// in an available attribute it will set to the platform which is written in
666 /// the available attribute.
667 AvailabilityResult
668 getAvailability(std::string *Message = nullptr,
669 VersionTuple EnclosingVersion = VersionTuple(),
670 StringRef *RealizedPlatform = nullptr) const;
671
672 /// Retrieve the version of the target platform in which this
673 /// declaration was introduced.
674 ///
675 /// \returns An empty version tuple if this declaration has no 'introduced'
676 /// availability attributes, or the version tuple that's specified in the
677 /// attribute otherwise.
678 VersionTuple getVersionIntroduced() const;
679
680 /// Determine whether this declaration is marked 'deprecated'.
681 ///
682 /// \param Message If non-NULL and the declaration is deprecated,
683 /// this will be set to the message describing why the declaration
684 /// was deprecated (which may be empty).
685 bool isDeprecated(std::string *Message = nullptr) const {
686 return getAvailability(Message) == AR_Deprecated;
687 }
688
689 /// Determine whether this declaration is marked 'unavailable'.
690 ///
691 /// \param Message If non-NULL and the declaration is unavailable,
692 /// this will be set to the message describing why the declaration
693 /// was made unavailable (which may be empty).
694 bool isUnavailable(std::string *Message = nullptr) const {
695 return getAvailability(Message) == AR_Unavailable;
696 }
697
698 /// Determine whether this is a weak-imported symbol.
699 ///
700 /// Weak-imported symbols are typically marked with the
701 /// 'weak_import' attribute, but may also be marked with an
702 /// 'availability' attribute where we're targing a platform prior to
703 /// the introduction of this feature.
704 bool isWeakImported() const;
705
706 /// Determines whether this symbol can be weak-imported,
707 /// e.g., whether it would be well-formed to add the weak_import
708 /// attribute.
709 ///
710 /// \param IsDefinition Set to \c true to indicate that this
711 /// declaration cannot be weak-imported because it has a definition.
712 bool canBeWeakImported(bool &IsDefinition) const;
713
714 /// Determine whether this declaration came from an AST file (such as
715 /// a precompiled header or module) rather than having been parsed.
716 bool isFromASTFile() const { return FromASTFile; }
717
718 /// Retrieve the global declaration ID associated with this
719 /// declaration, which specifies where this Decl was loaded from.
720 unsigned getGlobalID() const {
721 if (isFromASTFile())
722 return *((const unsigned*)this - 1);
723 return 0;
724 }
725
726 /// Retrieve the global ID of the module that owns this particular
727 /// declaration.
728 unsigned getOwningModuleID() const {
729 if (isFromASTFile())
730 return *((const unsigned*)this - 2);
731 return 0;
732 }
733
734private:
735 Module *getOwningModuleSlow() const;
736
737protected:
738 bool hasLocalOwningModuleStorage() const;
739
740public:
741 /// Get the imported owning module, if this decl is from an imported
742 /// (non-local) module.
743 Module *getImportedOwningModule() const {
744 if (!isFromASTFile() || !hasOwningModule())
745 return nullptr;
746
747 return getOwningModuleSlow();
748 }
749
750 /// Get the local owning module, if known. Returns nullptr if owner is
751 /// not yet known or declaration is not from a module.
752 Module *getLocalOwningModule() const {
753 if (isFromASTFile() || !hasOwningModule())
754 return nullptr;
755
756 assert(hasLocalOwningModuleStorage() &&((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 757, __PRETTY_FUNCTION__))
757 "owned local decl but no local module storage")((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 757, __PRETTY_FUNCTION__))
;
758 return reinterpret_cast<Module *const *>(this)[-1];
759 }
760 void setLocalOwningModule(Module *M) {
761 assert(!isFromASTFile() && hasOwningModule() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 763, __PRETTY_FUNCTION__))
762 hasLocalOwningModuleStorage() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 763, __PRETTY_FUNCTION__))
763 "should not have a cached owning module")((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 763, __PRETTY_FUNCTION__))
;
764 reinterpret_cast<Module **>(this)[-1] = M;
765 }
766
767 /// Is this declaration owned by some module?
768 bool hasOwningModule() const {
769 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
770 }
771
772 /// Get the module that owns this declaration (for visibility purposes).
773 Module *getOwningModule() const {
774 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
775 }
776
777 /// Get the module that owns this declaration for linkage purposes.
778 /// There only ever is such a module under the C++ Modules TS.
779 ///
780 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
781 /// all declarations in a global module fragment are unowned.
782 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
783
784 /// Determine whether this declaration is definitely visible to name lookup,
785 /// independent of whether the owning module is visible.
786 /// Note: The declaration may be visible even if this returns \c false if the
787 /// owning module is visible within the query context. This is a low-level
788 /// helper function; most code should be calling Sema::isVisible() instead.
789 bool isUnconditionallyVisible() const {
790 return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
791 }
792
793 /// Set that this declaration is globally visible, even if it came from a
794 /// module that is not visible.
795 void setVisibleDespiteOwningModule() {
796 if (!isUnconditionallyVisible())
797 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
798 }
799
800 /// Get the kind of module ownership for this declaration.
801 ModuleOwnershipKind getModuleOwnershipKind() const {
802 return NextInContextAndBits.getInt();
803 }
804
805 /// Set whether this declaration is hidden from name lookup.
806 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
807 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
808 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
809 !hasLocalOwningModuleStorage()) &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
810 "no storage available for owning module for this declaration")((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
;
811 NextInContextAndBits.setInt(MOK);
812 }
813
814 unsigned getIdentifierNamespace() const {
815 return IdentifierNamespace;
816 }
817
818 bool isInIdentifierNamespace(unsigned NS) const {
819 return getIdentifierNamespace() & NS;
820 }
821
822 static unsigned getIdentifierNamespaceForKind(Kind DK);
823
824 bool hasTagIdentifierNamespace() const {
825 return isTagIdentifierNamespace(getIdentifierNamespace());
826 }
827
828 static bool isTagIdentifierNamespace(unsigned NS) {
829 // TagDecls have Tag and Type set and may also have TagFriend.
830 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
831 }
832
833 /// getLexicalDeclContext - The declaration context where this Decl was
834 /// lexically declared (LexicalDC). May be different from
835 /// getDeclContext() (SemanticDC).
836 /// e.g.:
837 ///
838 /// namespace A {
839 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
840 /// }
841 /// void A::f(); // SemanticDC == namespace 'A'
842 /// // LexicalDC == global namespace
843 DeclContext *getLexicalDeclContext() {
844 if (isInSemaDC())
845 return getSemanticDC();
846 return getMultipleDC()->LexicalDC;
847 }
848 const DeclContext *getLexicalDeclContext() const {
849 return const_cast<Decl*>(this)->getLexicalDeclContext();
850 }
851
852 /// Determine whether this declaration is declared out of line (outside its
853 /// semantic context).
854 virtual bool isOutOfLine() const;
855
856 /// setDeclContext - Set both the semantic and lexical DeclContext
857 /// to DC.
858 void setDeclContext(DeclContext *DC);
859
860 void setLexicalDeclContext(DeclContext *DC);
861
862 /// Determine whether this declaration is a templated entity (whether it is
863 // within the scope of a template parameter).
864 bool isTemplated() const;
865
866 /// Determine the number of levels of template parameter surrounding this
867 /// declaration.
868 unsigned getTemplateDepth() const;
869
870 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
871 /// scoped decl is defined outside the current function or method. This is
872 /// roughly global variables and functions, but also handles enums (which
873 /// could be defined inside or outside a function etc).
874 bool isDefinedOutsideFunctionOrMethod() const {
875 return getParentFunctionOrMethod() == nullptr;
876 }
877
878 /// Determine whether a substitution into this declaration would occur as
879 /// part of a substitution into a dependent local scope. Such a substitution
880 /// transitively substitutes into all constructs nested within this
881 /// declaration.
882 ///
883 /// This recognizes non-defining declarations as well as members of local
884 /// classes and lambdas:
885 /// \code
886 /// template<typename T> void foo() { void bar(); }
887 /// template<typename T> void foo2() { class ABC { void bar(); }; }
888 /// template<typename T> inline int x = [](){ return 0; }();
889 /// \endcode
890 bool isInLocalScopeForInstantiation() const;
891
892 /// If this decl is defined inside a function/method/block it returns
893 /// the corresponding DeclContext, otherwise it returns null.
894 const DeclContext *getParentFunctionOrMethod() const;
895 DeclContext *getParentFunctionOrMethod() {
896 return const_cast<DeclContext*>(
897 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
898 }
899
900 /// Retrieves the "canonical" declaration of the given declaration.
901 virtual Decl *getCanonicalDecl() { return this; }
902 const Decl *getCanonicalDecl() const {
903 return const_cast<Decl*>(this)->getCanonicalDecl();
904 }
905
906 /// Whether this particular Decl is a canonical one.
907 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
908
909protected:
910 /// Returns the next redeclaration or itself if this is the only decl.
911 ///
912 /// Decl subclasses that can be redeclared should override this method so that
913 /// Decl::redecl_iterator can iterate over them.
914 virtual Decl *getNextRedeclarationImpl() { return this; }
915
916 /// Implementation of getPreviousDecl(), to be overridden by any
917 /// subclass that has a redeclaration chain.
918 virtual Decl *getPreviousDeclImpl() { return nullptr; }
919
920 /// Implementation of getMostRecentDecl(), to be overridden by any
921 /// subclass that has a redeclaration chain.
922 virtual Decl *getMostRecentDeclImpl() { return this; }
923
924public:
925 /// Iterates through all the redeclarations of the same decl.
926 class redecl_iterator {
927 /// Current - The current declaration.
928 Decl *Current = nullptr;
929 Decl *Starter;
930
931 public:
932 using value_type = Decl *;
933 using reference = const value_type &;
934 using pointer = const value_type *;
935 using iterator_category = std::forward_iterator_tag;
936 using difference_type = std::ptrdiff_t;
937
938 redecl_iterator() = default;
939 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
940
941 reference operator*() const { return Current; }
942 value_type operator->() const { return Current; }
943
944 redecl_iterator& operator++() {
945 assert(Current && "Advancing while iterator has reached end")((Current && "Advancing while iterator has reached end"
) ? static_cast<void> (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 945, __PRETTY_FUNCTION__))
;
946 // Get either previous decl or latest decl.
947 Decl *Next = Current->getNextRedeclarationImpl();
948 assert(Next && "Should return next redeclaration or itself, never null!")((Next && "Should return next redeclaration or itself, never null!"
) ? static_cast<void> (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 948, __PRETTY_FUNCTION__))
;
949 Current = (Next != Starter) ? Next : nullptr;
950 return *this;
951 }
952
953 redecl_iterator operator++(int) {
954 redecl_iterator tmp(*this);
955 ++(*this);
956 return tmp;
957 }
958
959 friend bool operator==(redecl_iterator x, redecl_iterator y) {
960 return x.Current == y.Current;
961 }
962
963 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
964 return x.Current != y.Current;
965 }
966 };
967
968 using redecl_range = llvm::iterator_range<redecl_iterator>;
969
970 /// Returns an iterator range for all the redeclarations of the same
971 /// decl. It will iterate at least once (when this decl is the only one).
972 redecl_range redecls() const {
973 return redecl_range(redecls_begin(), redecls_end());
974 }
975
976 redecl_iterator redecls_begin() const {
977 return redecl_iterator(const_cast<Decl *>(this));
978 }
979
980 redecl_iterator redecls_end() const { return redecl_iterator(); }
981
982 /// Retrieve the previous declaration that declares the same entity
983 /// as this declaration, or NULL if there is no previous declaration.
984 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
985
986 /// Retrieve the previous declaration that declares the same entity
987 /// as this declaration, or NULL if there is no previous declaration.
988 const Decl *getPreviousDecl() const {
989 return const_cast<Decl *>(this)->getPreviousDeclImpl();
990 }
991
992 /// True if this is the first declaration in its redeclaration chain.
993 bool isFirstDecl() const {
994 return getPreviousDecl() == nullptr;
995 }
996
997 /// Retrieve the most recent declaration that declares the same entity
998 /// as this declaration (which may be this declaration).
999 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
1000
1001 /// Retrieve the most recent declaration that declares the same entity
1002 /// as this declaration (which may be this declaration).
1003 const Decl *getMostRecentDecl() const {
1004 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
1005 }
1006
1007 /// getBody - If this Decl represents a declaration for a body of code,
1008 /// such as a function or method definition, this method returns the
1009 /// top-level Stmt* of that body. Otherwise this method returns null.
1010 virtual Stmt* getBody() const { return nullptr; }
1011
1012 /// Returns true if this \c Decl represents a declaration for a body of
1013 /// code, such as a function or method definition.
1014 /// Note that \c hasBody can also return true if any redeclaration of this
1015 /// \c Decl represents a declaration for a body of code.
1016 virtual bool hasBody() const { return getBody() != nullptr; }
1017
1018 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
1019 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
1020 SourceLocation getBodyRBrace() const;
1021
1022 // global temp stats (until we have a per-module visitor)
1023 static void add(Kind k);
1024 static void EnableStatistics();
1025 static void PrintStats();
1026
1027 /// isTemplateParameter - Determines whether this declaration is a
1028 /// template parameter.
1029 bool isTemplateParameter() const;
1030
1031 /// isTemplateParameter - Determines whether this declaration is a
1032 /// template parameter pack.
1033 bool isTemplateParameterPack() const;
1034
1035 /// Whether this declaration is a parameter pack.
1036 bool isParameterPack() const;
1037
1038 /// returns true if this declaration is a template
1039 bool isTemplateDecl() const;
1040
1041 /// Whether this declaration is a function or function template.
1042 bool isFunctionOrFunctionTemplate() const {
1043 return (DeclKind >= Decl::firstFunction &&
1044 DeclKind <= Decl::lastFunction) ||
1045 DeclKind == FunctionTemplate;
1046 }
1047
1048 /// If this is a declaration that describes some template, this
1049 /// method returns that template declaration.
1050 ///
1051 /// Note that this returns nullptr for partial specializations, because they
1052 /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
1053 /// those cases.
1054 TemplateDecl *getDescribedTemplate() const;
1055
1056 /// If this is a declaration that describes some template or partial
1057 /// specialization, this returns the corresponding template parameter list.
1058 const TemplateParameterList *getDescribedTemplateParams() const;
1059
1060 /// Returns the function itself, or the templated function if this is a
1061 /// function template.
1062 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1063
1064 const FunctionDecl *getAsFunction() const {
1065 return const_cast<Decl *>(this)->getAsFunction();
1066 }
1067
1068 /// Changes the namespace of this declaration to reflect that it's
1069 /// a function-local extern declaration.
1070 ///
1071 /// These declarations appear in the lexical context of the extern
1072 /// declaration, but in the semantic context of the enclosing namespace
1073 /// scope.
1074 void setLocalExternDecl() {
1075 Decl *Prev = getPreviousDecl();
1076 IdentifierNamespace &= ~IDNS_Ordinary;
1077
1078 // It's OK for the declaration to still have the "invisible friend" flag or
1079 // the "conflicts with tag declarations in this scope" flag for the outer
1080 // scope.
1081 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag
)) == 0 && "namespace is not ordinary") ? static_cast
<void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1082, __PRETTY_FUNCTION__))
1082 "namespace is not ordinary")(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag
)) == 0 && "namespace is not ordinary") ? static_cast
<void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1082, __PRETTY_FUNCTION__))
;
1083
1084 IdentifierNamespace |= IDNS_LocalExtern;
1085 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1086 IdentifierNamespace |= IDNS_Ordinary;
1087 }
1088
1089 /// Determine whether this is a block-scope declaration with linkage.
1090 /// This will either be a local variable declaration declared 'extern', or a
1091 /// local function declaration.
1092 bool isLocalExternDecl() {
1093 return IdentifierNamespace & IDNS_LocalExtern;
1094 }
1095
1096 /// Changes the namespace of this declaration to reflect that it's
1097 /// the object of a friend declaration.
1098 ///
1099 /// These declarations appear in the lexical context of the friending
1100 /// class, but in the semantic context of the actual entity. This property
1101 /// applies only to a specific decl object; other redeclarations of the
1102 /// same entity may not (and probably don't) share this property.
1103 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1104 unsigned OldNS = IdentifierNamespace;
1105 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
1106 IDNS_TagFriend | IDNS_OrdinaryFriend |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
1107 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
1108 "namespace includes neither ordinary nor tag")(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
;
1109 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
1110 IDNS_TagFriend | IDNS_OrdinaryFriend |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
1111 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
1112 "namespace includes other than ordinary or tag")((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
;
1113
1114 Decl *Prev = getPreviousDecl();
1115 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1116
1117 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1118 IdentifierNamespace |= IDNS_TagFriend;
1119 if (PerformFriendInjection ||
1120 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1121 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1122 }
1123
1124 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1125 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1126 IdentifierNamespace |= IDNS_OrdinaryFriend;
1127 if (PerformFriendInjection ||
1128 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1129 IdentifierNamespace |= IDNS_Ordinary;
1130 }
1131 }
1132
1133 enum FriendObjectKind {
1134 FOK_None, ///< Not a friend object.
1135 FOK_Declared, ///< A friend of a previously-declared entity.
1136 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1137 };
1138
1139 /// Determines whether this declaration is the object of a
1140 /// friend declaration and, if so, what kind.
1141 ///
1142 /// There is currently no direct way to find the associated FriendDecl.
1143 FriendObjectKind getFriendObjectKind() const {
1144 unsigned mask =
1145 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1146 if (!mask) return FOK_None;
1147 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1148 : FOK_Undeclared);
1149 }
1150
1151 /// Specifies that this declaration is a C++ overloaded non-member.
1152 void setNonMemberOperator() {
1153 assert(getKind() == Function || getKind() == FunctionTemplate)((getKind() == Function || getKind() == FunctionTemplate) ? static_cast
<void> (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1153, __PRETTY_FUNCTION__))
;
1154 assert((IdentifierNamespace & IDNS_Ordinary) &&(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace"
) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1155, __PRETTY_FUNCTION__))
1155 "visible non-member operators should be in ordinary namespace")(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace"
) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 1155, __PRETTY_FUNCTION__))
;
1156 IdentifierNamespace |= IDNS_NonMemberOperator;
1157 }
1158
1159 static bool classofKind(Kind K) { return true; }
1160 static DeclContext *castToDeclContext(const Decl *);
1161 static Decl *castFromDeclContext(const DeclContext *);
1162
1163 void print(raw_ostream &Out, unsigned Indentation = 0,
1164 bool PrintInstantiation = false) const;
1165 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1166 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1167 static void printGroup(Decl** Begin, unsigned NumDecls,
1168 raw_ostream &Out, const PrintingPolicy &Policy,
1169 unsigned Indentation = 0);
1170
1171 // Debuggers don't usually respect default arguments.
1172 void dump() const;
1173
1174 // Same as dump(), but forces color printing.
1175 void dumpColor() const;
1176
1177 void dump(raw_ostream &Out, bool Deserialize = false,
1178 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1179
1180 /// \return Unique reproducible object identifier
1181 int64_t getID() const;
1182
1183 /// Looks through the Decl's underlying type to extract a FunctionType
1184 /// when possible. Will return null if the type underlying the Decl does not
1185 /// have a FunctionType.
1186 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1187
1188private:
1189 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1190 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1191 ASTContext &Ctx);
1192
1193protected:
1194 ASTMutationListener *getASTMutationListener() const;
1195};
1196
1197/// Determine whether two declarations declare the same entity.
1198inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1199 if (!D1 || !D2)
1200 return false;
1201
1202 if (D1 == D2)
1203 return true;
1204
1205 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1206}
1207
1208/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1209/// doing something to a specific decl.
1210class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1211 const Decl *TheDecl;
1212 SourceLocation Loc;
1213 SourceManager &SM;
1214 const char *Message;
1215
1216public:
1217 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1218 SourceManager &sm, const char *Msg)
1219 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1220
1221 void print(raw_ostream &OS) const override;
1222};
1223
1224/// The results of name lookup within a DeclContext. This is either a
1225/// single result (with no stable storage) or a collection of results (with
1226/// stable storage provided by the lookup table).
1227class DeclContextLookupResult {
1228 using ResultTy = ArrayRef<NamedDecl *>;
1229
1230 ResultTy Result;
1231
1232 // If there is only one lookup result, it would be invalidated by
1233 // reallocations of the name table, so store it separately.
1234 NamedDecl *Single = nullptr;
1235
1236 static NamedDecl *const SingleElementDummyList;
1237
1238public:
1239 DeclContextLookupResult() = default;
1240 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1241 : Result(Result) {}
1242 DeclContextLookupResult(NamedDecl *Single)
1243 : Result(SingleElementDummyList), Single(Single) {}
1244
1245 class iterator;
1246
1247 using IteratorBase =
1248 llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1249 std::random_access_iterator_tag, NamedDecl *>;
1250
1251 class iterator : public IteratorBase {
1252 value_type SingleElement;
1253
1254 public:
1255 explicit iterator(pointer Pos, value_type Single = nullptr)
1256 : IteratorBase(Pos), SingleElement(Single) {}
1257
1258 reference operator*() const {
1259 return SingleElement ? SingleElement : IteratorBase::operator*();
1260 }
1261 };
1262
1263 using const_iterator = iterator;
1264 using pointer = iterator::pointer;
1265 using reference = iterator::reference;
1266
1267 iterator begin() const { return iterator(Result.begin(), Single); }
1268 iterator end() const { return iterator(Result.end(), Single); }
1269
1270 bool empty() const { return Result.empty(); }
1271 pointer data() const { return Single ? &Single : Result.data(); }
1272 size_t size() const { return Single ? 1 : Result.size(); }
1273 reference front() const { return Single ? Single : Result.front(); }
1274 reference back() const { return Single ? Single : Result.back(); }
1275 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1276
1277 // FIXME: Remove this from the interface
1278 DeclContextLookupResult slice(size_t N) const {
1279 DeclContextLookupResult Sliced = Result.slice(N);
1280 Sliced.Single = Single;
1281 return Sliced;
1282 }
1283};
1284
1285/// DeclContext - This is used only as base class of specific decl types that
1286/// can act as declaration contexts. These decls are (only the top classes
1287/// that directly derive from DeclContext are mentioned, not their subclasses):
1288///
1289/// TranslationUnitDecl
1290/// ExternCContext
1291/// NamespaceDecl
1292/// TagDecl
1293/// OMPDeclareReductionDecl
1294/// OMPDeclareMapperDecl
1295/// FunctionDecl
1296/// ObjCMethodDecl
1297/// ObjCContainerDecl
1298/// LinkageSpecDecl
1299/// ExportDecl
1300/// BlockDecl
1301/// CapturedDecl
1302class DeclContext {
1303 /// For makeDeclVisibleInContextImpl
1304 friend class ASTDeclReader;
1305 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1306 /// hasNeedToReconcileExternalVisibleStorage
1307 friend class ExternalASTSource;
1308 /// For CreateStoredDeclsMap
1309 friend class DependentDiagnostic;
1310 /// For hasNeedToReconcileExternalVisibleStorage,
1311 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1312 friend class ASTWriter;
1313
1314 // We use uint64_t in the bit-fields below since some bit-fields
1315 // cross the unsigned boundary and this breaks the packing.
1316
1317 /// Stores the bits used by DeclContext.
1318 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1319 /// methods in DeclContext should be updated appropriately.
1320 class DeclContextBitfields {
1321 friend class DeclContext;
1322 /// DeclKind - This indicates which class this is.
1323 uint64_t DeclKind : 7;
1324
1325 /// Whether this declaration context also has some external
1326 /// storage that contains additional declarations that are lexically
1327 /// part of this context.
1328 mutable uint64_t ExternalLexicalStorage : 1;
1329
1330 /// Whether this declaration context also has some external
1331 /// storage that contains additional declarations that are visible
1332 /// in this context.
1333 mutable uint64_t ExternalVisibleStorage : 1;
1334
1335 /// Whether this declaration context has had externally visible
1336 /// storage added since the last lookup. In this case, \c LookupPtr's
1337 /// invariant may not hold and needs to be fixed before we perform
1338 /// another lookup.
1339 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1340
1341 /// If \c true, this context may have local lexical declarations
1342 /// that are missing from the lookup table.
1343 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1344
1345 /// If \c true, the external source may have lexical declarations
1346 /// that are missing from the lookup table.
1347 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1348
1349 /// If \c true, lookups should only return identifier from
1350 /// DeclContext scope (for example TranslationUnit). Used in
1351 /// LookupQualifiedName()
1352 mutable uint64_t UseQualifiedLookup : 1;
1353 };
1354
1355 /// Number of bits in DeclContextBitfields.
1356 enum { NumDeclContextBits = 13 };
1357
1358 /// Stores the bits used by TagDecl.
1359 /// If modified NumTagDeclBits and the accessor
1360 /// methods in TagDecl should be updated appropriately.
1361 class TagDeclBitfields {
1362 friend class TagDecl;
1363 /// For the bits in DeclContextBitfields
1364 uint64_t : NumDeclContextBits;
1365
1366 /// The TagKind enum.
1367 uint64_t TagDeclKind : 3;
1368
1369 /// True if this is a definition ("struct foo {};"), false if it is a
1370 /// declaration ("struct foo;"). It is not considered a definition
1371 /// until the definition has been fully processed.
1372 uint64_t IsCompleteDefinition : 1;
1373
1374 /// True if this is currently being defined.
1375 uint64_t IsBeingDefined : 1;
1376
1377 /// True if this tag declaration is "embedded" (i.e., defined or declared
1378 /// for the very first time) in the syntax of a declarator.
1379 uint64_t IsEmbeddedInDeclarator : 1;
1380
1381 /// True if this tag is free standing, e.g. "struct foo;".
1382 uint64_t IsFreeStanding : 1;
1383
1384 /// Indicates whether it is possible for declarations of this kind
1385 /// to have an out-of-date definition.
1386 ///
1387 /// This option is only enabled when modules are enabled.
1388 uint64_t MayHaveOutOfDateDef : 1;
1389
1390 /// Has the full definition of this type been required by a use somewhere in
1391 /// the TU.
1392 uint64_t IsCompleteDefinitionRequired : 1;
1393 };
1394
1395 /// Number of non-inherited bits in TagDeclBitfields.
1396 enum { NumTagDeclBits = 9 };
1397
1398 /// Stores the bits used by EnumDecl.
1399 /// If modified NumEnumDeclBit and the accessor
1400 /// methods in EnumDecl should be updated appropriately.
1401 class EnumDeclBitfields {
1402 friend class EnumDecl;
1403 /// For the bits in DeclContextBitfields.
1404 uint64_t : NumDeclContextBits;
1405 /// For the bits in TagDeclBitfields.
1406 uint64_t : NumTagDeclBits;
1407
1408 /// Width in bits required to store all the non-negative
1409 /// enumerators of this enum.
1410 uint64_t NumPositiveBits : 8;
1411
1412 /// Width in bits required to store all the negative
1413 /// enumerators of this enum.
1414 uint64_t NumNegativeBits : 8;
1415
1416 /// True if this tag declaration is a scoped enumeration. Only
1417 /// possible in C++11 mode.
1418 uint64_t IsScoped : 1;
1419
1420 /// If this tag declaration is a scoped enum,
1421 /// then this is true if the scoped enum was declared using the class
1422 /// tag, false if it was declared with the struct tag. No meaning is
1423 /// associated if this tag declaration is not a scoped enum.
1424 uint64_t IsScopedUsingClassTag : 1;
1425
1426 /// True if this is an enumeration with fixed underlying type. Only
1427 /// possible in C++11, Microsoft extensions, or Objective C mode.
1428 uint64_t IsFixed : 1;
1429
1430 /// True if a valid hash is stored in ODRHash.
1431 uint64_t HasODRHash : 1;
1432 };
1433
1434 /// Number of non-inherited bits in EnumDeclBitfields.
1435 enum { NumEnumDeclBits = 20 };
1436
1437 /// Stores the bits used by RecordDecl.
1438 /// If modified NumRecordDeclBits and the accessor
1439 /// methods in RecordDecl should be updated appropriately.
1440 class RecordDeclBitfields {
1441 friend class RecordDecl;
1442 /// For the bits in DeclContextBitfields.
1443 uint64_t : NumDeclContextBits;
1444 /// For the bits in TagDeclBitfields.
1445 uint64_t : NumTagDeclBits;
1446
1447 /// This is true if this struct ends with a flexible
1448 /// array member (e.g. int X[]) or if this union contains a struct that does.
1449 /// If so, this cannot be contained in arrays or other structs as a member.
1450 uint64_t HasFlexibleArrayMember : 1;
1451
1452 /// Whether this is the type of an anonymous struct or union.
1453 uint64_t AnonymousStructOrUnion : 1;
1454
1455 /// This is true if this struct has at least one member
1456 /// containing an Objective-C object pointer type.
1457 uint64_t HasObjectMember : 1;
1458
1459 /// This is true if struct has at least one member of
1460 /// 'volatile' type.
1461 uint64_t HasVolatileMember : 1;
1462
1463 /// Whether the field declarations of this record have been loaded
1464 /// from external storage. To avoid unnecessary deserialization of
1465 /// methods/nested types we allow deserialization of just the fields
1466 /// when needed.
1467 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1468
1469 /// Basic properties of non-trivial C structs.
1470 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1471 uint64_t NonTrivialToPrimitiveCopy : 1;
1472 uint64_t NonTrivialToPrimitiveDestroy : 1;
1473
1474 /// The following bits indicate whether this is or contains a C union that
1475 /// is non-trivial to default-initialize, destruct, or copy. These bits
1476 /// imply the associated basic non-triviality predicates declared above.
1477 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1478 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1479 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1480
1481 /// Indicates whether this struct is destroyed in the callee.
1482 uint64_t ParamDestroyedInCallee : 1;
1483
1484 /// Represents the way this type is passed to a function.
1485 uint64_t ArgPassingRestrictions : 2;
1486 };
1487
1488 /// Number of non-inherited bits in RecordDeclBitfields.
1489 enum { NumRecordDeclBits = 14 };
1490
1491 /// Stores the bits used by OMPDeclareReductionDecl.
1492 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1493 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1494 class OMPDeclareReductionDeclBitfields {
1495 friend class OMPDeclareReductionDecl;
1496 /// For the bits in DeclContextBitfields
1497 uint64_t : NumDeclContextBits;
1498
1499 /// Kind of initializer,
1500 /// function call or omp_priv<init_expr> initializtion.
1501 uint64_t InitializerKind : 2;
1502 };
1503
1504 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1505 enum { NumOMPDeclareReductionDeclBits = 2 };
1506
1507 /// Stores the bits used by FunctionDecl.
1508 /// If modified NumFunctionDeclBits and the accessor
1509 /// methods in FunctionDecl and CXXDeductionGuideDecl
1510 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1511 class FunctionDeclBitfields {
1512 friend class FunctionDecl;
1513 /// For IsCopyDeductionCandidate
1514 friend class CXXDeductionGuideDecl;
1515 /// For the bits in DeclContextBitfields.
1516 uint64_t : NumDeclContextBits;
1517
1518 uint64_t SClass : 3;
1519 uint64_t IsInline : 1;
1520 uint64_t IsInlineSpecified : 1;
1521
1522 uint64_t IsVirtualAsWritten : 1;
1523 uint64_t IsPure : 1;
1524 uint64_t HasInheritedPrototype : 1;
1525 uint64_t HasWrittenPrototype : 1;
1526 uint64_t IsDeleted : 1;
1527 /// Used by CXXMethodDecl
1528 uint64_t IsTrivial : 1;
1529
1530 /// This flag indicates whether this function is trivial for the purpose of
1531 /// calls. This is meaningful only when this function is a copy/move
1532 /// constructor or a destructor.
1533 uint64_t IsTrivialForCall : 1;
1534
1535 uint64_t IsDefaulted : 1;
1536 uint64_t IsExplicitlyDefaulted : 1;
1537 uint64_t HasDefaultedFunctionInfo : 1;
1538 uint64_t HasImplicitReturnZero : 1;
1539 uint64_t IsLateTemplateParsed : 1;
1540
1541 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1542 uint64_t ConstexprKind : 2;
1543 uint64_t InstantiationIsPending : 1;
1544
1545 /// Indicates if the function uses __try.
1546 uint64_t UsesSEHTry : 1;
1547
1548 /// Indicates if the function was a definition
1549 /// but its body was skipped.
1550 uint64_t HasSkippedBody : 1;
1551
1552 /// Indicates if the function declaration will
1553 /// have a body, once we're done parsing it.
1554 uint64_t WillHaveBody : 1;
1555
1556 /// Indicates that this function is a multiversioned
1557 /// function using attribute 'target'.
1558 uint64_t IsMultiVersion : 1;
1559
1560 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1561 /// the Deduction Guide is the implicitly generated 'copy
1562 /// deduction candidate' (is used during overload resolution).
1563 uint64_t IsCopyDeductionCandidate : 1;
1564
1565 /// Store the ODRHash after first calculation.
1566 uint64_t HasODRHash : 1;
1567
1568 /// Indicates if the function uses Floating Point Constrained Intrinsics
1569 uint64_t UsesFPIntrin : 1;
1570 };
1571
1572 /// Number of non-inherited bits in FunctionDeclBitfields.
1573 enum { NumFunctionDeclBits = 27 };
1574
1575 /// Stores the bits used by CXXConstructorDecl. If modified
1576 /// NumCXXConstructorDeclBits and the accessor
1577 /// methods in CXXConstructorDecl should be updated appropriately.
1578 class CXXConstructorDeclBitfields {
1579 friend class CXXConstructorDecl;
1580 /// For the bits in DeclContextBitfields.
1581 uint64_t : NumDeclContextBits;
1582 /// For the bits in FunctionDeclBitfields.
1583 uint64_t : NumFunctionDeclBits;
1584
1585 /// 24 bits to fit in the remaining available space.
1586 /// Note that this makes CXXConstructorDeclBitfields take
1587 /// exactly 64 bits and thus the width of NumCtorInitializers
1588 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1589 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1590 uint64_t NumCtorInitializers : 21;
1591 uint64_t IsInheritingConstructor : 1;
1592
1593 /// Whether this constructor has a trail-allocated explicit specifier.
1594 uint64_t HasTrailingExplicitSpecifier : 1;
1595 /// If this constructor does't have a trail-allocated explicit specifier.
1596 /// Whether this constructor is explicit specified.
1597 uint64_t IsSimpleExplicit : 1;
1598 };
1599
1600 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1601 enum {
1602 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1603 };
1604
1605 /// Stores the bits used by ObjCMethodDecl.
1606 /// If modified NumObjCMethodDeclBits and the accessor
1607 /// methods in ObjCMethodDecl should be updated appropriately.
1608 class ObjCMethodDeclBitfields {
1609 friend class ObjCMethodDecl;
1610
1611 /// For the bits in DeclContextBitfields.
1612 uint64_t : NumDeclContextBits;
1613
1614 /// The conventional meaning of this method; an ObjCMethodFamily.
1615 /// This is not serialized; instead, it is computed on demand and
1616 /// cached.
1617 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1618
1619 /// instance (true) or class (false) method.
1620 uint64_t IsInstance : 1;
1621 uint64_t IsVariadic : 1;
1622
1623 /// True if this method is the getter or setter for an explicit property.
1624 uint64_t IsPropertyAccessor : 1;
1625
1626 /// True if this method is a synthesized property accessor stub.
1627 uint64_t IsSynthesizedAccessorStub : 1;
1628
1629 /// Method has a definition.
1630 uint64_t IsDefined : 1;
1631
1632 /// Method redeclaration in the same interface.
1633 uint64_t IsRedeclaration : 1;
1634
1635 /// Is redeclared in the same interface.
1636 mutable uint64_t HasRedeclaration : 1;
1637
1638 /// \@required/\@optional
1639 uint64_t DeclImplementation : 2;
1640
1641 /// in, inout, etc.
1642 uint64_t objcDeclQualifier : 7;
1643
1644 /// Indicates whether this method has a related result type.
1645 uint64_t RelatedResultType : 1;
1646
1647 /// Whether the locations of the selector identifiers are in a
1648 /// "standard" position, a enum SelectorLocationsKind.
1649 uint64_t SelLocsKind : 2;
1650
1651 /// Whether this method overrides any other in the class hierarchy.
1652 ///
1653 /// A method is said to override any method in the class's
1654 /// base classes, its protocols, or its categories' protocols, that has
1655 /// the same selector and is of the same kind (class or instance).
1656 /// A method in an implementation is not considered as overriding the same
1657 /// method in the interface or its categories.
1658 uint64_t IsOverriding : 1;
1659
1660 /// Indicates if the method was a definition but its body was skipped.
1661 uint64_t HasSkippedBody : 1;
1662 };
1663
1664 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1665 enum { NumObjCMethodDeclBits = 24 };
1666
1667 /// Stores the bits used by ObjCContainerDecl.
1668 /// If modified NumObjCContainerDeclBits and the accessor
1669 /// methods in ObjCContainerDecl should be updated appropriately.
1670 class ObjCContainerDeclBitfields {
1671 friend class ObjCContainerDecl;
1672 /// For the bits in DeclContextBitfields
1673 uint32_t : NumDeclContextBits;
1674
1675 // Not a bitfield but this saves space.
1676 // Note that ObjCContainerDeclBitfields is full.
1677 SourceLocation AtStart;
1678 };
1679
1680 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1681 /// Note that here we rely on the fact that SourceLocation is 32 bits
1682 /// wide. We check this with the static_assert in the ctor of DeclContext.
1683 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1684
1685 /// Stores the bits used by LinkageSpecDecl.
1686 /// If modified NumLinkageSpecDeclBits and the accessor
1687 /// methods in LinkageSpecDecl should be updated appropriately.
1688 class LinkageSpecDeclBitfields {
1689 friend class LinkageSpecDecl;
1690 /// For the bits in DeclContextBitfields.
1691 uint64_t : NumDeclContextBits;
1692
1693 /// The language for this linkage specification with values
1694 /// in the enum LinkageSpecDecl::LanguageIDs.
1695 uint64_t Language : 3;
1696
1697 /// True if this linkage spec has braces.
1698 /// This is needed so that hasBraces() returns the correct result while the
1699 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1700 /// not used, so it doesn't need to be serialized.
1701 uint64_t HasBraces : 1;
1702 };
1703
1704 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1705 enum { NumLinkageSpecDeclBits = 4 };
1706
1707 /// Stores the bits used by BlockDecl.
1708 /// If modified NumBlockDeclBits and the accessor
1709 /// methods in BlockDecl should be updated appropriately.
1710 class BlockDeclBitfields {
1711 friend class BlockDecl;
1712 /// For the bits in DeclContextBitfields.
1713 uint64_t : NumDeclContextBits;
1714
1715 uint64_t IsVariadic : 1;
1716 uint64_t CapturesCXXThis : 1;
1717 uint64_t BlockMissingReturnType : 1;
1718 uint64_t IsConversionFromLambda : 1;
1719
1720 /// A bit that indicates this block is passed directly to a function as a
1721 /// non-escaping parameter.
1722 uint64_t DoesNotEscape : 1;
1723
1724 /// A bit that indicates whether it's possible to avoid coying this block to
1725 /// the heap when it initializes or is assigned to a local variable with
1726 /// automatic storage.
1727 uint64_t CanAvoidCopyToHeap : 1;
1728 };
1729
1730 /// Number of non-inherited bits in BlockDeclBitfields.
1731 enum { NumBlockDeclBits = 5 };
1732
1733 /// Pointer to the data structure used to lookup declarations
1734 /// within this context (or a DependentStoredDeclsMap if this is a
1735 /// dependent context). We maintain the invariant that, if the map
1736 /// contains an entry for a DeclarationName (and we haven't lazily
1737 /// omitted anything), then it contains all relevant entries for that
1738 /// name (modulo the hasExternalDecls() flag).
1739 mutable StoredDeclsMap *LookupPtr = nullptr;
1740
1741protected:
1742 /// This anonymous union stores the bits belonging to DeclContext and classes
1743 /// deriving from it. The goal is to use otherwise wasted
1744 /// space in DeclContext to store data belonging to derived classes.
1745 /// The space saved is especially significient when pointers are aligned
1746 /// to 8 bytes. In this case due to alignment requirements we have a
1747 /// little less than 8 bytes free in DeclContext which we can use.
1748 /// We check that none of the classes in this union is larger than
1749 /// 8 bytes with static_asserts in the ctor of DeclContext.
1750 union {
1751 DeclContextBitfields DeclContextBits;
1752 TagDeclBitfields TagDeclBits;
1753 EnumDeclBitfields EnumDeclBits;
1754 RecordDeclBitfields RecordDeclBits;
1755 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1756 FunctionDeclBitfields FunctionDeclBits;
1757 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1758 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1759 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1760 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1761 BlockDeclBitfields BlockDeclBits;
1762
1763 static_assert(sizeof(DeclContextBitfields) <= 8,
1764 "DeclContextBitfields is larger than 8 bytes!");
1765 static_assert(sizeof(TagDeclBitfields) <= 8,
1766 "TagDeclBitfields is larger than 8 bytes!");
1767 static_assert(sizeof(EnumDeclBitfields) <= 8,
1768 "EnumDeclBitfields is larger than 8 bytes!");
1769 static_assert(sizeof(RecordDeclBitfields) <= 8,
1770 "RecordDeclBitfields is larger than 8 bytes!");
1771 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1772 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1773 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1774 "FunctionDeclBitfields is larger than 8 bytes!");
1775 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1776 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1777 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1778 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1779 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1780 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1781 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1782 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1783 static_assert(sizeof(BlockDeclBitfields) <= 8,
1784 "BlockDeclBitfields is larger than 8 bytes!");
1785 };
1786
1787 /// FirstDecl - The first declaration stored within this declaration
1788 /// context.
1789 mutable Decl *FirstDecl = nullptr;
1790
1791 /// LastDecl - The last declaration stored within this declaration
1792 /// context. FIXME: We could probably cache this value somewhere
1793 /// outside of the DeclContext, to reduce the size of DeclContext by
1794 /// another pointer.
1795 mutable Decl *LastDecl = nullptr;
1796
1797 /// Build up a chain of declarations.
1798 ///
1799 /// \returns the first/last pair of declarations.
1800 static std::pair<Decl *, Decl *>
1801 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1802
1803 DeclContext(Decl::Kind K);
1804
1805public:
1806 ~DeclContext();
1807
1808 Decl::Kind getDeclKind() const {
1809 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1810 }
1811
1812 const char *getDeclKindName() const;
1813
1814 /// getParent - Returns the containing DeclContext.
1815 DeclContext *getParent() {
1816 return cast<Decl>(this)->getDeclContext();
1817 }
1818 const DeclContext *getParent() const {
1819 return const_cast<DeclContext*>(this)->getParent();
1820 }
1821
1822 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1823 /// different from getParent, e.g.:
1824 ///
1825 /// namespace A {
1826 /// struct S;
1827 /// }
1828 /// struct A::S {}; // getParent() == namespace 'A'
1829 /// // getLexicalParent() == translation unit
1830 ///
1831 DeclContext *getLexicalParent() {
1832 return cast<Decl>(this)->getLexicalDeclContext();
1833 }
1834 const DeclContext *getLexicalParent() const {
1835 return const_cast<DeclContext*>(this)->getLexicalParent();
1836 }
1837
1838 DeclContext *getLookupParent();
1839
1840 const DeclContext *getLookupParent() const {
1841 return const_cast<DeclContext*>(this)->getLookupParent();
1842 }
1843
1844 ASTContext &getParentASTContext() const {
1845 return cast<Decl>(this)->getASTContext();
1846 }
1847
1848 bool isClosure() const { return getDeclKind() == Decl::Block; }
1849
1850 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1851 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1852 const BlockDecl *getInnermostBlockDecl() const;
1853
1854 bool isObjCContainer() const {
1855 switch (getDeclKind()) {
1856 case Decl::ObjCCategory:
1857 case Decl::ObjCCategoryImpl:
1858 case Decl::ObjCImplementation:
1859 case Decl::ObjCInterface:
1860 case Decl::ObjCProtocol:
1861 return true;
1862 default:
1863 return false;
1864 }
1865 }
1866
1867 bool isFunctionOrMethod() const {
1868 switch (getDeclKind()) {
1869 case Decl::Block:
1870 case Decl::Captured:
1871 case Decl::ObjCMethod:
1872 return true;
1873 default:
1874 return getDeclKind() >= Decl::firstFunction &&
1875 getDeclKind() <= Decl::lastFunction;
1876 }
1877 }
1878
1879 /// Test whether the context supports looking up names.
1880 bool isLookupContext() const {
1881 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1882 getDeclKind() != Decl::Export;
1883 }
1884
1885 bool isFileContext() const {
1886 return getDeclKind() == Decl::TranslationUnit ||
1887 getDeclKind() == Decl::Namespace;
1888 }
1889
1890 bool isTranslationUnit() const {
1891 return getDeclKind() == Decl::TranslationUnit;
1892 }
1893
1894 bool isRecord() const {
1895 return getDeclKind() >= Decl::firstRecord &&
1896 getDeclKind() <= Decl::lastRecord;
1897 }
1898
1899 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1900
1901 bool isStdNamespace() const;
1902
1903 bool isInlineNamespace() const;
1904
1905 /// Determines whether this context is dependent on a
1906 /// template parameter.
1907 bool isDependentContext() const;
1908
1909 /// isTransparentContext - Determines whether this context is a
1910 /// "transparent" context, meaning that the members declared in this
1911 /// context are semantically declared in the nearest enclosing
1912 /// non-transparent (opaque) context but are lexically declared in
1913 /// this context. For example, consider the enumerators of an
1914 /// enumeration type:
1915 /// @code
1916 /// enum E {
1917 /// Val1
1918 /// };
1919 /// @endcode
1920 /// Here, E is a transparent context, so its enumerator (Val1) will
1921 /// appear (semantically) that it is in the same context of E.
1922 /// Examples of transparent contexts include: enumerations (except for
1923 /// C++0x scoped enums), and C++ linkage specifications.
1924 bool isTransparentContext() const;
1925
1926 /// Determines whether this context or some of its ancestors is a
1927 /// linkage specification context that specifies C linkage.
1928 bool isExternCContext() const;
1929
1930 /// Retrieve the nearest enclosing C linkage specification context.
1931 const LinkageSpecDecl *getExternCContext() const;
1932
1933 /// Determines whether this context or some of its ancestors is a
1934 /// linkage specification context that specifies C++ linkage.
1935 bool isExternCXXContext() const;
1936
1937 /// Determine whether this declaration context is equivalent
1938 /// to the declaration context DC.
1939 bool Equals(const DeclContext *DC) const {
1940 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1941 }
1942
1943 /// Determine whether this declaration context encloses the
1944 /// declaration context DC.
1945 bool Encloses(const DeclContext *DC) const;
1946
1947 /// Find the nearest non-closure ancestor of this context,
1948 /// i.e. the innermost semantic parent of this context which is not
1949 /// a closure. A context may be its own non-closure ancestor.
1950 Decl *getNonClosureAncestor();
1951 const Decl *getNonClosureAncestor() const {
1952 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1953 }
1954
1955 /// getPrimaryContext - There may be many different
1956 /// declarations of the same entity (including forward declarations
1957 /// of classes, multiple definitions of namespaces, etc.), each with
1958 /// a different set of declarations. This routine returns the
1959 /// "primary" DeclContext structure, which will contain the
1960 /// information needed to perform name lookup into this context.
1961 DeclContext *getPrimaryContext();
1962 const DeclContext *getPrimaryContext() const {
1963 return const_cast<DeclContext*>(this)->getPrimaryContext();
1964 }
1965
1966 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1967 /// other entities of the same name, or where it is a redeclaration if the
1968 /// two entities are compatible. This skips through transparent contexts.
1969 DeclContext *getRedeclContext();
1970 const DeclContext *getRedeclContext() const {
1971 return const_cast<DeclContext *>(this)->getRedeclContext();
1972 }
1973
1974 /// Retrieve the nearest enclosing namespace context.
1975 DeclContext *getEnclosingNamespaceContext();
1976 const DeclContext *getEnclosingNamespaceContext() const {
1977 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1978 }
1979
1980 /// Retrieve the outermost lexically enclosing record context.
1981 RecordDecl *getOuterLexicalRecordContext();
1982 const RecordDecl *getOuterLexicalRecordContext() const {
1983 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1984 }
1985
1986 /// Test if this context is part of the enclosing namespace set of
1987 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1988 /// isn't a namespace, this is equivalent to Equals().
1989 ///
1990 /// The enclosing namespace set of a namespace is the namespace and, if it is
1991 /// inline, its enclosing namespace, recursively.
1992 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1993
1994 /// Collects all of the declaration contexts that are semantically
1995 /// connected to this declaration context.
1996 ///
1997 /// For declaration contexts that have multiple semantically connected but
1998 /// syntactically distinct contexts, such as C++ namespaces, this routine
1999 /// retrieves the complete set of such declaration contexts in source order.
2000 /// For example, given:
2001 ///
2002 /// \code
2003 /// namespace N {
2004 /// int x;
2005 /// }
2006 /// namespace N {
2007 /// int y;
2008 /// }
2009 /// \endcode
2010 ///
2011 /// The \c Contexts parameter will contain both definitions of N.
2012 ///
2013 /// \param Contexts Will be cleared and set to the set of declaration
2014 /// contexts that are semanticaly connected to this declaration context,
2015 /// in source order, including this context (which may be the only result,
2016 /// for non-namespace contexts).
2017 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2018
2019 /// decl_iterator - Iterates through the declarations stored
2020 /// within this context.
2021 class decl_iterator {
2022 /// Current - The current declaration.
2023 Decl *Current = nullptr;
2024
2025 public:
2026 using value_type = Decl *;
2027 using reference = const value_type &;
2028 using pointer = const value_type *;
2029 using iterator_category = std::forward_iterator_tag;
2030 using difference_type = std::ptrdiff_t;
2031
2032 decl_iterator() = default;
2033 explicit decl_iterator(Decl *C) : Current(C) {}
2034
2035 reference operator*() const { return Current; }
2036
2037 // This doesn't meet the iterator requirements, but it's convenient
2038 value_type operator->() const { return Current; }
2039
2040 decl_iterator& operator++() {
2041 Current = Current->getNextDeclInContext();
2042 return *this;
2043 }
2044
2045 decl_iterator operator++(int) {
2046 decl_iterator tmp(*this);
2047 ++(*this);
2048 return tmp;
2049 }
2050
2051 friend bool operator==(decl_iterator x, decl_iterator y) {
2052 return x.Current == y.Current;
2053 }
2054
2055 friend bool operator!=(decl_iterator x, decl_iterator y) {
2056 return x.Current != y.Current;
2057 }
2058 };
2059
2060 using decl_range = llvm::iterator_range<decl_iterator>;
2061
2062 /// decls_begin/decls_end - Iterate over the declarations stored in
2063 /// this context.
2064 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2065 decl_iterator decls_begin() const;
2066 decl_iterator decls_end() const { return decl_iterator(); }
2067 bool decls_empty() const;
2068
2069 /// noload_decls_begin/end - Iterate over the declarations stored in this
2070 /// context that are currently loaded; don't attempt to retrieve anything
2071 /// from an external source.
2072 decl_range noload_decls() const {
2073 return decl_range(noload_decls_begin(), noload_decls_end());
2074 }
2075 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2076 decl_iterator noload_decls_end() const { return decl_iterator(); }
2077
2078 /// specific_decl_iterator - Iterates over a subrange of
2079 /// declarations stored in a DeclContext, providing only those that
2080 /// are of type SpecificDecl (or a class derived from it). This
2081 /// iterator is used, for example, to provide iteration over just
2082 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2083 template<typename SpecificDecl>
2084 class specific_decl_iterator {
2085 /// Current - The current, underlying declaration iterator, which
2086 /// will either be NULL or will point to a declaration of
2087 /// type SpecificDecl.
2088 DeclContext::decl_iterator Current;
2089
2090 /// SkipToNextDecl - Advances the current position up to the next
2091 /// declaration of type SpecificDecl that also meets the criteria
2092 /// required by Acceptable.
2093 void SkipToNextDecl() {
2094 while (*Current && !isa<SpecificDecl>(*Current))
2095 ++Current;
2096 }
2097
2098 public:
2099 using value_type = SpecificDecl *;
2100 // TODO: Add reference and pointer types (with some appropriate proxy type)
2101 // if we ever have a need for them.
2102 using reference = void;
2103 using pointer = void;
2104 using difference_type =
2105 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2106 using iterator_category = std::forward_iterator_tag;
2107
2108 specific_decl_iterator() = default;
2109
2110 /// specific_decl_iterator - Construct a new iterator over a
2111 /// subset of the declarations the range [C,
2112 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2113 /// member function of SpecificDecl that should return true for
2114 /// all of the SpecificDecl instances that will be in the subset
2115 /// of iterators. For example, if you want Objective-C instance
2116 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2117 /// &ObjCMethodDecl::isInstanceMethod.
2118 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2119 SkipToNextDecl();
2120 }
2121
2122 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2123
2124 // This doesn't meet the iterator requirements, but it's convenient
2125 value_type operator->() const { return **this; }
2126
2127 specific_decl_iterator& operator++() {
2128 ++Current;
2129 SkipToNextDecl();
2130 return *this;
2131 }
2132
2133 specific_decl_iterator operator++(int) {
2134 specific_decl_iterator tmp(*this);
2135 ++(*this);
2136 return tmp;
2137 }
2138
2139 friend bool operator==(const specific_decl_iterator& x,
2140 const specific_decl_iterator& y) {
2141 return x.Current == y.Current;
2142 }
2143
2144 friend bool operator!=(const specific_decl_iterator& x,
2145 const specific_decl_iterator& y) {
2146 return x.Current != y.Current;
2147 }
2148 };
2149
2150 /// Iterates over a filtered subrange of declarations stored
2151 /// in a DeclContext.
2152 ///
2153 /// This iterator visits only those declarations that are of type
2154 /// SpecificDecl (or a class derived from it) and that meet some
2155 /// additional run-time criteria. This iterator is used, for
2156 /// example, to provide access to the instance methods within an
2157 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2158 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2159 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2160 class filtered_decl_iterator {
2161 /// Current - The current, underlying declaration iterator, which
2162 /// will either be NULL or will point to a declaration of
2163 /// type SpecificDecl.
2164 DeclContext::decl_iterator Current;
2165
2166 /// SkipToNextDecl - Advances the current position up to the next
2167 /// declaration of type SpecificDecl that also meets the criteria
2168 /// required by Acceptable.
2169 void SkipToNextDecl() {
2170 while (*Current &&
2171 (!isa<SpecificDecl>(*Current) ||
2172 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2173 ++Current;
2174 }
2175
2176 public:
2177 using value_type = SpecificDecl *;
2178 // TODO: Add reference and pointer types (with some appropriate proxy type)
2179 // if we ever have a need for them.
2180 using reference = void;
2181 using pointer = void;
2182 using difference_type =
2183 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2184 using iterator_category = std::forward_iterator_tag;
2185
2186 filtered_decl_iterator() = default;
2187
2188 /// filtered_decl_iterator - Construct a new iterator over a
2189 /// subset of the declarations the range [C,
2190 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2191 /// member function of SpecificDecl that should return true for
2192 /// all of the SpecificDecl instances that will be in the subset
2193 /// of iterators. For example, if you want Objective-C instance
2194 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2195 /// &ObjCMethodDecl::isInstanceMethod.
2196 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2197 SkipToNextDecl();
2198 }
2199
2200 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2201 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2202
2203 filtered_decl_iterator& operator++() {
2204 ++Current;
2205 SkipToNextDecl();
2206 return *this;
2207 }
2208
2209 filtered_decl_iterator operator++(int) {
2210 filtered_decl_iterator tmp(*this);
2211 ++(*this);
2212 return tmp;
2213 }
2214
2215 friend bool operator==(const filtered_decl_iterator& x,
2216 const filtered_decl_iterator& y) {
2217 return x.Current == y.Current;
2218 }
2219
2220 friend bool operator!=(const filtered_decl_iterator& x,
2221 const filtered_decl_iterator& y) {
2222 return x.Current != y.Current;
2223 }
2224 };
2225
2226 /// Add the declaration D into this context.
2227 ///
2228 /// This routine should be invoked when the declaration D has first
2229 /// been declared, to place D into the context where it was
2230 /// (lexically) defined. Every declaration must be added to one
2231 /// (and only one!) context, where it can be visited via
2232 /// [decls_begin(), decls_end()). Once a declaration has been added
2233 /// to its lexical context, the corresponding DeclContext owns the
2234 /// declaration.
2235 ///
2236 /// If D is also a NamedDecl, it will be made visible within its
2237 /// semantic context via makeDeclVisibleInContext.
2238 void addDecl(Decl *D);
2239
2240 /// Add the declaration D into this context, but suppress
2241 /// searches for external declarations with the same name.
2242 ///
2243 /// Although analogous in function to addDecl, this removes an
2244 /// important check. This is only useful if the Decl is being
2245 /// added in response to an external search; in all other cases,
2246 /// addDecl() is the right function to use.
2247 /// See the ASTImporter for use cases.
2248 void addDeclInternal(Decl *D);
2249
2250 /// Add the declaration D to this context without modifying
2251 /// any lookup tables.
2252 ///
2253 /// This is useful for some operations in dependent contexts where
2254 /// the semantic context might not be dependent; this basically
2255 /// only happens with friends.
2256 void addHiddenDecl(Decl *D);
2257
2258 /// Removes a declaration from this context.
2259 void removeDecl(Decl *D);
2260
2261 /// Checks whether a declaration is in this context.
2262 bool containsDecl(Decl *D) const;
2263
2264 /// Checks whether a declaration is in this context.
2265 /// This also loads the Decls from the external source before the check.
2266 bool containsDeclAndLoad(Decl *D) const;
2267
2268 using lookup_result = DeclContextLookupResult;
2269 using lookup_iterator = lookup_result::iterator;
2270
2271 /// lookup - Find the declarations (if any) with the given Name in
2272 /// this context. Returns a range of iterators that contains all of
2273 /// the declarations with this name, with object, function, member,
2274 /// and enumerator names preceding any tag name. Note that this
2275 /// routine will not look into parent contexts.
2276 lookup_result lookup(DeclarationName Name) const;
2277
2278 /// Find the declarations with the given name that are visible
2279 /// within this context; don't attempt to retrieve anything from an
2280 /// external source.
2281 lookup_result noload_lookup(DeclarationName Name);
2282
2283 /// A simplistic name lookup mechanism that performs name lookup
2284 /// into this declaration context without consulting the external source.
2285 ///
2286 /// This function should almost never be used, because it subverts the
2287 /// usual relationship between a DeclContext and the external source.
2288 /// See the ASTImporter for the (few, but important) use cases.
2289 ///
2290 /// FIXME: This is very inefficient; replace uses of it with uses of
2291 /// noload_lookup.
2292 void localUncachedLookup(DeclarationName Name,
2293 SmallVectorImpl<NamedDecl *> &Results);
2294
2295 /// Makes a declaration visible within this context.
2296 ///
2297 /// This routine makes the declaration D visible to name lookup
2298 /// within this context and, if this is a transparent context,
2299 /// within its parent contexts up to the first enclosing
2300 /// non-transparent context. Making a declaration visible within a
2301 /// context does not transfer ownership of a declaration, and a
2302 /// declaration can be visible in many contexts that aren't its
2303 /// lexical context.
2304 ///
2305 /// If D is a redeclaration of an existing declaration that is
2306 /// visible from this context, as determined by
2307 /// NamedDecl::declarationReplaces, the previous declaration will be
2308 /// replaced with D.
2309 void makeDeclVisibleInContext(NamedDecl *D);
2310
2311 /// all_lookups_iterator - An iterator that provides a view over the results
2312 /// of looking up every possible name.
2313 class all_lookups_iterator;
2314
2315 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2316
2317 lookups_range lookups() const;
2318 // Like lookups(), but avoids loading external declarations.
2319 // If PreserveInternalState, avoids building lookup data structures too.
2320 lookups_range noload_lookups(bool PreserveInternalState) const;
2321
2322 /// Iterators over all possible lookups within this context.
2323 all_lookups_iterator lookups_begin() const;
2324 all_lookups_iterator lookups_end() const;
2325
2326 /// Iterators over all possible lookups within this context that are
2327 /// currently loaded; don't attempt to retrieve anything from an external
2328 /// source.
2329 all_lookups_iterator noload_lookups_begin() const;
2330 all_lookups_iterator noload_lookups_end() const;
2331
2332 struct udir_iterator;
2333
2334 using udir_iterator_base =
2335 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2336 std::random_access_iterator_tag,
2337 UsingDirectiveDecl *>;
2338
2339 struct udir_iterator : udir_iterator_base {
2340 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2341
2342 UsingDirectiveDecl *operator*() const;
2343 };
2344
2345 using udir_range = llvm::iterator_range<udir_iterator>;
2346
2347 udir_range using_directives() const;
2348
2349 // These are all defined in DependentDiagnostic.h.
2350 class ddiag_iterator;
2351
2352 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2353
2354 inline ddiag_range ddiags() const;
2355
2356 // Low-level accessors
2357
2358 /// Mark that there are external lexical declarations that we need
2359 /// to include in our lookup table (and that are not available as external
2360 /// visible lookups). These extra lookup results will be found by walking
2361 /// the lexical declarations of this context. This should be used only if
2362 /// setHasExternalLexicalStorage() has been called on any decl context for
2363 /// which this is the primary context.
2364 void setMustBuildLookupTable() {
2365 assert(this == getPrimaryContext() &&((this == getPrimaryContext() && "should only be called on primary context"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 2366, __PRETTY_FUNCTION__))
2366 "should only be called on primary context")((this == getPrimaryContext() && "should only be called on primary context"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include/clang/AST/DeclBase.h"
, 2366, __PRETTY_FUNCTION__))
;
2367 DeclContextBits.HasLazyExternalLexicalLookups = true;
2368 }
2369
2370 /// Retrieve the internal representation of the lookup structure.
2371 /// This may omit some names if we are lazily building the structure.
2372 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2373
2374 /// Ensure the lookup structure is fully-built and return it.
2375 StoredDeclsMap *buildLookup();
2376
2377 /// Whether this DeclContext has external storage containing
2378 /// additional declarations that are lexically in this context.
2379 bool hasExternalLexicalStorage() const {
2380 return DeclContextBits.ExternalLexicalStorage;
2381 }
2382
2383 /// State whether this DeclContext has external storage for
2384 /// declarations lexically in this context.
2385 void setHasExternalLexicalStorage(bool ES = true) const {
2386 DeclContextBits.ExternalLexicalStorage = ES;
2387 }
2388
2389 /// Whether this DeclContext has external storage containing
2390 /// additional declarations that are visible in this context.
2391 bool hasExternalVisibleStorage() const {
2392 return DeclContextBits.ExternalVisibleStorage;
2393 }
2394
2395 /// State whether this DeclContext has external storage for
2396 /// declarations visible in this context.
2397 void setHasExternalVisibleStorage(bool ES = true) const {
2398 DeclContextBits.ExternalVisibleStorage = ES;
2399 if (ES && LookupPtr)
2400 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2401 }
2402
2403 /// Determine whether the given declaration is stored in the list of
2404 /// declarations lexically within this context.
2405 bool isDeclInLexicalTraversal(const Decl *D) const {
2406 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2407 D == LastDecl);
2408 }
2409
2410 bool setUseQualifiedLookup(bool use = true) const {
2411 bool old_value = DeclContextBits.UseQualifiedLookup;
2412 DeclContextBits.UseQualifiedLookup = use;
2413 return old_value;
2414 }
2415
2416 bool shouldUseQualifiedLookup() const {
2417 return DeclContextBits.UseQualifiedLookup;
2418 }
2419
2420 static bool classof(const Decl *D);
2421 static bool classof(const DeclContext *D) { return true; }
2422
2423 void dumpDeclContext() const;
2424 void dumpLookups() const;
2425 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2426 bool Deserialize = false) const;
2427
2428private:
2429 /// Whether this declaration context has had externally visible
2430 /// storage added since the last lookup. In this case, \c LookupPtr's
2431 /// invariant may not hold and needs to be fixed before we perform
2432 /// another lookup.
2433 bool hasNeedToReconcileExternalVisibleStorage() const {
2434 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2435 }
2436
2437 /// State that this declaration context has had externally visible
2438 /// storage added since the last lookup. In this case, \c LookupPtr's
2439 /// invariant may not hold and needs to be fixed before we perform
2440 /// another lookup.
2441 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2442 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2443 }
2444
2445 /// If \c true, this context may have local lexical declarations
2446 /// that are missing from the lookup table.
2447 bool hasLazyLocalLexicalLookups() const {
2448 return DeclContextBits.HasLazyLocalLexicalLookups;
2449 }
2450
2451 /// If \c true, this context may have local lexical declarations
2452 /// that are missing from the lookup table.
2453 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2454 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2455 }
2456
2457 /// If \c true, the external source may have lexical declarations
2458 /// that are missing from the lookup table.
2459 bool hasLazyExternalLexicalLookups() const {
2460 return DeclContextBits.HasLazyExternalLexicalLookups;
2461 }
2462
2463 /// If \c true, the external source may have lexical declarations
2464 /// that are missing from the lookup table.
2465 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2466 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2467 }
2468
2469 void reconcileExternalVisibleStorage() const;
2470 bool LoadLexicalDeclsFromExternalStorage() const;
2471
2472 /// Makes a declaration visible within this context, but
2473 /// suppresses searches for external declarations with the same
2474 /// name.
2475 ///
2476 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2477 /// use of addDeclInternal().
2478 void makeDeclVisibleInContextInternal(NamedDecl *D);
2479
2480 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2481
2482 void loadLazyLocalLexicalLookups();
2483 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2484 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2485 bool Rediscoverable);
2486 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2487};
2488
2489inline bool Decl::isTemplateParameter() const {
2490 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2491 getKind() == TemplateTemplateParm;
2492}
2493
2494// Specialization selected when ToTy is not a known subclass of DeclContext.
2495template <class ToTy,
2496 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2497struct cast_convert_decl_context {
2498 static const ToTy *doit(const DeclContext *Val) {
2499 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2500 }
2501
2502 static ToTy *doit(DeclContext *Val) {
2503 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2504 }
2505};
2506
2507// Specialization selected when ToTy is a known subclass of DeclContext.
2508template <class ToTy>
2509struct cast_convert_decl_context<ToTy, true> {
2510 static const ToTy *doit(const DeclContext *Val) {
2511 return static_cast<const ToTy*>(Val);
2512 }
2513
2514 static ToTy *doit(DeclContext *Val) {
2515 return static_cast<ToTy*>(Val);
2516 }
2517};
2518
2519} // namespace clang
2520
2521namespace llvm {
2522
2523/// isa<T>(DeclContext*)
2524template <typename To>
2525struct isa_impl<To, ::clang::DeclContext> {
2526 static bool doit(const ::clang::DeclContext &Val) {
2527 return To::classofKind(Val.getDeclKind());
2528 }
2529};
2530
2531/// cast<T>(DeclContext*)
2532template<class ToTy>
2533struct cast_convert_val<ToTy,
2534 const ::clang::DeclContext,const ::clang::DeclContext> {
2535 static const ToTy &doit(const ::clang::DeclContext &Val) {
2536 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2537 }
2538};
2539
2540template<class ToTy>
2541struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2542 static ToTy &doit(::clang::DeclContext &Val) {
2543 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2544 }
2545};
2546
2547template<class ToTy>
2548struct cast_convert_val<ToTy,
2549 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2550 static const ToTy *doit(const ::clang::DeclContext *Val) {
2551 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2552 }
2553};
2554
2555template<class ToTy>
2556struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2557 static ToTy *doit(::clang::DeclContext *Val) {
2558 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2559 }
2560};
2561
2562/// Implement cast_convert_val for Decl -> DeclContext conversions.
2563template<class FromTy>
2564struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2565 static ::clang::DeclContext &doit(const FromTy &Val) {
2566 return *FromTy::castToDeclContext(&Val);
2567 }
2568};
2569
2570template<class FromTy>
2571struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2572 static ::clang::DeclContext *doit(const FromTy *Val) {
2573 return FromTy::castToDeclContext(Val);
2574 }
2575};
2576
2577template<class FromTy>
2578struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2579 static const ::clang::DeclContext &doit(const FromTy &Val) {
2580 return *FromTy::castToDeclContext(&Val);
2581 }
2582};
2583
2584template<class FromTy>
2585struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2586 static const ::clang::DeclContext *doit(const FromTy *Val) {
2587 return FromTy::castToDeclContext(Val);
2588 }
2589};
2590
2591} // namespace llvm
2592
2593#endif // LLVM_CLANG_AST_DECLBASE_H