Bug Summary

File:clang/lib/CodeGen/CodeGenModule.cpp
Warning:line 4149, column 17
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 CodeGenModule.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 -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-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/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-12/lib/clang/12.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-12~++20200927111121+5811d723998/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998=. -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-2020-09-28-092409-31635-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp

/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp

1//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
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 coordinates the per-module state used while generating code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenModule.h"
14#include "CGBlocks.h"
15#include "CGCUDARuntime.h"
16#include "CGCXXABI.h"
17#include "CGCall.h"
18#include "CGDebugInfo.h"
19#include "CGObjCRuntime.h"
20#include "CGOpenCLRuntime.h"
21#include "CGOpenMPRuntime.h"
22#include "CGOpenMPRuntimeAMDGCN.h"
23#include "CGOpenMPRuntimeNVPTX.h"
24#include "CodeGenFunction.h"
25#include "CodeGenPGO.h"
26#include "ConstantEmitter.h"
27#include "CoverageMappingGen.h"
28#include "TargetInfo.h"
29#include "clang/AST/ASTContext.h"
30#include "clang/AST/CharUnits.h"
31#include "clang/AST/DeclCXX.h"
32#include "clang/AST/DeclObjC.h"
33#include "clang/AST/DeclTemplate.h"
34#include "clang/AST/Mangle.h"
35#include "clang/AST/RecordLayout.h"
36#include "clang/AST/RecursiveASTVisitor.h"
37#include "clang/AST/StmtVisitor.h"
38#include "clang/Basic/Builtins.h"
39#include "clang/Basic/CharInfo.h"
40#include "clang/Basic/CodeGenOptions.h"
41#include "clang/Basic/Diagnostic.h"
42#include "clang/Basic/FileManager.h"
43#include "clang/Basic/Module.h"
44#include "clang/Basic/SourceManager.h"
45#include "clang/Basic/TargetInfo.h"
46#include "clang/Basic/Version.h"
47#include "clang/CodeGen/ConstantInitBuilder.h"
48#include "clang/Frontend/FrontendDiagnostic.h"
49#include "llvm/ADT/StringSwitch.h"
50#include "llvm/ADT/Triple.h"
51#include "llvm/Analysis/TargetLibraryInfo.h"
52#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
53#include "llvm/IR/CallingConv.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/Intrinsics.h"
56#include "llvm/IR/LLVMContext.h"
57#include "llvm/IR/Module.h"
58#include "llvm/IR/ProfileSummary.h"
59#include "llvm/ProfileData/InstrProfReader.h"
60#include "llvm/Support/CodeGen.h"
61#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/ConvertUTF.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/MD5.h"
65#include "llvm/Support/TimeProfiler.h"
66
67using namespace clang;
68using namespace CodeGen;
69
70static llvm::cl::opt<bool> LimitedCoverage(
71 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
72 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
73 llvm::cl::init(false));
74
75static const char AnnotationSection[] = "llvm.metadata";
76
77static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
78 switch (CGM.getTarget().getCXXABI().getKind()) {
79 case TargetCXXABI::Fuchsia:
80 case TargetCXXABI::GenericAArch64:
81 case TargetCXXABI::GenericARM:
82 case TargetCXXABI::iOS:
83 case TargetCXXABI::iOS64:
84 case TargetCXXABI::WatchOS:
85 case TargetCXXABI::GenericMIPS:
86 case TargetCXXABI::GenericItanium:
87 case TargetCXXABI::WebAssembly:
88 case TargetCXXABI::XL:
89 return CreateItaniumCXXABI(CGM);
90 case TargetCXXABI::Microsoft:
91 return CreateMicrosoftCXXABI(CGM);
92 }
93
94 llvm_unreachable("invalid C++ ABI kind")::llvm::llvm_unreachable_internal("invalid C++ ABI kind", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 94)
;
95}
96
97CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
98 const PreprocessorOptions &PPO,
99 const CodeGenOptions &CGO, llvm::Module &M,
100 DiagnosticsEngine &diags,
101 CoverageSourceInfo *CoverageInfo)
102 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
103 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
104 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
105 VMContext(M.getContext()), Types(*this), VTables(*this),
106 SanitizerMD(new SanitizerMetadata(*this)) {
107
108 // Initialize the type cache.
109 llvm::LLVMContext &LLVMContext = M.getContext();
110 VoidTy = llvm::Type::getVoidTy(LLVMContext);
111 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
112 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
113 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
114 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
115 HalfTy = llvm::Type::getHalfTy(LLVMContext);
116 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
117 FloatTy = llvm::Type::getFloatTy(LLVMContext);
118 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
119 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
120 PointerAlignInBytes =
121 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
122 SizeSizeInBytes =
123 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
124 IntAlignInBytes =
125 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
126 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
127 IntPtrTy = llvm::IntegerType::get(LLVMContext,
128 C.getTargetInfo().getMaxPointerWidth());
129 Int8PtrTy = Int8Ty->getPointerTo(0);
130 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
131 AllocaInt8PtrTy = Int8Ty->getPointerTo(
132 M.getDataLayout().getAllocaAddrSpace());
133 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
134
135 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
136
137 if (LangOpts.ObjC)
138 createObjCRuntime();
139 if (LangOpts.OpenCL)
140 createOpenCLRuntime();
141 if (LangOpts.OpenMP)
142 createOpenMPRuntime();
143 if (LangOpts.CUDA)
144 createCUDARuntime();
145
146 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
147 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
148 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
149 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
150 getCXXABI().getMangleContext()));
151
152 // If debug info or coverage generation is enabled, create the CGDebugInfo
153 // object.
154 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
155 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
156 DebugInfo.reset(new CGDebugInfo(*this));
157
158 Block.GlobalUniqueCount = 0;
159
160 if (C.getLangOpts().ObjC)
161 ObjCData.reset(new ObjCEntrypoints());
162
163 if (CodeGenOpts.hasProfileClangUse()) {
164 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
165 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
166 if (auto E = ReaderOrErr.takeError()) {
167 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
168 "Could not read profile %0: %1");
169 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
170 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
171 << EI.message();
172 });
173 } else
174 PGOReader = std::move(ReaderOrErr.get());
175 }
176
177 // If coverage mapping generation is enabled, create the
178 // CoverageMappingModuleGen object.
179 if (CodeGenOpts.CoverageMapping)
180 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
181}
182
183CodeGenModule::~CodeGenModule() {}
184
185void CodeGenModule::createObjCRuntime() {
186 // This is just isGNUFamily(), but we want to force implementors of
187 // new ABIs to decide how best to do this.
188 switch (LangOpts.ObjCRuntime.getKind()) {
189 case ObjCRuntime::GNUstep:
190 case ObjCRuntime::GCC:
191 case ObjCRuntime::ObjFW:
192 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
193 return;
194
195 case ObjCRuntime::FragileMacOSX:
196 case ObjCRuntime::MacOSX:
197 case ObjCRuntime::iOS:
198 case ObjCRuntime::WatchOS:
199 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
200 return;
201 }
202 llvm_unreachable("bad runtime kind")::llvm::llvm_unreachable_internal("bad runtime kind", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 202)
;
203}
204
205void CodeGenModule::createOpenCLRuntime() {
206 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
207}
208
209void CodeGenModule::createOpenMPRuntime() {
210 // Select a specialized code generation class based on the target, if any.
211 // If it does not exist use the default implementation.
212 switch (getTriple().getArch()) {
213 case llvm::Triple::nvptx:
214 case llvm::Triple::nvptx64:
215 assert(getLangOpts().OpenMPIsDevice &&((getLangOpts().OpenMPIsDevice && "OpenMP NVPTX is only prepared to deal with device code."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP NVPTX is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 216, __PRETTY_FUNCTION__))
216 "OpenMP NVPTX is only prepared to deal with device code.")((getLangOpts().OpenMPIsDevice && "OpenMP NVPTX is only prepared to deal with device code."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP NVPTX is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 216, __PRETTY_FUNCTION__))
;
217 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
218 break;
219 case llvm::Triple::amdgcn:
220 assert(getLangOpts().OpenMPIsDevice &&((getLangOpts().OpenMPIsDevice && "OpenMP AMDGCN is only prepared to deal with device code."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP AMDGCN is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 221, __PRETTY_FUNCTION__))
221 "OpenMP AMDGCN is only prepared to deal with device code.")((getLangOpts().OpenMPIsDevice && "OpenMP AMDGCN is only prepared to deal with device code."
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().OpenMPIsDevice && \"OpenMP AMDGCN is only prepared to deal with device code.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 221, __PRETTY_FUNCTION__))
;
222 OpenMPRuntime.reset(new CGOpenMPRuntimeAMDGCN(*this));
223 break;
224 default:
225 if (LangOpts.OpenMPSimd)
226 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
227 else
228 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
229 break;
230 }
231}
232
233void CodeGenModule::createCUDARuntime() {
234 CUDARuntime.reset(CreateNVCUDARuntime(*this));
235}
236
237void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
238 Replacements[Name] = C;
239}
240
241void CodeGenModule::applyReplacements() {
242 for (auto &I : Replacements) {
243 StringRef MangledName = I.first();
244 llvm::Constant *Replacement = I.second;
245 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
246 if (!Entry)
247 continue;
248 auto *OldF = cast<llvm::Function>(Entry);
249 auto *NewF = dyn_cast<llvm::Function>(Replacement);
250 if (!NewF) {
251 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
252 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
253 } else {
254 auto *CE = cast<llvm::ConstantExpr>(Replacement);
255 assert(CE->getOpcode() == llvm::Instruction::BitCast ||((CE->getOpcode() == llvm::Instruction::BitCast || CE->
getOpcode() == llvm::Instruction::GetElementPtr) ? static_cast
<void> (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 256, __PRETTY_FUNCTION__))
256 CE->getOpcode() == llvm::Instruction::GetElementPtr)((CE->getOpcode() == llvm::Instruction::BitCast || CE->
getOpcode() == llvm::Instruction::GetElementPtr) ? static_cast
<void> (0) : __assert_fail ("CE->getOpcode() == llvm::Instruction::BitCast || CE->getOpcode() == llvm::Instruction::GetElementPtr"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 256, __PRETTY_FUNCTION__))
;
257 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
258 }
259 }
260
261 // Replace old with new, but keep the old order.
262 OldF->replaceAllUsesWith(Replacement);
263 if (NewF) {
264 NewF->removeFromParent();
265 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
266 NewF);
267 }
268 OldF->eraseFromParent();
269 }
270}
271
272void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
273 GlobalValReplacements.push_back(std::make_pair(GV, C));
274}
275
276void CodeGenModule::applyGlobalValReplacements() {
277 for (auto &I : GlobalValReplacements) {
278 llvm::GlobalValue *GV = I.first;
279 llvm::Constant *C = I.second;
280
281 GV->replaceAllUsesWith(C);
282 GV->eraseFromParent();
283 }
284}
285
286// This is only used in aliases that we created and we know they have a
287// linear structure.
288static const llvm::GlobalObject *getAliasedGlobal(
289 const llvm::GlobalIndirectSymbol &GIS) {
290 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
291 const llvm::Constant *C = &GIS;
292 for (;;) {
293 C = C->stripPointerCasts();
294 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
295 return GO;
296 // stripPointerCasts will not walk over weak aliases.
297 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
298 if (!GIS2)
299 return nullptr;
300 if (!Visited.insert(GIS2).second)
301 return nullptr;
302 C = GIS2->getIndirectSymbol();
303 }
304}
305
306void CodeGenModule::checkAliases() {
307 // Check if the constructed aliases are well formed. It is really unfortunate
308 // that we have to do this in CodeGen, but we only construct mangled names
309 // and aliases during codegen.
310 bool Error = false;
311 DiagnosticsEngine &Diags = getDiags();
312 for (const GlobalDecl &GD : Aliases) {
313 const auto *D = cast<ValueDecl>(GD.getDecl());
314 SourceLocation Location;
315 bool IsIFunc = D->hasAttr<IFuncAttr>();
316 if (const Attr *A = D->getDefiningAttr())
317 Location = A->getLocation();
318 else
319 llvm_unreachable("Not an alias or ifunc?")::llvm::llvm_unreachable_internal("Not an alias or ifunc?", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 319)
;
320 StringRef MangledName = getMangledName(GD);
321 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
322 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
323 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
324 if (!GV) {
325 Error = true;
326 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
327 } else if (GV->isDeclaration()) {
328 Error = true;
329 Diags.Report(Location, diag::err_alias_to_undefined)
330 << IsIFunc << IsIFunc;
331 } else if (IsIFunc) {
332 // Check resolver function type.
333 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
334 GV->getType()->getPointerElementType());
335 assert(FTy)((FTy) ? static_cast<void> (0) : __assert_fail ("FTy", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 335, __PRETTY_FUNCTION__))
;
336 if (!FTy->getReturnType()->isPointerTy())
337 Diags.Report(Location, diag::err_ifunc_resolver_return);
338 }
339
340 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
341 llvm::GlobalValue *AliaseeGV;
342 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
343 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
344 else
345 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
346
347 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
348 StringRef AliasSection = SA->getName();
349 if (AliasSection != AliaseeGV->getSection())
350 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
351 << AliasSection << IsIFunc << IsIFunc;
352 }
353
354 // We have to handle alias to weak aliases in here. LLVM itself disallows
355 // this since the object semantics would not match the IL one. For
356 // compatibility with gcc we implement it by just pointing the alias
357 // to its aliasee's aliasee. We also warn, since the user is probably
358 // expecting the link to be weak.
359 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
360 if (GA->isInterposable()) {
361 Diags.Report(Location, diag::warn_alias_to_weak_alias)
362 << GV->getName() << GA->getName() << IsIFunc;
363 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
364 GA->getIndirectSymbol(), Alias->getType());
365 Alias->setIndirectSymbol(Aliasee);
366 }
367 }
368 }
369 if (!Error)
370 return;
371
372 for (const GlobalDecl &GD : Aliases) {
373 StringRef MangledName = getMangledName(GD);
374 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
375 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
376 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
377 Alias->eraseFromParent();
378 }
379}
380
381void CodeGenModule::clear() {
382 DeferredDeclsToEmit.clear();
383 if (OpenMPRuntime)
384 OpenMPRuntime->clear();
385}
386
387void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
388 StringRef MainFile) {
389 if (!hasDiagnostics())
390 return;
391 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
392 if (MainFile.empty())
393 MainFile = "<stdin>";
394 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
395 } else {
396 if (Mismatched > 0)
397 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
398
399 if (Missing > 0)
400 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
401 }
402}
403
404void CodeGenModule::Release() {
405 EmitDeferred();
406 EmitVTablesOpportunistically();
407 applyGlobalValReplacements();
408 applyReplacements();
409 checkAliases();
410 emitMultiVersionFunctions();
411 EmitCXXGlobalInitFunc();
412 EmitCXXGlobalCleanUpFunc();
413 registerGlobalDtorsWithAtExit();
414 EmitCXXThreadLocalInitFunc();
415 if (ObjCRuntime)
416 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
417 AddGlobalCtor(ObjCInitFunction);
418 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
419 CUDARuntime) {
420 if (llvm::Function *CudaCtorFunction =
421 CUDARuntime->makeModuleCtorFunction())
422 AddGlobalCtor(CudaCtorFunction);
423 }
424 if (OpenMPRuntime) {
425 if (llvm::Function *OpenMPRequiresDirectiveRegFun =
426 OpenMPRuntime->emitRequiresDirectiveRegFun()) {
427 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
428 }
429 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
430 OpenMPRuntime->clear();
431 }
432 if (PGOReader) {
433 getModule().setProfileSummary(
434 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
435 llvm::ProfileSummary::PSK_Instr);
436 if (PGOStats.hasDiagnostics())
437 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
438 }
439 EmitCtorList(GlobalCtors, "llvm.global_ctors");
440 EmitCtorList(GlobalDtors, "llvm.global_dtors");
441 EmitGlobalAnnotations();
442 EmitStaticExternCAliases();
443 EmitDeferredUnusedCoverageMappings();
444 if (CoverageMapping)
445 CoverageMapping->emit();
446 if (CodeGenOpts.SanitizeCfiCrossDso) {
447 CodeGenFunction(*this).EmitCfiCheckFail();
448 CodeGenFunction(*this).EmitCfiCheckStub();
449 }
450 emitAtAvailableLinkGuard();
451 if (Context.getTargetInfo().getTriple().isWasm() &&
452 !Context.getTargetInfo().getTriple().isOSEmscripten()) {
453 EmitMainVoidAlias();
454 }
455 emitLLVMUsed();
456 if (SanStats)
457 SanStats->finish();
458
459 if (CodeGenOpts.Autolink &&
460 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
461 EmitModuleLinkOptions();
462 }
463
464 // On ELF we pass the dependent library specifiers directly to the linker
465 // without manipulating them. This is in contrast to other platforms where
466 // they are mapped to a specific linker option by the compiler. This
467 // difference is a result of the greater variety of ELF linkers and the fact
468 // that ELF linkers tend to handle libraries in a more complicated fashion
469 // than on other platforms. This forces us to defer handling the dependent
470 // libs to the linker.
471 //
472 // CUDA/HIP device and host libraries are different. Currently there is no
473 // way to differentiate dependent libraries for host or device. Existing
474 // usage of #pragma comment(lib, *) is intended for host libraries on
475 // Windows. Therefore emit llvm.dependent-libraries only for host.
476 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
477 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
478 for (auto *MD : ELFDependentLibraries)
479 NMD->addOperand(MD);
480 }
481
482 // Record mregparm value now so it is visible through rest of codegen.
483 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
484 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
485 CodeGenOpts.NumRegisterParameters);
486
487 if (CodeGenOpts.DwarfVersion) {
488 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
489 CodeGenOpts.DwarfVersion);
490 }
491
492 if (Context.getLangOpts().SemanticInterposition)
493 // Require various optimization to respect semantic interposition.
494 getModule().setSemanticInterposition(1);
495 else if (Context.getLangOpts().ExplicitNoSemanticInterposition)
496 // Allow dso_local on applicable targets.
497 getModule().setSemanticInterposition(0);
498
499 if (CodeGenOpts.EmitCodeView) {
500 // Indicate that we want CodeView in the metadata.
501 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
502 }
503 if (CodeGenOpts.CodeViewGHash) {
504 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
505 }
506 if (CodeGenOpts.ControlFlowGuard) {
507 // Function ID tables and checks for Control Flow Guard (cfguard=2).
508 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
509 } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
510 // Function ID tables for Control Flow Guard (cfguard=1).
511 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
512 }
513 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
514 // We don't support LTO with 2 with different StrictVTablePointers
515 // FIXME: we could support it by stripping all the information introduced
516 // by StrictVTablePointers.
517
518 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
519
520 llvm::Metadata *Ops[2] = {
521 llvm::MDString::get(VMContext, "StrictVTablePointers"),
522 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
523 llvm::Type::getInt32Ty(VMContext), 1))};
524
525 getModule().addModuleFlag(llvm::Module::Require,
526 "StrictVTablePointersRequirement",
527 llvm::MDNode::get(VMContext, Ops));
528 }
529 if (getModuleDebugInfo())
530 // We support a single version in the linked module. The LLVM
531 // parser will drop debug info with a different version number
532 // (and warn about it, too).
533 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
534 llvm::DEBUG_METADATA_VERSION);
535
536 // We need to record the widths of enums and wchar_t, so that we can generate
537 // the correct build attributes in the ARM backend. wchar_size is also used by
538 // TargetLibraryInfo.
539 uint64_t WCharWidth =
540 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
541 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
542
543 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
544 if ( Arch == llvm::Triple::arm
545 || Arch == llvm::Triple::armeb
546 || Arch == llvm::Triple::thumb
547 || Arch == llvm::Triple::thumbeb) {
548 // The minimum width of an enum in bytes
549 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
550 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
551 }
552
553 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
554 StringRef ABIStr = Target.getABI();
555 llvm::LLVMContext &Ctx = TheModule.getContext();
556 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
557 llvm::MDString::get(Ctx, ABIStr));
558 }
559
560 if (CodeGenOpts.SanitizeCfiCrossDso) {
561 // Indicate that we want cross-DSO control flow integrity checks.
562 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
563 }
564
565 if (CodeGenOpts.WholeProgramVTables) {
566 // Indicate whether VFE was enabled for this module, so that the
567 // vcall_visibility metadata added under whole program vtables is handled
568 // appropriately in the optimizer.
569 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
570 CodeGenOpts.VirtualFunctionElimination);
571 }
572
573 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
574 getModule().addModuleFlag(llvm::Module::Override,
575 "CFI Canonical Jump Tables",
576 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
577 }
578
579 if (CodeGenOpts.CFProtectionReturn &&
580 Target.checkCFProtectionReturnSupported(getDiags())) {
581 // Indicate that we want to instrument return control flow protection.
582 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
583 1);
584 }
585
586 if (CodeGenOpts.CFProtectionBranch &&
587 Target.checkCFProtectionBranchSupported(getDiags())) {
588 // Indicate that we want to instrument branch control flow protection.
589 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
590 1);
591 }
592
593 if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
594 Arch == llvm::Triple::aarch64_be) {
595 getModule().addModuleFlag(llvm::Module::Error,
596 "branch-target-enforcement",
597 LangOpts.BranchTargetEnforcement);
598
599 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address",
600 LangOpts.hasSignReturnAddress());
601
602 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all",
603 LangOpts.isSignReturnAddressScopeAll());
604
605 getModule().addModuleFlag(llvm::Module::Error,
606 "sign-return-address-with-bkey",
607 !LangOpts.isSignReturnAddressWithAKey());
608 }
609
610 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
611 // Indicate whether __nvvm_reflect should be configured to flush denormal
612 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
613 // property.)
614 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
615 CodeGenOpts.FP32DenormalMode.Output !=
616 llvm::DenormalMode::IEEE);
617 }
618
619 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
620 if (LangOpts.OpenCL) {
621 EmitOpenCLMetadata();
622 // Emit SPIR version.
623 if (getTriple().isSPIR()) {
624 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
625 // opencl.spir.version named metadata.
626 // C++ is backwards compatible with OpenCL v2.0.
627 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
628 llvm::Metadata *SPIRVerElts[] = {
629 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
630 Int32Ty, Version / 100)),
631 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
632 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
633 llvm::NamedMDNode *SPIRVerMD =
634 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
635 llvm::LLVMContext &Ctx = TheModule.getContext();
636 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
637 }
638 }
639
640 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
641 assert(PLevel < 3 && "Invalid PIC Level")((PLevel < 3 && "Invalid PIC Level") ? static_cast
<void> (0) : __assert_fail ("PLevel < 3 && \"Invalid PIC Level\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 641, __PRETTY_FUNCTION__))
;
642 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
643 if (Context.getLangOpts().PIE)
644 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
645 }
646
647 if (getCodeGenOpts().CodeModel.size() > 0) {
648 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
649 .Case("tiny", llvm::CodeModel::Tiny)
650 .Case("small", llvm::CodeModel::Small)
651 .Case("kernel", llvm::CodeModel::Kernel)
652 .Case("medium", llvm::CodeModel::Medium)
653 .Case("large", llvm::CodeModel::Large)
654 .Default(~0u);
655 if (CM != ~0u) {
656 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
657 getModule().setCodeModel(codeModel);
658 }
659 }
660
661 if (CodeGenOpts.NoPLT)
662 getModule().setRtLibUseGOT();
663
664 SimplifyPersonality();
665
666 if (getCodeGenOpts().EmitDeclMetadata)
667 EmitDeclMetadata();
668
669 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
670 EmitCoverageFile();
671
672 if (CGDebugInfo *DI = getModuleDebugInfo())
673 DI->finalize();
674
675 if (getCodeGenOpts().EmitVersionIdentMetadata)
676 EmitVersionIdentMetadata();
677
678 if (!getCodeGenOpts().RecordCommandLine.empty())
679 EmitCommandLineMetadata();
680
681 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
682
683 EmitBackendOptionsMetadata(getCodeGenOpts());
684}
685
686void CodeGenModule::EmitOpenCLMetadata() {
687 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
688 // opencl.ocl.version named metadata node.
689 // C++ is backwards compatible with OpenCL v2.0.
690 // FIXME: We might need to add CXX version at some point too?
691 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
692 llvm::Metadata *OCLVerElts[] = {
693 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
694 Int32Ty, Version / 100)),
695 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
696 Int32Ty, (Version % 100) / 10))};
697 llvm::NamedMDNode *OCLVerMD =
698 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
699 llvm::LLVMContext &Ctx = TheModule.getContext();
700 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
701}
702
703void CodeGenModule::EmitBackendOptionsMetadata(
704 const CodeGenOptions CodeGenOpts) {
705 switch (getTriple().getArch()) {
706 default:
707 break;
708 case llvm::Triple::riscv32:
709 case llvm::Triple::riscv64:
710 getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
711 CodeGenOpts.SmallDataLimit);
712 break;
713 }
714}
715
716void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
717 // Make sure that this type is translated.
718 Types.UpdateCompletedType(TD);
719}
720
721void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
722 // Make sure that this type is translated.
723 Types.RefreshTypeCacheForClass(RD);
724}
725
726llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
727 if (!TBAA)
728 return nullptr;
729 return TBAA->getTypeInfo(QTy);
730}
731
732TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
733 if (!TBAA)
734 return TBAAAccessInfo();
735 if (getLangOpts().CUDAIsDevice) {
736 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
737 // access info.
738 if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
739 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
740 nullptr)
741 return TBAAAccessInfo();
742 } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
743 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
744 nullptr)
745 return TBAAAccessInfo();
746 }
747 }
748 return TBAA->getAccessInfo(AccessType);
749}
750
751TBAAAccessInfo
752CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
753 if (!TBAA)
754 return TBAAAccessInfo();
755 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
756}
757
758llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
759 if (!TBAA)
760 return nullptr;
761 return TBAA->getTBAAStructInfo(QTy);
762}
763
764llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
765 if (!TBAA)
766 return nullptr;
767 return TBAA->getBaseTypeInfo(QTy);
768}
769
770llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
771 if (!TBAA)
772 return nullptr;
773 return TBAA->getAccessTagInfo(Info);
774}
775
776TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
777 TBAAAccessInfo TargetInfo) {
778 if (!TBAA)
779 return TBAAAccessInfo();
780 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
781}
782
783TBAAAccessInfo
784CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
785 TBAAAccessInfo InfoB) {
786 if (!TBAA)
787 return TBAAAccessInfo();
788 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
789}
790
791TBAAAccessInfo
792CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
793 TBAAAccessInfo SrcInfo) {
794 if (!TBAA)
795 return TBAAAccessInfo();
796 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
797}
798
799void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
800 TBAAAccessInfo TBAAInfo) {
801 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
802 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
803}
804
805void CodeGenModule::DecorateInstructionWithInvariantGroup(
806 llvm::Instruction *I, const CXXRecordDecl *RD) {
807 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
808 llvm::MDNode::get(getLLVMContext(), {}));
809}
810
811void CodeGenModule::Error(SourceLocation loc, StringRef message) {
812 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
813 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
814}
815
816/// ErrorUnsupported - Print out an error that codegen doesn't support the
817/// specified stmt yet.
818void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
819 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
820 "cannot compile this %0 yet");
821 std::string Msg = Type;
822 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
823 << Msg << S->getSourceRange();
824}
825
826/// ErrorUnsupported - Print out an error that codegen doesn't support the
827/// specified decl yet.
828void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
829 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
830 "cannot compile this %0 yet");
831 std::string Msg = Type;
832 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
833}
834
835llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
836 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
837}
838
839void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
840 const NamedDecl *D) const {
841 if (GV->hasDLLImportStorageClass())
842 return;
843 // Internal definitions always have default visibility.
844 if (GV->hasLocalLinkage()) {
845 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
846 return;
847 }
848 if (!D)
849 return;
850 // Set visibility for definitions, and for declarations if requested globally
851 // or set explicitly.
852 LinkageInfo LV = D->getLinkageAndVisibility();
853 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
854 !GV->isDeclarationForLinker())
855 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
856}
857
858static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
859 llvm::GlobalValue *GV) {
860 if (GV->hasLocalLinkage())
861 return true;
862
863 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
864 return true;
865
866 // DLLImport explicitly marks the GV as external.
867 if (GV->hasDLLImportStorageClass())
868 return false;
869
870 const llvm::Triple &TT = CGM.getTriple();
871 if (TT.isWindowsGNUEnvironment()) {
872 // In MinGW, variables without DLLImport can still be automatically
873 // imported from a DLL by the linker; don't mark variables that
874 // potentially could come from another DLL as DSO local.
875 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
876 !GV->isThreadLocal())
877 return false;
878 }
879
880 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
881 // remain unresolved in the link, they can be resolved to zero, which is
882 // outside the current DSO.
883 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
884 return false;
885
886 // Every other GV is local on COFF.
887 // Make an exception for windows OS in the triple: Some firmware builds use
888 // *-win32-macho triples. This (accidentally?) produced windows relocations
889 // without GOT tables in older clang versions; Keep this behaviour.
890 // FIXME: even thread local variables?
891 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
892 return true;
893
894 // Only handle COFF and ELF for now.
895 if (!TT.isOSBinFormatELF())
896 return false;
897
898 // If this is not an executable, don't assume anything is local.
899 const auto &CGOpts = CGM.getCodeGenOpts();
900 llvm::Reloc::Model RM = CGOpts.RelocationModel;
901 const auto &LOpts = CGM.getLangOpts();
902 if (RM != llvm::Reloc::Static && !LOpts.PIE)
903 return false;
904
905 // A definition cannot be preempted from an executable.
906 if (!GV->isDeclarationForLinker())
907 return true;
908
909 // Most PIC code sequences that assume that a symbol is local cannot produce a
910 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
911 // depended, it seems worth it to handle it here.
912 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
913 return false;
914
915 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
916 llvm::Triple::ArchType Arch = TT.getArch();
917 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
918 Arch == llvm::Triple::ppc64le)
919 return false;
920
921 // If we can use copy relocations we can assume it is local.
922 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
923 if (!Var->isThreadLocal() &&
924 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
925 return true;
926
927 // If we can use a plt entry as the symbol address we can assume it
928 // is local.
929 // FIXME: This should work for PIE, but the gold linker doesn't support it.
930 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
931 return true;
932
933 // Otherwise don't assume it is local.
934 return false;
935}
936
937void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
938 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
939}
940
941void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
942 GlobalDecl GD) const {
943 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
944 // C++ destructors have a few C++ ABI specific special cases.
945 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
946 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
947 return;
948 }
949 setDLLImportDLLExport(GV, D);
950}
951
952void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
953 const NamedDecl *D) const {
954 if (D && D->isExternallyVisible()) {
955 if (D->hasAttr<DLLImportAttr>())
956 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
957 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
958 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
959 }
960}
961
962void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
963 GlobalDecl GD) const {
964 setDLLImportDLLExport(GV, GD);
965 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
966}
967
968void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
969 const NamedDecl *D) const {
970 setDLLImportDLLExport(GV, D);
971 setGVPropertiesAux(GV, D);
972}
973
974void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
975 const NamedDecl *D) const {
976 setGlobalVisibility(GV, D);
977 setDSOLocal(GV);
978 GV->setPartition(CodeGenOpts.SymbolPartition);
979}
980
981static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
982 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
983 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
984 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
985 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
986 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
987}
988
989llvm::GlobalVariable::ThreadLocalMode
990CodeGenModule::GetDefaultLLVMTLSModel() const {
991 switch (CodeGenOpts.getDefaultTLSModel()) {
992 case CodeGenOptions::GeneralDynamicTLSModel:
993 return llvm::GlobalVariable::GeneralDynamicTLSModel;
994 case CodeGenOptions::LocalDynamicTLSModel:
995 return llvm::GlobalVariable::LocalDynamicTLSModel;
996 case CodeGenOptions::InitialExecTLSModel:
997 return llvm::GlobalVariable::InitialExecTLSModel;
998 case CodeGenOptions::LocalExecTLSModel:
999 return llvm::GlobalVariable::LocalExecTLSModel;
1000 }
1001 llvm_unreachable("Invalid TLS model!")::llvm::llvm_unreachable_internal("Invalid TLS model!", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1001)
;
1002}
1003
1004void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1005 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!")((D.getTLSKind() && "setting TLS mode on non-TLS var!"
) ? static_cast<void> (0) : __assert_fail ("D.getTLSKind() && \"setting TLS mode on non-TLS var!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1005, __PRETTY_FUNCTION__))
;
1006
1007 llvm::GlobalValue::ThreadLocalMode TLM;
1008 TLM = GetDefaultLLVMTLSModel();
1009
1010 // Override the TLS model if it is explicitly specified.
1011 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1012 TLM = GetLLVMTLSModel(Attr->getModel());
1013 }
1014
1015 GV->setThreadLocalMode(TLM);
1016}
1017
1018static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1019 StringRef Name) {
1020 const TargetInfo &Target = CGM.getTarget();
1021 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1022}
1023
1024static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1025 const CPUSpecificAttr *Attr,
1026 unsigned CPUIndex,
1027 raw_ostream &Out) {
1028 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1029 // supported.
1030 if (Attr)
1031 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1032 else if (CGM.getTarget().supportsIFunc())
1033 Out << ".resolver";
1034}
1035
1036static void AppendTargetMangling(const CodeGenModule &CGM,
1037 const TargetAttr *Attr, raw_ostream &Out) {
1038 if (Attr->isDefaultVersion())
1039 return;
1040
1041 Out << '.';
1042 const TargetInfo &Target = CGM.getTarget();
1043 ParsedTargetAttr Info =
1044 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
1045 // Multiversioning doesn't allow "no-${feature}", so we can
1046 // only have "+" prefixes here.
1047 assert(LHS.startswith("+") && RHS.startswith("+") &&((LHS.startswith("+") && RHS.startswith("+") &&
"Features should always have a prefix.") ? static_cast<void
> (0) : __assert_fail ("LHS.startswith(\"+\") && RHS.startswith(\"+\") && \"Features should always have a prefix.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1048, __PRETTY_FUNCTION__))
1048 "Features should always have a prefix.")((LHS.startswith("+") && RHS.startswith("+") &&
"Features should always have a prefix.") ? static_cast<void
> (0) : __assert_fail ("LHS.startswith(\"+\") && RHS.startswith(\"+\") && \"Features should always have a prefix.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1048, __PRETTY_FUNCTION__))
;
1049 return Target.multiVersionSortPriority(LHS.substr(1)) >
1050 Target.multiVersionSortPriority(RHS.substr(1));
1051 });
1052
1053 bool IsFirst = true;
1054
1055 if (!Info.Architecture.empty()) {
1056 IsFirst = false;
1057 Out << "arch_" << Info.Architecture;
1058 }
1059
1060 for (StringRef Feat : Info.Features) {
1061 if (!IsFirst)
1062 Out << '_';
1063 IsFirst = false;
1064 Out << Feat.substr(1);
1065 }
1066}
1067
1068static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
1069 const NamedDecl *ND,
1070 bool OmitMultiVersionMangling = false) {
1071 SmallString<256> Buffer;
1072 llvm::raw_svector_ostream Out(Buffer);
1073 MangleContext &MC = CGM.getCXXABI().getMangleContext();
1074 if (MC.shouldMangleDeclName(ND))
1075 MC.mangleName(GD.getWithDecl(ND), Out);
1076 else {
1077 IdentifierInfo *II = ND->getIdentifier();
1078 assert(II && "Attempt to mangle unnamed decl.")((II && "Attempt to mangle unnamed decl.") ? static_cast
<void> (0) : __assert_fail ("II && \"Attempt to mangle unnamed decl.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1078, __PRETTY_FUNCTION__))
;
1079 const auto *FD = dyn_cast<FunctionDecl>(ND);
1080
1081 if (FD &&
1082 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1083 Out << "__regcall3__" << II->getName();
1084 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1085 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
1086 Out << "__device_stub__" << II->getName();
1087 } else {
1088 Out << II->getName();
1089 }
1090 }
1091
1092 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1093 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1094 switch (FD->getMultiVersionKind()) {
1095 case MultiVersionKind::CPUDispatch:
1096 case MultiVersionKind::CPUSpecific:
1097 AppendCPUSpecificCPUDispatchMangling(CGM,
1098 FD->getAttr<CPUSpecificAttr>(),
1099 GD.getMultiVersionIndex(), Out);
1100 break;
1101 case MultiVersionKind::Target:
1102 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1103 break;
1104 case MultiVersionKind::None:
1105 llvm_unreachable("None multiversion type isn't valid here")::llvm::llvm_unreachable_internal("None multiversion type isn't valid here"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1105)
;
1106 }
1107 }
1108
1109 return std::string(Out.str());
1110}
1111
1112void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1113 const FunctionDecl *FD) {
1114 if (!FD->isMultiVersion())
1115 return;
1116
1117 // Get the name of what this would be without the 'target' attribute. This
1118 // allows us to lookup the version that was emitted when this wasn't a
1119 // multiversion function.
1120 std::string NonTargetName =
1121 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1122 GlobalDecl OtherGD;
1123 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1124 assert(OtherGD.getCanonicalDecl()((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1128, __PRETTY_FUNCTION__))
1125 .getDecl()((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1128, __PRETTY_FUNCTION__))
1126 ->getAsFunction()((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1128, __PRETTY_FUNCTION__))
1127 ->isMultiVersion() &&((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1128, __PRETTY_FUNCTION__))
1128 "Other GD should now be a multiversioned function")((OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->
isMultiVersion() && "Other GD should now be a multiversioned function"
) ? static_cast<void> (0) : __assert_fail ("OtherGD.getCanonicalDecl() .getDecl() ->getAsFunction() ->isMultiVersion() && \"Other GD should now be a multiversioned function\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1128, __PRETTY_FUNCTION__))
;
1129 // OtherFD is the version of this function that was mangled BEFORE
1130 // becoming a MultiVersion function. It potentially needs to be updated.
1131 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1132 .getDecl()
1133 ->getAsFunction()
1134 ->getMostRecentDecl();
1135 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1136 // This is so that if the initial version was already the 'default'
1137 // version, we don't try to update it.
1138 if (OtherName != NonTargetName) {
1139 // Remove instead of erase, since others may have stored the StringRef
1140 // to this.
1141 const auto ExistingRecord = Manglings.find(NonTargetName);
1142 if (ExistingRecord != std::end(Manglings))
1143 Manglings.remove(&(*ExistingRecord));
1144 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1145 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1146 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1147 Entry->setName(OtherName);
1148 }
1149 }
1150}
1151
1152StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1153 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1154
1155 // Some ABIs don't have constructor variants. Make sure that base and
1156 // complete constructors get mangled the same.
1157 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1158 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1159 CXXCtorType OrigCtorType = GD.getCtorType();
1160 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete)((OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete)
? static_cast<void> (0) : __assert_fail ("OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1160, __PRETTY_FUNCTION__))
;
1161 if (OrigCtorType == Ctor_Base)
1162 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1163 }
1164 }
1165
1166 auto FoundName = MangledDeclNames.find(CanonicalGD);
1167 if (FoundName != MangledDeclNames.end())
1168 return FoundName->second;
1169
1170 // Keep the first result in the case of a mangling collision.
1171 const auto *ND = cast<NamedDecl>(GD.getDecl());
1172 std::string MangledName = getMangledNameImpl(*this, GD, ND);
1173
1174 // Ensure either we have different ABIs between host and device compilations,
1175 // says host compilation following MSVC ABI but device compilation follows
1176 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1177 // mangling should be the same after name stubbing. The later checking is
1178 // very important as the device kernel name being mangled in host-compilation
1179 // is used to resolve the device binaries to be executed. Inconsistent naming
1180 // result in undefined behavior. Even though we cannot check that naming
1181 // directly between host- and device-compilations, the host- and
1182 // device-mangling in host compilation could help catching certain ones.
1183 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
1184 getLangOpts().CUDAIsDevice ||((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
1185 (getContext().getAuxTargetInfo() &&((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
1186 (getContext().getAuxTargetInfo()->getCXXABI() !=((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
1187 getContext().getTargetInfo().getCXXABI())) ||((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
1188 getCUDARuntime().getDeviceSideName(ND) ==((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
1189 getMangledNameImpl(((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
1190 *this,((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
1191 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
1192 ND))((!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr
>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo
() && (getContext().getAuxTargetInfo()->getCXXABI(
) != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime
().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind
(KernelReferenceKind::Kernel), ND)) ? static_cast<void>
(0) : __assert_fail ("!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || getLangOpts().CUDAIsDevice || (getContext().getAuxTargetInfo() && (getContext().getAuxTargetInfo()->getCXXABI() != getContext().getTargetInfo().getCXXABI())) || getCUDARuntime().getDeviceSideName(ND) == getMangledNameImpl( *this, GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), ND)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1192, __PRETTY_FUNCTION__))
;
1193
1194 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1195 return MangledDeclNames[CanonicalGD] = Result.first->first();
1196}
1197
1198StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1199 const BlockDecl *BD) {
1200 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1201 const Decl *D = GD.getDecl();
1202
1203 SmallString<256> Buffer;
1204 llvm::raw_svector_ostream Out(Buffer);
1205 if (!D)
1206 MangleCtx.mangleGlobalBlock(BD,
1207 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1208 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1209 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1210 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1211 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1212 else
1213 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1214
1215 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1216 return Result.first->first();
1217}
1218
1219llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1220 return getModule().getNamedValue(Name);
1221}
1222
1223/// AddGlobalCtor - Add a function to the list that will be called before
1224/// main() runs.
1225void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1226 llvm::Constant *AssociatedData) {
1227 // FIXME: Type coercion of void()* types.
1228 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1229}
1230
1231/// AddGlobalDtor - Add a function to the list that will be called
1232/// when the module is unloaded.
1233void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
1234 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1235 if (getCXXABI().useSinitAndSterm())
1236 llvm::report_fatal_error(
1237 "register global dtors with atexit() is not supported yet");
1238 DtorsUsingAtExit[Priority].push_back(Dtor);
1239 return;
1240 }
1241
1242 // FIXME: Type coercion of void()* types.
1243 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1244}
1245
1246void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1247 if (Fns.empty()) return;
1248
1249 // Ctor function type is void()*.
1250 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1251 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1252 TheModule.getDataLayout().getProgramAddressSpace());
1253
1254 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1255 llvm::StructType *CtorStructTy = llvm::StructType::get(
1256 Int32Ty, CtorPFTy, VoidPtrTy);
1257
1258 // Construct the constructor and destructor arrays.
1259 ConstantInitBuilder builder(*this);
1260 auto ctors = builder.beginArray(CtorStructTy);
1261 for (const auto &I : Fns) {
1262 auto ctor = ctors.beginStruct(CtorStructTy);
1263 ctor.addInt(Int32Ty, I.Priority);
1264 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1265 if (I.AssociatedData)
1266 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1267 else
1268 ctor.addNullPointer(VoidPtrTy);
1269 ctor.finishAndAddTo(ctors);
1270 }
1271
1272 auto list =
1273 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1274 /*constant*/ false,
1275 llvm::GlobalValue::AppendingLinkage);
1276
1277 // The LTO linker doesn't seem to like it when we set an alignment
1278 // on appending variables. Take it off as a workaround.
1279 list->setAlignment(llvm::None);
1280
1281 Fns.clear();
1282}
1283
1284llvm::GlobalValue::LinkageTypes
1285CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1286 const auto *D = cast<FunctionDecl>(GD.getDecl());
1287
1288 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1289
1290 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1291 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1292
1293 if (isa<CXXConstructorDecl>(D) &&
1294 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1295 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1296 // Our approach to inheriting constructors is fundamentally different from
1297 // that used by the MS ABI, so keep our inheriting constructor thunks
1298 // internal rather than trying to pick an unambiguous mangling for them.
1299 return llvm::GlobalValue::InternalLinkage;
1300 }
1301
1302 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
1303}
1304
1305llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1306 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1307 if (!MDS) return nullptr;
1308
1309 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1310}
1311
1312void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1313 const CGFunctionInfo &Info,
1314 llvm::Function *F) {
1315 unsigned CallingConv;
1316 llvm::AttributeList PAL;
1317 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
1318 F->setAttributes(PAL);
1319 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1320}
1321
1322static void removeImageAccessQualifier(std::string& TyName) {
1323 std::string ReadOnlyQual("__read_only");
1324 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1325 if (ReadOnlyPos != std::string::npos)
1326 // "+ 1" for the space after access qualifier.
1327 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1328 else {
1329 std::string WriteOnlyQual("__write_only");
1330 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1331 if (WriteOnlyPos != std::string::npos)
1332 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1333 else {
1334 std::string ReadWriteQual("__read_write");
1335 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1336 if (ReadWritePos != std::string::npos)
1337 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1338 }
1339 }
1340}
1341
1342// Returns the address space id that should be produced to the
1343// kernel_arg_addr_space metadata. This is always fixed to the ids
1344// as specified in the SPIR 2.0 specification in order to differentiate
1345// for example in clGetKernelArgInfo() implementation between the address
1346// spaces with targets without unique mapping to the OpenCL address spaces
1347// (basically all single AS CPUs).
1348static unsigned ArgInfoAddressSpace(LangAS AS) {
1349 switch (AS) {
1350 case LangAS::opencl_global:
1351 return 1;
1352 case LangAS::opencl_constant:
1353 return 2;
1354 case LangAS::opencl_local:
1355 return 3;
1356 case LangAS::opencl_generic:
1357 return 4; // Not in SPIR 2.0 specs.
1358 case LangAS::opencl_global_device:
1359 return 5;
1360 case LangAS::opencl_global_host:
1361 return 6;
1362 default:
1363 return 0; // Assume private.
1364 }
1365}
1366
1367void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
1368 const FunctionDecl *FD,
1369 CodeGenFunction *CGF) {
1370 assert(((FD && CGF) || (!FD && !CGF)) &&((((FD && CGF) || (!FD && !CGF)) && "Incorrect use - FD and CGF should either be both null or not!"
) ? static_cast<void> (0) : __assert_fail ("((FD && CGF) || (!FD && !CGF)) && \"Incorrect use - FD and CGF should either be both null or not!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1371, __PRETTY_FUNCTION__))
1371 "Incorrect use - FD and CGF should either be both null or not!")((((FD && CGF) || (!FD && !CGF)) && "Incorrect use - FD and CGF should either be both null or not!"
) ? static_cast<void> (0) : __assert_fail ("((FD && CGF) || (!FD && !CGF)) && \"Incorrect use - FD and CGF should either be both null or not!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1371, __PRETTY_FUNCTION__))
;
1372 // Create MDNodes that represent the kernel arg metadata.
1373 // Each MDNode is a list in the form of "key", N number of values which is
1374 // the same number of values as their are kernel arguments.
1375
1376 const PrintingPolicy &Policy = Context.getPrintingPolicy();
1377
1378 // MDNode for the kernel argument address space qualifiers.
1379 SmallVector<llvm::Metadata *, 8> addressQuals;
1380
1381 // MDNode for the kernel argument access qualifiers (images only).
1382 SmallVector<llvm::Metadata *, 8> accessQuals;
1383
1384 // MDNode for the kernel argument type names.
1385 SmallVector<llvm::Metadata *, 8> argTypeNames;
1386
1387 // MDNode for the kernel argument base type names.
1388 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1389
1390 // MDNode for the kernel argument type qualifiers.
1391 SmallVector<llvm::Metadata *, 8> argTypeQuals;
1392
1393 // MDNode for the kernel argument names.
1394 SmallVector<llvm::Metadata *, 8> argNames;
1395
1396 if (FD && CGF)
1397 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
1398 const ParmVarDecl *parm = FD->getParamDecl(i);
1399 QualType ty = parm->getType();
1400 std::string typeQuals;
1401
1402 if (ty->isPointerType()) {
1403 QualType pointeeTy = ty->getPointeeType();
1404
1405 // Get address qualifier.
1406 addressQuals.push_back(
1407 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1408 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1409
1410 // Get argument type name.
1411 std::string typeName =
1412 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
1413
1414 // Turn "unsigned type" to "utype"
1415 std::string::size_type pos = typeName.find("unsigned");
1416 if (pointeeTy.isCanonical() && pos != std::string::npos)
1417 typeName.erase(pos + 1, 8);
1418
1419 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1420
1421 std::string baseTypeName =
1422 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
1423 Policy) +
1424 "*";
1425
1426 // Turn "unsigned type" to "utype"
1427 pos = baseTypeName.find("unsigned");
1428 if (pos != std::string::npos)
1429 baseTypeName.erase(pos + 1, 8);
1430
1431 argBaseTypeNames.push_back(
1432 llvm::MDString::get(VMContext, baseTypeName));
1433
1434 // Get argument type qualifiers:
1435 if (ty.isRestrictQualified())
1436 typeQuals = "restrict";
1437 if (pointeeTy.isConstQualified() ||
1438 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
1439 typeQuals += typeQuals.empty() ? "const" : " const";
1440 if (pointeeTy.isVolatileQualified())
1441 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
1442 } else {
1443 uint32_t AddrSpc = 0;
1444 bool isPipe = ty->isPipeType();
1445 if (ty->isImageType() || isPipe)
1446 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1447
1448 addressQuals.push_back(
1449 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1450
1451 // Get argument type name.
1452 std::string typeName;
1453 if (isPipe)
1454 typeName = ty.getCanonicalType()
1455 ->castAs<PipeType>()
1456 ->getElementType()
1457 .getAsString(Policy);
1458 else
1459 typeName = ty.getUnqualifiedType().getAsString(Policy);
1460
1461 // Turn "unsigned type" to "utype"
1462 std::string::size_type pos = typeName.find("unsigned");
1463 if (ty.isCanonical() && pos != std::string::npos)
1464 typeName.erase(pos + 1, 8);
1465
1466 std::string baseTypeName;
1467 if (isPipe)
1468 baseTypeName = ty.getCanonicalType()
1469 ->castAs<PipeType>()
1470 ->getElementType()
1471 .getCanonicalType()
1472 .getAsString(Policy);
1473 else
1474 baseTypeName =
1475 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
1476
1477 // Remove access qualifiers on images
1478 // (as they are inseparable from type in clang implementation,
1479 // but OpenCL spec provides a special query to get access qualifier
1480 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1481 if (ty->isImageType()) {
1482 removeImageAccessQualifier(typeName);
1483 removeImageAccessQualifier(baseTypeName);
1484 }
1485
1486 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1487
1488 // Turn "unsigned type" to "utype"
1489 pos = baseTypeName.find("unsigned");
1490 if (pos != std::string::npos)
1491 baseTypeName.erase(pos + 1, 8);
1492
1493 argBaseTypeNames.push_back(
1494 llvm::MDString::get(VMContext, baseTypeName));
1495
1496 if (isPipe)
1497 typeQuals = "pipe";
1498 }
1499
1500 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1501
1502 // Get image and pipe access qualifier:
1503 if (ty->isImageType() || ty->isPipeType()) {
1504 const Decl *PDecl = parm;
1505 if (auto *TD = dyn_cast<TypedefType>(ty))
1506 PDecl = TD->getDecl();
1507 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1508 if (A && A->isWriteOnly())
1509 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1510 else if (A && A->isReadWrite())
1511 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1512 else
1513 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1514 } else
1515 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1516
1517 // Get argument name.
1518 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1519 }
1520
1521 Fn->setMetadata("kernel_arg_addr_space",
1522 llvm::MDNode::get(VMContext, addressQuals));
1523 Fn->setMetadata("kernel_arg_access_qual",
1524 llvm::MDNode::get(VMContext, accessQuals));
1525 Fn->setMetadata("kernel_arg_type",
1526 llvm::MDNode::get(VMContext, argTypeNames));
1527 Fn->setMetadata("kernel_arg_base_type",
1528 llvm::MDNode::get(VMContext, argBaseTypeNames));
1529 Fn->setMetadata("kernel_arg_type_qual",
1530 llvm::MDNode::get(VMContext, argTypeQuals));
1531 if (getCodeGenOpts().EmitOpenCLArgMetadata)
1532 Fn->setMetadata("kernel_arg_name",
1533 llvm::MDNode::get(VMContext, argNames));
1534}
1535
1536/// Determines whether the language options require us to model
1537/// unwind exceptions. We treat -fexceptions as mandating this
1538/// except under the fragile ObjC ABI with only ObjC exceptions
1539/// enabled. This means, for example, that C with -fexceptions
1540/// enables this.
1541static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1542 // If exceptions are completely disabled, obviously this is false.
1543 if (!LangOpts.Exceptions) return false;
1544
1545 // If C++ exceptions are enabled, this is true.
1546 if (LangOpts.CXXExceptions) return true;
1547
1548 // If ObjC exceptions are enabled, this depends on the ABI.
1549 if (LangOpts.ObjCExceptions) {
1550 return LangOpts.ObjCRuntime.hasUnwindExceptions();
1551 }
1552
1553 return true;
1554}
1555
1556static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1557 const CXXMethodDecl *MD) {
1558 // Check that the type metadata can ever actually be used by a call.
1559 if (!CGM.getCodeGenOpts().LTOUnit ||
1560 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1561 return false;
1562
1563 // Only functions whose address can be taken with a member function pointer
1564 // need this sort of type metadata.
1565 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1566 !isa<CXXDestructorDecl>(MD);
1567}
1568
1569std::vector<const CXXRecordDecl *>
1570CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1571 llvm::SetVector<const CXXRecordDecl *> MostBases;
1572
1573 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1574 CollectMostBases = [&](const CXXRecordDecl *RD) {
1575 if (RD->getNumBases() == 0)
1576 MostBases.insert(RD);
1577 for (const CXXBaseSpecifier &B : RD->bases())
1578 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1579 };
1580 CollectMostBases(RD);
1581 return MostBases.takeVector();
1582}
1583
1584void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1585 llvm::Function *F) {
1586 llvm::AttrBuilder B;
1587
1588 if (CodeGenOpts.UnwindTables)
1589 B.addAttribute(llvm::Attribute::UWTable);
1590
1591 if (CodeGenOpts.StackClashProtector)
1592 B.addAttribute("probe-stack", "inline-asm");
1593
1594 if (!hasUnwindExceptions(LangOpts))
1595 B.addAttribute(llvm::Attribute::NoUnwind);
1596
1597 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1598 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1599 B.addAttribute(llvm::Attribute::StackProtect);
1600 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1601 B.addAttribute(llvm::Attribute::StackProtectStrong);
1602 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1603 B.addAttribute(llvm::Attribute::StackProtectReq);
1604 }
1605
1606 if (!D) {
1607 // If we don't have a declaration to control inlining, the function isn't
1608 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1609 // disabled, mark the function as noinline.
1610 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1611 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1612 B.addAttribute(llvm::Attribute::NoInline);
1613
1614 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1615 return;
1616 }
1617
1618 // Track whether we need to add the optnone LLVM attribute,
1619 // starting with the default for this optimization level.
1620 bool ShouldAddOptNone =
1621 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1622 // We can't add optnone in the following cases, it won't pass the verifier.
1623 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1624 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1625
1626 // Add optnone, but do so only if the function isn't always_inline.
1627 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1628 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1629 B.addAttribute(llvm::Attribute::OptimizeNone);
1630
1631 // OptimizeNone implies noinline; we should not be inlining such functions.
1632 B.addAttribute(llvm::Attribute::NoInline);
1633
1634 // We still need to handle naked functions even though optnone subsumes
1635 // much of their semantics.
1636 if (D->hasAttr<NakedAttr>())
1637 B.addAttribute(llvm::Attribute::Naked);
1638
1639 // OptimizeNone wins over OptimizeForSize and MinSize.
1640 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1641 F->removeFnAttr(llvm::Attribute::MinSize);
1642 } else if (D->hasAttr<NakedAttr>()) {
1643 // Naked implies noinline: we should not be inlining such functions.
1644 B.addAttribute(llvm::Attribute::Naked);
1645 B.addAttribute(llvm::Attribute::NoInline);
1646 } else if (D->hasAttr<NoDuplicateAttr>()) {
1647 B.addAttribute(llvm::Attribute::NoDuplicate);
1648 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1649 // Add noinline if the function isn't always_inline.
1650 B.addAttribute(llvm::Attribute::NoInline);
1651 } else if (D->hasAttr<AlwaysInlineAttr>() &&
1652 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1653 // (noinline wins over always_inline, and we can't specify both in IR)
1654 B.addAttribute(llvm::Attribute::AlwaysInline);
1655 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1656 // If we're not inlining, then force everything that isn't always_inline to
1657 // carry an explicit noinline attribute.
1658 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1659 B.addAttribute(llvm::Attribute::NoInline);
1660 } else {
1661 // Otherwise, propagate the inline hint attribute and potentially use its
1662 // absence to mark things as noinline.
1663 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1664 // Search function and template pattern redeclarations for inline.
1665 auto CheckForInline = [](const FunctionDecl *FD) {
1666 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1667 return Redecl->isInlineSpecified();
1668 };
1669 if (any_of(FD->redecls(), CheckRedeclForInline))
1670 return true;
1671 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1672 if (!Pattern)
1673 return false;
1674 return any_of(Pattern->redecls(), CheckRedeclForInline);
1675 };
1676 if (CheckForInline(FD)) {
1677 B.addAttribute(llvm::Attribute::InlineHint);
1678 } else if (CodeGenOpts.getInlining() ==
1679 CodeGenOptions::OnlyHintInlining &&
1680 !FD->isInlined() &&
1681 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1682 B.addAttribute(llvm::Attribute::NoInline);
1683 }
1684 }
1685 }
1686
1687 // Add other optimization related attributes if we are optimizing this
1688 // function.
1689 if (!D->hasAttr<OptimizeNoneAttr>()) {
1690 if (D->hasAttr<ColdAttr>()) {
1691 if (!ShouldAddOptNone)
1692 B.addAttribute(llvm::Attribute::OptimizeForSize);
1693 B.addAttribute(llvm::Attribute::Cold);
1694 }
1695
1696 if (D->hasAttr<MinSizeAttr>())
1697 B.addAttribute(llvm::Attribute::MinSize);
1698 }
1699
1700 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1701
1702 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1703 if (alignment)
1704 F->setAlignment(llvm::Align(alignment));
1705
1706 if (!D->hasAttr<AlignedAttr>())
1707 if (LangOpts.FunctionAlignment)
1708 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
1709
1710 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1711 // reserve a bit for differentiating between virtual and non-virtual member
1712 // functions. If the current target's C++ ABI requires this and this is a
1713 // member function, set its alignment accordingly.
1714 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1715 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1716 F->setAlignment(llvm::Align(2));
1717 }
1718
1719 // In the cross-dso CFI mode with canonical jump tables, we want !type
1720 // attributes on definitions only.
1721 if (CodeGenOpts.SanitizeCfiCrossDso &&
1722 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1723 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1724 // Skip available_externally functions. They won't be codegen'ed in the
1725 // current module anyway.
1726 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
1727 CreateFunctionTypeMetadataForIcall(FD, F);
1728 }
1729 }
1730
1731 // Emit type metadata on member functions for member function pointer checks.
1732 // These are only ever necessary on definitions; we're guaranteed that the
1733 // definition will be present in the LTO unit as a result of LTO visibility.
1734 auto *MD = dyn_cast<CXXMethodDecl>(D);
1735 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1736 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1737 llvm::Metadata *Id =
1738 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1739 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1740 F->addTypeMetadata(0, Id);
1741 }
1742 }
1743}
1744
1745void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1746 const Decl *D = GD.getDecl();
1747 if (dyn_cast_or_null<NamedDecl>(D))
1748 setGVProperties(GV, GD);
1749 else
1750 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1751
1752 if (D && D->hasAttr<UsedAttr>())
1753 addUsedGlobal(GV);
1754
1755 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1756 const auto *VD = cast<VarDecl>(D);
1757 if (VD->getType().isConstQualified() &&
1758 VD->getStorageDuration() == SD_Static)
1759 addUsedGlobal(GV);
1760 }
1761}
1762
1763bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
1764 llvm::AttrBuilder &Attrs) {
1765 // Add target-cpu and target-features attributes to functions. If
1766 // we have a decl for the function and it has a target attribute then
1767 // parse that and add it to the feature set.
1768 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1769 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
1770 std::vector<std::string> Features;
1771 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
1772 FD = FD ? FD->getMostRecentDecl() : FD;
1773 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1774 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
1775 bool AddedAttr = false;
1776 if (TD || SD) {
1777 llvm::StringMap<bool> FeatureMap;
1778 getContext().getFunctionFeatureMap(FeatureMap, GD);
1779
1780 // Produce the canonical string for this set of features.
1781 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1782 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1783
1784 // Now add the target-cpu and target-features to the function.
1785 // While we populated the feature map above, we still need to
1786 // get and parse the target attribute so we can get the cpu for
1787 // the function.
1788 if (TD) {
1789 ParsedTargetAttr ParsedAttr = TD->parse();
1790 if (!ParsedAttr.Architecture.empty() &&
1791 getTarget().isValidCPUName(ParsedAttr.Architecture)) {
1792 TargetCPU = ParsedAttr.Architecture;
1793 TuneCPU = ""; // Clear the tune CPU.
1794 }
1795 if (!ParsedAttr.Tune.empty() &&
1796 getTarget().isValidCPUName(ParsedAttr.Tune))
1797 TuneCPU = ParsedAttr.Tune;
1798 }
1799 } else {
1800 // Otherwise just add the existing target cpu and target features to the
1801 // function.
1802 Features = getTarget().getTargetOpts().Features;
1803 }
1804
1805 if (!TargetCPU.empty()) {
1806 Attrs.addAttribute("target-cpu", TargetCPU);
1807 AddedAttr = true;
1808 }
1809 if (!TuneCPU.empty()) {
1810 Attrs.addAttribute("tune-cpu", TuneCPU);
1811 AddedAttr = true;
1812 }
1813 if (!Features.empty()) {
1814 llvm::sort(Features);
1815 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1816 AddedAttr = true;
1817 }
1818
1819 return AddedAttr;
1820}
1821
1822void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1823 llvm::GlobalObject *GO) {
1824 const Decl *D = GD.getDecl();
1825 SetCommonAttributes(GD, GO);
1826
1827 if (D) {
1828 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1829 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1830 GV->addAttribute("bss-section", SA->getName());
1831 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1832 GV->addAttribute("data-section", SA->getName());
1833 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1834 GV->addAttribute("rodata-section", SA->getName());
1835 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
1836 GV->addAttribute("relro-section", SA->getName());
1837 }
1838
1839 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1840 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1841 if (!D->getAttr<SectionAttr>())
1842 F->addFnAttr("implicit-section-name", SA->getName());
1843
1844 llvm::AttrBuilder Attrs;
1845 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
1846 // We know that GetCPUAndFeaturesAttributes will always have the
1847 // newest set, since it has the newest possible FunctionDecl, so the
1848 // new ones should replace the old.
1849 llvm::AttrBuilder RemoveAttrs;
1850 RemoveAttrs.addAttribute("target-cpu");
1851 RemoveAttrs.addAttribute("target-features");
1852 RemoveAttrs.addAttribute("tune-cpu");
1853 F->removeAttributes(llvm::AttributeList::FunctionIndex, RemoveAttrs);
1854 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1855 }
1856 }
1857
1858 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1859 GO->setSection(CSA->getName());
1860 else if (const auto *SA = D->getAttr<SectionAttr>())
1861 GO->setSection(SA->getName());
1862 }
1863
1864 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1865}
1866
1867void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
1868 llvm::Function *F,
1869 const CGFunctionInfo &FI) {
1870 const Decl *D = GD.getDecl();
1871 SetLLVMFunctionAttributes(GD, FI, F);
1872 SetLLVMFunctionAttributesForDefinition(D, F);
1873
1874 F->setLinkage(llvm::Function::InternalLinkage);
1875
1876 setNonAliasAttributes(GD, F);
1877}
1878
1879static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
1880 // Set linkage and visibility in case we never see a definition.
1881 LinkageInfo LV = ND->getLinkageAndVisibility();
1882 // Don't set internal linkage on declarations.
1883 // "extern_weak" is overloaded in LLVM; we probably should have
1884 // separate linkage types for this.
1885 if (isExternallyVisible(LV.getLinkage()) &&
1886 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1887 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1888}
1889
1890void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1891 llvm::Function *F) {
1892 // Only if we are checking indirect calls.
1893 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1894 return;
1895
1896 // Non-static class methods are handled via vtable or member function pointer
1897 // checks elsewhere.
1898 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1899 return;
1900
1901 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1902 F->addTypeMetadata(0, MD);
1903 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
1904
1905 // Emit a hash-based bit set entry for cross-DSO calls.
1906 if (CodeGenOpts.SanitizeCfiCrossDso)
1907 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1908 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1909}
1910
1911void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1912 bool IsIncompleteFunction,
1913 bool IsThunk) {
1914
1915 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1916 // If this is an intrinsic function, set the function's attributes
1917 // to the intrinsic's attributes.
1918 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1919 return;
1920 }
1921
1922 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1923
1924 if (!IsIncompleteFunction)
1925 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
1926
1927 // Add the Returned attribute for "this", except for iOS 5 and earlier
1928 // where substantial code, including the libstdc++ dylib, was compiled with
1929 // GCC and does not actually return "this".
1930 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1931 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1932 assert(!F->arg_empty() &&((!F->arg_empty() && F->arg_begin()->getType
() ->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return") ? static_cast<void> (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1935, __PRETTY_FUNCTION__))
1933 F->arg_begin()->getType()((!F->arg_empty() && F->arg_begin()->getType
() ->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return") ? static_cast<void> (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1935, __PRETTY_FUNCTION__))
1934 ->canLosslesslyBitCastTo(F->getReturnType()) &&((!F->arg_empty() && F->arg_begin()->getType
() ->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return") ? static_cast<void> (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1935, __PRETTY_FUNCTION__))
1935 "unexpected this return")((!F->arg_empty() && F->arg_begin()->getType
() ->canLosslesslyBitCastTo(F->getReturnType()) &&
"unexpected this return") ? static_cast<void> (0) : __assert_fail
("!F->arg_empty() && F->arg_begin()->getType() ->canLosslesslyBitCastTo(F->getReturnType()) && \"unexpected this return\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1935, __PRETTY_FUNCTION__))
;
1936 F->addAttribute(1, llvm::Attribute::Returned);
1937 }
1938
1939 // Only a few attributes are set on declarations; these may later be
1940 // overridden by a definition.
1941
1942 setLinkageForGV(F, FD);
1943 setGVProperties(F, FD);
1944
1945 // Setup target-specific attributes.
1946 if (!IsIncompleteFunction && F->isDeclaration())
1947 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1948
1949 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1950 F->setSection(CSA->getName());
1951 else if (const auto *SA = FD->getAttr<SectionAttr>())
1952 F->setSection(SA->getName());
1953
1954 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
1955 if (FD->isInlineBuiltinDeclaration()) {
1956 const FunctionDecl *FDBody;
1957 bool HasBody = FD->hasBody(FDBody);
1958 (void)HasBody;
1959 assert(HasBody && "Inline builtin declarations should always have an "((HasBody && "Inline builtin declarations should always have an "
"available body!") ? static_cast<void> (0) : __assert_fail
("HasBody && \"Inline builtin declarations should always have an \" \"available body!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1960, __PRETTY_FUNCTION__))
1960 "available body!")((HasBody && "Inline builtin declarations should always have an "
"available body!") ? static_cast<void> (0) : __assert_fail
("HasBody && \"Inline builtin declarations should always have an \" \"available body!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 1960, __PRETTY_FUNCTION__))
;
1961 if (shouldEmitFunction(FDBody))
1962 F->addAttribute(llvm::AttributeList::FunctionIndex,
1963 llvm::Attribute::NoBuiltin);
1964 }
1965
1966 if (FD->isReplaceableGlobalAllocationFunction()) {
1967 // A replaceable global allocation function does not act like a builtin by
1968 // default, only if it is invoked by a new-expression or delete-expression.
1969 F->addAttribute(llvm::AttributeList::FunctionIndex,
1970 llvm::Attribute::NoBuiltin);
1971 }
1972
1973 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1974 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1975 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1976 if (MD->isVirtual())
1977 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1978
1979 // Don't emit entries for function declarations in the cross-DSO mode. This
1980 // is handled with better precision by the receiving DSO. But if jump tables
1981 // are non-canonical then we need type metadata in order to produce the local
1982 // jump table.
1983 if (!CodeGenOpts.SanitizeCfiCrossDso ||
1984 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
1985 CreateFunctionTypeMetadataForIcall(FD, F);
1986
1987 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1988 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1989
1990 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
1991 // Annotate the callback behavior as metadata:
1992 // - The callback callee (as argument number).
1993 // - The callback payloads (as argument numbers).
1994 llvm::LLVMContext &Ctx = F->getContext();
1995 llvm::MDBuilder MDB(Ctx);
1996
1997 // The payload indices are all but the first one in the encoding. The first
1998 // identifies the callback callee.
1999 int CalleeIdx = *CB->encoding_begin();
2000 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2001 F->addMetadata(llvm::LLVMContext::MD_callback,
2002 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2003 CalleeIdx, PayloadIndices,
2004 /* VarArgsArePassed */ false)}));
2005 }
2006}
2007
2008void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2009 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&(((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
"Only globals with definition can force usage.") ? static_cast
<void> (0) : __assert_fail ("(isa<llvm::Function>(GV) || !GV->isDeclaration()) && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2010, __PRETTY_FUNCTION__))
2010 "Only globals with definition can force usage.")(((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
"Only globals with definition can force usage.") ? static_cast
<void> (0) : __assert_fail ("(isa<llvm::Function>(GV) || !GV->isDeclaration()) && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2010, __PRETTY_FUNCTION__))
;
2011 LLVMUsed.emplace_back(GV);
2012}
2013
2014void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2015 assert(!GV->isDeclaration() &&((!GV->isDeclaration() && "Only globals with definition can force usage."
) ? static_cast<void> (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2016, __PRETTY_FUNCTION__))
2016 "Only globals with definition can force usage.")((!GV->isDeclaration() && "Only globals with definition can force usage."
) ? static_cast<void> (0) : __assert_fail ("!GV->isDeclaration() && \"Only globals with definition can force usage.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2016, __PRETTY_FUNCTION__))
;
2017 LLVMCompilerUsed.emplace_back(GV);
2018}
2019
2020static void emitUsed(CodeGenModule &CGM, StringRef Name,
2021 std::vector<llvm::WeakTrackingVH> &List) {
2022 // Don't create llvm.used if there is no need.
2023 if (List.empty())
2024 return;
2025
2026 // Convert List to what ConstantArray needs.
2027 SmallVector<llvm::Constant*, 8> UsedArray;
2028 UsedArray.resize(List.size());
2029 for (unsigned i = 0, e = List.size(); i != e; ++i) {
2030 UsedArray[i] =
2031 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2032 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2033 }
2034
2035 if (UsedArray.empty())
2036 return;
2037 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2038
2039 auto *GV = new llvm::GlobalVariable(
2040 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2041 llvm::ConstantArray::get(ATy, UsedArray), Name);
2042
2043 GV->setSection("llvm.metadata");
2044}
2045
2046void CodeGenModule::emitLLVMUsed() {
2047 emitUsed(*this, "llvm.used", LLVMUsed);
2048 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2049}
2050
2051void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2052 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2053 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2054}
2055
2056void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2057 llvm::SmallString<32> Opt;
2058 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2059 if (Opt.empty())
2060 return;
2061 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2062 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2063}
2064
2065void CodeGenModule::AddDependentLib(StringRef Lib) {
2066 auto &C = getLLVMContext();
2067 if (getTarget().getTriple().isOSBinFormatELF()) {
2068 ELFDependentLibraries.push_back(
2069 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2070 return;
2071 }
2072
2073 llvm::SmallString<24> Opt;
2074 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2075 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2076 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2077}
2078
2079/// Add link options implied by the given module, including modules
2080/// it depends on, using a postorder walk.
2081static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2082 SmallVectorImpl<llvm::MDNode *> &Metadata,
2083 llvm::SmallPtrSet<Module *, 16> &Visited) {
2084 // Import this module's parent.
2085 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2086 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2087 }
2088
2089 // Import this module's dependencies.
2090 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
2091 if (Visited.insert(Mod->Imports[I - 1]).second)
2092 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
2093 }
2094
2095 // Add linker options to link against the libraries/frameworks
2096 // described by this module.
2097 llvm::LLVMContext &Context = CGM.getLLVMContext();
2098 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2099
2100 // For modules that use export_as for linking, use that module
2101 // name instead.
2102 if (Mod->UseExportAsModuleLinkName)
2103 return;
2104
2105 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
2106 // Link against a framework. Frameworks are currently Darwin only, so we
2107 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2108 if (Mod->LinkLibraries[I-1].IsFramework) {
2109 llvm::Metadata *Args[2] = {
2110 llvm::MDString::get(Context, "-framework"),
2111 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
2112
2113 Metadata.push_back(llvm::MDNode::get(Context, Args));
2114 continue;
2115 }
2116
2117 // Link against a library.
2118 if (IsELF) {
2119 llvm::Metadata *Args[2] = {
2120 llvm::MDString::get(Context, "lib"),
2121 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
2122 };
2123 Metadata.push_back(llvm::MDNode::get(Context, Args));
2124 } else {
2125 llvm::SmallString<24> Opt;
2126 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
2127 Mod->LinkLibraries[I - 1].Library, Opt);
2128 auto *OptString = llvm::MDString::get(Context, Opt);
2129 Metadata.push_back(llvm::MDNode::get(Context, OptString));
2130 }
2131 }
2132}
2133
2134void CodeGenModule::EmitModuleLinkOptions() {
2135 // Collect the set of all of the modules we want to visit to emit link
2136 // options, which is essentially the imported modules and all of their
2137 // non-explicit child modules.
2138 llvm::SetVector<clang::Module *> LinkModules;
2139 llvm::SmallPtrSet<clang::Module *, 16> Visited;
2140 SmallVector<clang::Module *, 16> Stack;
2141
2142 // Seed the stack with imported modules.
2143 for (Module *M : ImportedModules) {
2144 // Do not add any link flags when an implementation TU of a module imports
2145 // a header of that same module.
2146 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2147 !getLangOpts().isCompilingModule())
2148 continue;
2149 if (Visited.insert(M).second)
2150 Stack.push_back(M);
2151 }
2152
2153 // Find all of the modules to import, making a little effort to prune
2154 // non-leaf modules.
2155 while (!Stack.empty()) {
2156 clang::Module *Mod = Stack.pop_back_val();
2157
2158 bool AnyChildren = false;
2159
2160 // Visit the submodules of this module.
2161 for (const auto &SM : Mod->submodules()) {
2162 // Skip explicit children; they need to be explicitly imported to be
2163 // linked against.
2164 if (SM->IsExplicit)
2165 continue;
2166
2167 if (Visited.insert(SM).second) {
2168 Stack.push_back(SM);
2169 AnyChildren = true;
2170 }
2171 }
2172
2173 // We didn't find any children, so add this module to the list of
2174 // modules to link against.
2175 if (!AnyChildren) {
2176 LinkModules.insert(Mod);
2177 }
2178 }
2179
2180 // Add link options for all of the imported modules in reverse topological
2181 // order. We don't do anything to try to order import link flags with respect
2182 // to linker options inserted by things like #pragma comment().
2183 SmallVector<llvm::MDNode *, 16> MetadataArgs;
2184 Visited.clear();
2185 for (Module *M : LinkModules)
2186 if (Visited.insert(M).second)
2187 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2188 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2189 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2190
2191 // Add the linker options metadata flag.
2192 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2193 for (auto *MD : LinkerOptionsMetadata)
2194 NMD->addOperand(MD);
2195}
2196
2197void CodeGenModule::EmitDeferred() {
2198 // Emit deferred declare target declarations.
2199 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2200 getOpenMPRuntime().emitDeferredTargetDecls();
2201
2202 // Emit code for any potentially referenced deferred decls. Since a
2203 // previously unused static decl may become used during the generation of code
2204 // for a static function, iterate until no changes are made.
2205
2206 if (!DeferredVTables.empty()) {
2207 EmitDeferredVTables();
2208
2209 // Emitting a vtable doesn't directly cause more vtables to
2210 // become deferred, although it can cause functions to be
2211 // emitted that then need those vtables.
2212 assert(DeferredVTables.empty())((DeferredVTables.empty()) ? static_cast<void> (0) : __assert_fail
("DeferredVTables.empty()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2212, __PRETTY_FUNCTION__))
;
2213 }
2214
2215 // Emit CUDA/HIP static device variables referenced by host code only.
2216 if (getLangOpts().CUDA)
2217 for (auto V : getContext().CUDAStaticDeviceVarReferencedByHost)
2218 DeferredDeclsToEmit.push_back(V);
2219
2220 // Stop if we're out of both deferred vtables and deferred declarations.
2221 if (DeferredDeclsToEmit.empty())
2222 return;
2223
2224 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2225 // work, it will not interfere with this.
2226 std::vector<GlobalDecl> CurDeclsToEmit;
2227 CurDeclsToEmit.swap(DeferredDeclsToEmit);
2228
2229 for (GlobalDecl &D : CurDeclsToEmit) {
2230 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2231 // to get GlobalValue with exactly the type we need, not something that
2232 // might had been created for another decl with the same mangled name but
2233 // different type.
2234 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2235 GetAddrOfGlobal(D, ForDefinition));
2236
2237 // In case of different address spaces, we may still get a cast, even with
2238 // IsForDefinition equal to true. Query mangled names table to get
2239 // GlobalValue.
2240 if (!GV)
2241 GV = GetGlobalValue(getMangledName(D));
2242
2243 // Make sure GetGlobalValue returned non-null.
2244 assert(GV)((GV) ? static_cast<void> (0) : __assert_fail ("GV", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2244, __PRETTY_FUNCTION__))
;
2245
2246 // Check to see if we've already emitted this. This is necessary
2247 // for a couple of reasons: first, decls can end up in the
2248 // deferred-decls queue multiple times, and second, decls can end
2249 // up with definitions in unusual ways (e.g. by an extern inline
2250 // function acquiring a strong function redefinition). Just
2251 // ignore these cases.
2252 if (!GV->isDeclaration())
2253 continue;
2254
2255 // If this is OpenMP, check if it is legal to emit this global normally.
2256 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2257 continue;
2258
2259 // Otherwise, emit the definition and move on to the next one.
2260 EmitGlobalDefinition(D, GV);
2261
2262 // If we found out that we need to emit more decls, do that recursively.
2263 // This has the advantage that the decls are emitted in a DFS and related
2264 // ones are close together, which is convenient for testing.
2265 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2266 EmitDeferred();
2267 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty())((DeferredVTables.empty() && DeferredDeclsToEmit.empty
()) ? static_cast<void> (0) : __assert_fail ("DeferredVTables.empty() && DeferredDeclsToEmit.empty()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2267, __PRETTY_FUNCTION__))
;
2268 }
2269 }
2270}
2271
2272void CodeGenModule::EmitVTablesOpportunistically() {
2273 // Try to emit external vtables as available_externally if they have emitted
2274 // all inlined virtual functions. It runs after EmitDeferred() and therefore
2275 // is not allowed to create new references to things that need to be emitted
2276 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2277
2278 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())(((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables
()) && "Only emit opportunistic vtables with optimizations"
) ? static_cast<void> (0) : __assert_fail ("(OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) && \"Only emit opportunistic vtables with optimizations\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2279, __PRETTY_FUNCTION__))
2279 && "Only emit opportunistic vtables with optimizations")(((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables
()) && "Only emit opportunistic vtables with optimizations"
) ? static_cast<void> (0) : __assert_fail ("(OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) && \"Only emit opportunistic vtables with optimizations\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2279, __PRETTY_FUNCTION__))
;
2280
2281 for (const CXXRecordDecl *RD : OpportunisticVTables) {
2282 assert(getVTables().isVTableExternal(RD) &&((getVTables().isVTableExternal(RD) && "This queue should only contain external vtables"
) ? static_cast<void> (0) : __assert_fail ("getVTables().isVTableExternal(RD) && \"This queue should only contain external vtables\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2283, __PRETTY_FUNCTION__))
2283 "This queue should only contain external vtables")((getVTables().isVTableExternal(RD) && "This queue should only contain external vtables"
) ? static_cast<void> (0) : __assert_fail ("getVTables().isVTableExternal(RD) && \"This queue should only contain external vtables\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2283, __PRETTY_FUNCTION__))
;
2284 if (getCXXABI().canSpeculativelyEmitVTable(RD))
2285 VTables.GenerateClassData(RD);
2286 }
2287 OpportunisticVTables.clear();
2288}
2289
2290void CodeGenModule::EmitGlobalAnnotations() {
2291 if (Annotations.empty())
2292 return;
2293
2294 // Create a new global variable for the ConstantStruct in the Module.
2295 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2296 Annotations[0]->getType(), Annotations.size()), Annotations);
2297 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2298 llvm::GlobalValue::AppendingLinkage,
2299 Array, "llvm.global.annotations");
2300 gv->setSection(AnnotationSection);
2301}
2302
2303llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2304 llvm::Constant *&AStr = AnnotationStrings[Str];
2305 if (AStr)
2306 return AStr;
2307
2308 // Not found yet, create a new global.
2309 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2310 auto *gv =
2311 new llvm::GlobalVariable(getModule(), s->getType(), true,
2312 llvm::GlobalValue::PrivateLinkage, s, ".str");
2313 gv->setSection(AnnotationSection);
2314 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2315 AStr = gv;
2316 return gv;
2317}
2318
2319llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2320 SourceManager &SM = getContext().getSourceManager();
2321 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2322 if (PLoc.isValid())
2323 return EmitAnnotationString(PLoc.getFilename());
2324 return EmitAnnotationString(SM.getBufferName(Loc));
2325}
2326
2327llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2328 SourceManager &SM = getContext().getSourceManager();
2329 PresumedLoc PLoc = SM.getPresumedLoc(L);
2330 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2331 SM.getExpansionLineNumber(L);
2332 return llvm::ConstantInt::get(Int32Ty, LineNo);
2333}
2334
2335llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2336 const AnnotateAttr *AA,
2337 SourceLocation L) {
2338 // Get the globals for file name, annotation, and the line number.
2339 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2340 *UnitGV = EmitAnnotationUnit(L),
2341 *LineNoCst = EmitAnnotationLineNo(L);
2342
2343 llvm::Constant *ASZeroGV = GV;
2344 if (GV->getAddressSpace() != 0) {
2345 ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2346 GV, GV->getValueType()->getPointerTo(0));
2347 }
2348
2349 // Create the ConstantStruct for the global annotation.
2350 llvm::Constant *Fields[4] = {
2351 llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
2352 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
2353 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2354 LineNoCst
2355 };
2356 return llvm::ConstantStruct::getAnon(Fields);
2357}
2358
2359void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2360 llvm::GlobalValue *GV) {
2361 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute")((D->hasAttr<AnnotateAttr>() && "no annotate attribute"
) ? static_cast<void> (0) : __assert_fail ("D->hasAttr<AnnotateAttr>() && \"no annotate attribute\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2361, __PRETTY_FUNCTION__))
;
2362 // Get the struct elements for these annotations.
2363 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2364 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2365}
2366
2367bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
2368 llvm::Function *Fn,
2369 SourceLocation Loc) const {
2370 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2371 // Blacklist by function name.
2372 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
2373 return true;
2374 // Blacklist by location.
2375 if (Loc.isValid())
2376 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
2377 // If location is unknown, this may be a compiler-generated function. Assume
2378 // it's located in the main file.
2379 auto &SM = Context.getSourceManager();
2380 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2381 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
2382 }
2383 return false;
2384}
2385
2386bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
2387 SourceLocation Loc, QualType Ty,
2388 StringRef Category) const {
2389 // For now globals can be blacklisted only in ASan and KASan.
2390 const SanitizerMask EnabledAsanMask =
2391 LangOpts.Sanitize.Mask &
2392 (SanitizerKind::Address | SanitizerKind::KernelAddress |
2393 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2394 SanitizerKind::MemTag);
2395 if (!EnabledAsanMask)
2396 return false;
2397 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2398 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
2399 return true;
2400 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
2401 return true;
2402 // Check global type.
2403 if (!Ty.isNull()) {
2404 // Drill down the array types: if global variable of a fixed type is
2405 // blacklisted, we also don't instrument arrays of them.
2406 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2407 Ty = AT->getElementType();
2408 Ty = Ty.getCanonicalType().getUnqualifiedType();
2409 // We allow to blacklist only record types (classes, structs etc.)
2410 if (Ty->isRecordType()) {
2411 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2412 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
2413 return true;
2414 }
2415 }
2416 return false;
2417}
2418
2419bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2420 StringRef Category) const {
2421 const auto &XRayFilter = getContext().getXRayFilter();
2422 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2423 auto Attr = ImbueAttr::NONE;
2424 if (Loc.isValid())
2425 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2426 if (Attr == ImbueAttr::NONE)
2427 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2428 switch (Attr) {
2429 case ImbueAttr::NONE:
2430 return false;
2431 case ImbueAttr::ALWAYS:
2432 Fn->addFnAttr("function-instrument", "xray-always");
2433 break;
2434 case ImbueAttr::ALWAYS_ARG1:
2435 Fn->addFnAttr("function-instrument", "xray-always");
2436 Fn->addFnAttr("xray-log-args", "1");
2437 break;
2438 case ImbueAttr::NEVER:
2439 Fn->addFnAttr("function-instrument", "xray-never");
2440 break;
2441 }
2442 return true;
2443}
2444
2445bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2446 // Never defer when EmitAllDecls is specified.
2447 if (LangOpts.EmitAllDecls)
2448 return true;
2449
2450 if (CodeGenOpts.KeepStaticConsts) {
2451 const auto *VD = dyn_cast<VarDecl>(Global);
2452 if (VD && VD->getType().isConstQualified() &&
2453 VD->getStorageDuration() == SD_Static)
2454 return true;
2455 }
2456
2457 return getContext().DeclMustBeEmitted(Global);
2458}
2459
2460bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2461 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2462 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2463 // Implicit template instantiations may change linkage if they are later
2464 // explicitly instantiated, so they should not be emitted eagerly.
2465 return false;
2466 // In OpenMP 5.0 function may be marked as device_type(nohost) and we should
2467 // not emit them eagerly unless we sure that the function must be emitted on
2468 // the host.
2469 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd &&
2470 !LangOpts.OpenMPIsDevice &&
2471 !OMPDeclareTargetDeclAttr::getDeviceType(FD) &&
2472 !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced())
2473 return false;
2474 }
2475 if (const auto *VD = dyn_cast<VarDecl>(Global))
2476 if (Context.getInlineVariableDefinitionKind(VD) ==
2477 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2478 // A definition of an inline constexpr static data member may change
2479 // linkage later if it's redeclared outside the class.
2480 return false;
2481 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2482 // codegen for global variables, because they may be marked as threadprivate.
2483 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2484 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2485 !isTypeConstant(Global->getType(), false) &&
2486 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2487 return false;
2488
2489 return true;
2490}
2491
2492ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
2493 StringRef Name = getMangledName(GD);
2494
2495 // The UUID descriptor should be pointer aligned.
2496 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2497
2498 // Look for an existing global.
2499 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2500 return ConstantAddress(GV, Alignment);
2501
2502 ConstantEmitter Emitter(*this);
2503 llvm::Constant *Init;
2504
2505 APValue &V = GD->getAsAPValue();
2506 if (!V.isAbsent()) {
2507 // If possible, emit the APValue version of the initializer. In particular,
2508 // this gets the type of the constant right.
2509 Init = Emitter.emitForInitializer(
2510 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
2511 } else {
2512 // As a fallback, directly construct the constant.
2513 // FIXME: This may get padding wrong under esoteric struct layout rules.
2514 // MSVC appears to create a complete type 'struct __s_GUID' that it
2515 // presumably uses to represent these constants.
2516 MSGuidDecl::Parts Parts = GD->getParts();
2517 llvm::Constant *Fields[4] = {
2518 llvm::ConstantInt::get(Int32Ty, Parts.Part1),
2519 llvm::ConstantInt::get(Int16Ty, Parts.Part2),
2520 llvm::ConstantInt::get(Int16Ty, Parts.Part3),
2521 llvm::ConstantDataArray::getRaw(
2522 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
2523 Int8Ty)};
2524 Init = llvm::ConstantStruct::getAnon(Fields);
2525 }
2526
2527 auto *GV = new llvm::GlobalVariable(
2528 getModule(), Init->getType(),
2529 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2530 if (supportsCOMDAT())
2531 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2532 setDSOLocal(GV);
2533
2534 llvm::Constant *Addr = GV;
2535 if (!V.isAbsent()) {
2536 Emitter.finalize(GV);
2537 } else {
2538 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
2539 Addr = llvm::ConstantExpr::getBitCast(
2540 GV, Ty->getPointerTo(GV->getAddressSpace()));
2541 }
2542 return ConstantAddress(Addr, Alignment);
2543}
2544
2545ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2546 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2547 assert(AA && "No alias?")((AA && "No alias?") ? static_cast<void> (0) : __assert_fail
("AA && \"No alias?\"", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2547, __PRETTY_FUNCTION__))
;
2548
2549 CharUnits Alignment = getContext().getDeclAlign(VD);
2550 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2551
2552 // See if there is already something with the target's name in the module.
2553 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2554 if (Entry) {
2555 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2556 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2557 return ConstantAddress(Ptr, Alignment);
2558 }
2559
2560 llvm::Constant *Aliasee;
2561 if (isa<llvm::FunctionType>(DeclTy))
2562 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2563 GlobalDecl(cast<FunctionDecl>(VD)),
2564 /*ForVTable=*/false);
2565 else
2566 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2567 llvm::PointerType::getUnqual(DeclTy),
2568 nullptr);
2569
2570 auto *F = cast<llvm::GlobalValue>(Aliasee);
2571 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2572 WeakRefReferences.insert(F);
2573
2574 return ConstantAddress(Aliasee, Alignment);
2575}
2576
2577void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2578 const auto *Global = cast<ValueDecl>(GD.getDecl());
2579
2580 // Weak references don't produce any output by themselves.
2581 if (Global->hasAttr<WeakRefAttr>())
2582 return;
2583
2584 // If this is an alias definition (which otherwise looks like a declaration)
2585 // emit it now.
2586 if (Global->hasAttr<AliasAttr>())
2587 return EmitAliasDefinition(GD);
2588
2589 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2590 if (Global->hasAttr<IFuncAttr>())
2591 return emitIFuncDefinition(GD);
2592
2593 // If this is a cpu_dispatch multiversion function, emit the resolver.
2594 if (Global->hasAttr<CPUDispatchAttr>())
2595 return emitCPUDispatchDefinition(GD);
2596
2597 // If this is CUDA, be selective about which declarations we emit.
2598 if (LangOpts.CUDA) {
2599 if (LangOpts.CUDAIsDevice) {
2600 if (!Global->hasAttr<CUDADeviceAttr>() &&
2601 !Global->hasAttr<CUDAGlobalAttr>() &&
2602 !Global->hasAttr<CUDAConstantAttr>() &&
2603 !Global->hasAttr<CUDASharedAttr>() &&
2604 !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
2605 !Global->getType()->isCUDADeviceBuiltinTextureType())
2606 return;
2607 } else {
2608 // We need to emit host-side 'shadows' for all global
2609 // device-side variables because the CUDA runtime needs their
2610 // size and host-side address in order to provide access to
2611 // their device-side incarnations.
2612
2613 // So device-only functions are the only things we skip.
2614 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2615 Global->hasAttr<CUDADeviceAttr>())
2616 return;
2617
2618 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&(((isa<FunctionDecl>(Global) || isa<VarDecl>(Global
)) && "Expected Variable or Function") ? static_cast<
void> (0) : __assert_fail ("(isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && \"Expected Variable or Function\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2619, __PRETTY_FUNCTION__))
2619 "Expected Variable or Function")(((isa<FunctionDecl>(Global) || isa<VarDecl>(Global
)) && "Expected Variable or Function") ? static_cast<
void> (0) : __assert_fail ("(isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && \"Expected Variable or Function\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2619, __PRETTY_FUNCTION__))
;
2620 }
2621 }
2622
2623 if (LangOpts.OpenMP) {
2624 // If this is OpenMP, check if it is legal to emit this global normally.
2625 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2626 return;
2627 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2628 if (MustBeEmitted(Global))
2629 EmitOMPDeclareReduction(DRD);
2630 return;
2631 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2632 if (MustBeEmitted(Global))
2633 EmitOMPDeclareMapper(DMD);
2634 return;
2635 }
2636 }
2637
2638 // Ignore declarations, they will be emitted on their first use.
2639 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2640 // Forward declarations are emitted lazily on first use.
2641 if (!FD->doesThisDeclarationHaveABody()) {
2642 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2643 return;
2644
2645 StringRef MangledName = getMangledName(GD);
2646
2647 // Compute the function info and LLVM type.
2648 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2649 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2650
2651 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2652 /*DontDefer=*/false);
2653 return;
2654 }
2655 } else {
2656 const auto *VD = cast<VarDecl>(Global);
2657 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.")((VD->isFileVarDecl() && "Cannot emit local var decl as global."
) ? static_cast<void> (0) : __assert_fail ("VD->isFileVarDecl() && \"Cannot emit local var decl as global.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2657, __PRETTY_FUNCTION__))
;
2658 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2659 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2660 if (LangOpts.OpenMP) {
2661 // Emit declaration of the must-be-emitted declare target variable.
2662 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2663 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2664 bool UnifiedMemoryEnabled =
2665 getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
2666 if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2667 !UnifiedMemoryEnabled) {
2668 (void)GetAddrOfGlobalVar(VD);
2669 } else {
2670 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||((((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr
::MT_To && UnifiedMemoryEnabled)) && "Link clause or to clause with unified memory expected."
) ? static_cast<void> (0) : __assert_fail ("((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To && UnifiedMemoryEnabled)) && \"Link clause or to clause with unified memory expected.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2673, __PRETTY_FUNCTION__))
2671 (*Res == OMPDeclareTargetDeclAttr::MT_To &&((((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr
::MT_To && UnifiedMemoryEnabled)) && "Link clause or to clause with unified memory expected."
) ? static_cast<void> (0) : __assert_fail ("((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To && UnifiedMemoryEnabled)) && \"Link clause or to clause with unified memory expected.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2673, __PRETTY_FUNCTION__))
2672 UnifiedMemoryEnabled)) &&((((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr
::MT_To && UnifiedMemoryEnabled)) && "Link clause or to clause with unified memory expected."
) ? static_cast<void> (0) : __assert_fail ("((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To && UnifiedMemoryEnabled)) && \"Link clause or to clause with unified memory expected.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2673, __PRETTY_FUNCTION__))
2673 "Link clause or to clause with unified memory expected.")((((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr
::MT_To && UnifiedMemoryEnabled)) && "Link clause or to clause with unified memory expected."
) ? static_cast<void> (0) : __assert_fail ("((*Res == OMPDeclareTargetDeclAttr::MT_Link) || (*Res == OMPDeclareTargetDeclAttr::MT_To && UnifiedMemoryEnabled)) && \"Link clause or to clause with unified memory expected.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2673, __PRETTY_FUNCTION__))
;
2674 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2675 }
2676
2677 return;
2678 }
2679 }
2680 // If this declaration may have caused an inline variable definition to
2681 // change linkage, make sure that it's emitted.
2682 if (Context.getInlineVariableDefinitionKind(VD) ==
2683 ASTContext::InlineVariableDefinitionKind::Strong)
2684 GetAddrOfGlobalVar(VD);
2685 return;
2686 }
2687 }
2688
2689 // Defer code generation to first use when possible, e.g. if this is an inline
2690 // function. If the global must always be emitted, do it eagerly if possible
2691 // to benefit from cache locality.
2692 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2693 // Emit the definition if it can't be deferred.
2694 EmitGlobalDefinition(GD);
2695 return;
2696 }
2697
2698 // If we're deferring emission of a C++ variable with an
2699 // initializer, remember the order in which it appeared in the file.
2700 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2701 cast<VarDecl>(Global)->hasInit()) {
2702 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2703 CXXGlobalInits.push_back(nullptr);
2704 }
2705
2706 StringRef MangledName = getMangledName(GD);
2707 if (GetGlobalValue(MangledName) != nullptr) {
2708 // The value has already been used and should therefore be emitted.
2709 addDeferredDeclToEmit(GD);
2710 } else if (MustBeEmitted(Global)) {
2711 // The value must be emitted, but cannot be emitted eagerly.
2712 assert(!MayBeEmittedEagerly(Global))((!MayBeEmittedEagerly(Global)) ? static_cast<void> (0)
: __assert_fail ("!MayBeEmittedEagerly(Global)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2712, __PRETTY_FUNCTION__))
;
2713 addDeferredDeclToEmit(GD);
2714 } else {
2715 // Otherwise, remember that we saw a deferred decl with this name. The
2716 // first use of the mangled name will cause it to move into
2717 // DeferredDeclsToEmit.
2718 DeferredDecls[MangledName] = GD;
2719 }
2720}
2721
2722// Check if T is a class type with a destructor that's not dllimport.
2723static bool HasNonDllImportDtor(QualType T) {
2724 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2725 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2726 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2727 return true;
2728
2729 return false;
2730}
2731
2732namespace {
2733 struct FunctionIsDirectlyRecursive
2734 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
2735 const StringRef Name;
2736 const Builtin::Context &BI;
2737 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
2738 : Name(N), BI(C) {}
2739
2740 bool VisitCallExpr(const CallExpr *E) {
2741 const FunctionDecl *FD = E->getDirectCallee();
2742 if (!FD)
2743 return false;
2744 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2745 if (Attr && Name == Attr->getLabel())
2746 return true;
2747 unsigned BuiltinID = FD->getBuiltinID();
2748 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2749 return false;
2750 StringRef BuiltinName = BI.getName(BuiltinID);
2751 if (BuiltinName.startswith("__builtin_") &&
2752 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2753 return true;
2754 }
2755 return false;
2756 }
2757
2758 bool VisitStmt(const Stmt *S) {
2759 for (const Stmt *Child : S->children())
2760 if (Child && this->Visit(Child))
2761 return true;
2762 return false;
2763 }
2764 };
2765
2766 // Make sure we're not referencing non-imported vars or functions.
2767 struct DLLImportFunctionVisitor
2768 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2769 bool SafeToInline = true;
2770
2771 bool shouldVisitImplicitCode() const { return true; }
2772
2773 bool VisitVarDecl(VarDecl *VD) {
2774 if (VD->getTLSKind()) {
2775 // A thread-local variable cannot be imported.
2776 SafeToInline = false;
2777 return SafeToInline;
2778 }
2779
2780 // A variable definition might imply a destructor call.
2781 if (VD->isThisDeclarationADefinition())
2782 SafeToInline = !HasNonDllImportDtor(VD->getType());
2783
2784 return SafeToInline;
2785 }
2786
2787 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2788 if (const auto *D = E->getTemporary()->getDestructor())
2789 SafeToInline = D->hasAttr<DLLImportAttr>();
2790 return SafeToInline;
2791 }
2792
2793 bool VisitDeclRefExpr(DeclRefExpr *E) {
2794 ValueDecl *VD = E->getDecl();
2795 if (isa<FunctionDecl>(VD))
2796 SafeToInline = VD->hasAttr<DLLImportAttr>();
2797 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2798 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2799 return SafeToInline;
2800 }
2801
2802 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2803 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2804 return SafeToInline;
2805 }
2806
2807 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2808 CXXMethodDecl *M = E->getMethodDecl();
2809 if (!M) {
2810 // Call through a pointer to member function. This is safe to inline.
2811 SafeToInline = true;
2812 } else {
2813 SafeToInline = M->hasAttr<DLLImportAttr>();
2814 }
2815 return SafeToInline;
2816 }
2817
2818 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2819 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2820 return SafeToInline;
2821 }
2822
2823 bool VisitCXXNewExpr(CXXNewExpr *E) {
2824 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2825 return SafeToInline;
2826 }
2827 };
2828}
2829
2830// isTriviallyRecursive - Check if this function calls another
2831// decl that, because of the asm attribute or the other decl being a builtin,
2832// ends up pointing to itself.
2833bool
2834CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2835 StringRef Name;
2836 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2837 // asm labels are a special kind of mangling we have to support.
2838 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2839 if (!Attr)
2840 return false;
2841 Name = Attr->getLabel();
2842 } else {
2843 Name = FD->getName();
2844 }
2845
2846 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2847 const Stmt *Body = FD->getBody();
2848 return Body ? Walker.Visit(Body) : false;
2849}
2850
2851bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2852 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2853 return true;
2854 const auto *F = cast<FunctionDecl>(GD.getDecl());
2855 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2856 return false;
2857
2858 if (F->hasAttr<DLLImportAttr>()) {
2859 // Check whether it would be safe to inline this dllimport function.
2860 DLLImportFunctionVisitor Visitor;
2861 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2862 if (!Visitor.SafeToInline)
2863 return false;
2864
2865 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2866 // Implicit destructor invocations aren't captured in the AST, so the
2867 // check above can't see them. Check for them manually here.
2868 for (const Decl *Member : Dtor->getParent()->decls())
2869 if (isa<FieldDecl>(Member))
2870 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2871 return false;
2872 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2873 if (HasNonDllImportDtor(B.getType()))
2874 return false;
2875 }
2876 }
2877
2878 // PR9614. Avoid cases where the source code is lying to us. An available
2879 // externally function should have an equivalent function somewhere else,
2880 // but a function that calls itself through asm label/`__builtin_` trickery is
2881 // clearly not equivalent to the real implementation.
2882 // This happens in glibc's btowc and in some configure checks.
2883 return !isTriviallyRecursive(F);
2884}
2885
2886bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2887 return CodeGenOpts.OptimizationLevel > 0;
2888}
2889
2890void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
2891 llvm::GlobalValue *GV) {
2892 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2893
2894 if (FD->isCPUSpecificMultiVersion()) {
2895 auto *Spec = FD->getAttr<CPUSpecificAttr>();
2896 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
2897 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
2898 // Requires multiple emits.
2899 } else
2900 EmitGlobalFunctionDefinition(GD, GV);
2901}
2902
2903void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2904 const auto *D = cast<ValueDecl>(GD.getDecl());
2905
2906 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2907 Context.getSourceManager(),
2908 "Generating code for declaration");
2909
2910 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2911 // At -O0, don't generate IR for functions with available_externally
2912 // linkage.
2913 if (!shouldEmitFunction(GD))
2914 return;
2915
2916 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
2917 std::string Name;
2918 llvm::raw_string_ostream OS(Name);
2919 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
2920 /*Qualified=*/true);
2921 return Name;
2922 });
2923
2924 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2925 // Make sure to emit the definition(s) before we emit the thunks.
2926 // This is necessary for the generation of certain thunks.
2927 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
2928 ABI->emitCXXStructor(GD);
2929 else if (FD->isMultiVersion())
2930 EmitMultiVersionFunctionDefinition(GD, GV);
2931 else
2932 EmitGlobalFunctionDefinition(GD, GV);
2933
2934 if (Method->isVirtual())
2935 getVTables().EmitThunks(GD);
2936
2937 return;
2938 }
2939
2940 if (FD->isMultiVersion())
2941 return EmitMultiVersionFunctionDefinition(GD, GV);
2942 return EmitGlobalFunctionDefinition(GD, GV);
2943 }
2944
2945 if (const auto *VD = dyn_cast<VarDecl>(D))
2946 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2947
2948 llvm_unreachable("Invalid argument to EmitGlobalDefinition()")::llvm::llvm_unreachable_internal("Invalid argument to EmitGlobalDefinition()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2948)
;
2949}
2950
2951static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2952 llvm::Function *NewFn);
2953
2954static unsigned
2955TargetMVPriority(const TargetInfo &TI,
2956 const CodeGenFunction::MultiVersionResolverOption &RO) {
2957 unsigned Priority = 0;
2958 for (StringRef Feat : RO.Conditions.Features)
2959 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2960
2961 if (!RO.Conditions.Architecture.empty())
2962 Priority = std::max(
2963 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2964 return Priority;
2965}
2966
2967void CodeGenModule::emitMultiVersionFunctions() {
2968 for (GlobalDecl GD : MultiVersionFuncs) {
2969 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2970 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2971 getContext().forEachMultiversionedFunctionVersion(
2972 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2973 GlobalDecl CurGD{
2974 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2975 StringRef MangledName = getMangledName(CurGD);
2976 llvm::Constant *Func = GetGlobalValue(MangledName);
2977 if (!Func) {
2978 if (CurFD->isDefined()) {
2979 EmitGlobalFunctionDefinition(CurGD, nullptr);
2980 Func = GetGlobalValue(MangledName);
2981 } else {
2982 const CGFunctionInfo &FI =
2983 getTypes().arrangeGlobalDeclaration(GD);
2984 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2985 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2986 /*DontDefer=*/false, ForDefinition);
2987 }
2988 assert(Func && "This should have just been created")((Func && "This should have just been created") ? static_cast
<void> (0) : __assert_fail ("Func && \"This should have just been created\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 2988, __PRETTY_FUNCTION__))
;
2989 }
2990
2991 const auto *TA = CurFD->getAttr<TargetAttr>();
2992 llvm::SmallVector<StringRef, 8> Feats;
2993 TA->getAddedFeatures(Feats);
2994
2995 Options.emplace_back(cast<llvm::Function>(Func),
2996 TA->getArchitecture(), Feats);
2997 });
2998
2999 llvm::Function *ResolverFunc;
3000 const TargetInfo &TI = getTarget();
3001
3002 if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
3003 ResolverFunc = cast<llvm::Function>(
3004 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
3005 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3006 } else {
3007 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
3008 }
3009
3010 if (supportsCOMDAT())
3011 ResolverFunc->setComdat(
3012 getModule().getOrInsertComdat(ResolverFunc->getName()));
3013
3014 llvm::stable_sort(
3015 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3016 const CodeGenFunction::MultiVersionResolverOption &RHS) {
3017 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3018 });
3019 CodeGenFunction CGF(*this);
3020 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3021 }
3022}
3023
3024void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3025 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3026 assert(FD && "Not a FunctionDecl?")((FD && "Not a FunctionDecl?") ? static_cast<void>
(0) : __assert_fail ("FD && \"Not a FunctionDecl?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3026, __PRETTY_FUNCTION__))
;
3027 const auto *DD = FD->getAttr<CPUDispatchAttr>();
3028 assert(DD && "Not a cpu_dispatch Function?")((DD && "Not a cpu_dispatch Function?") ? static_cast
<void> (0) : __assert_fail ("DD && \"Not a cpu_dispatch Function?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3028, __PRETTY_FUNCTION__))
;
3029 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
3030
3031 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
3032 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
3033 DeclTy = getTypes().GetFunctionType(FInfo);
3034 }
3035
3036 StringRef ResolverName = getMangledName(GD);
3037
3038 llvm::Type *ResolverType;
3039 GlobalDecl ResolverGD;
3040 if (getTarget().supportsIFunc())
3041 ResolverType = llvm::FunctionType::get(
3042 llvm::PointerType::get(DeclTy,
3043 Context.getTargetAddressSpace(FD->getType())),
3044 false);
3045 else {
3046 ResolverType = DeclTy;
3047 ResolverGD = GD;
3048 }
3049
3050 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3051 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3052 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3053 if (supportsCOMDAT())
3054 ResolverFunc->setComdat(
3055 getModule().getOrInsertComdat(ResolverFunc->getName()));
3056
3057 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3058 const TargetInfo &Target = getTarget();
3059 unsigned Index = 0;
3060 for (const IdentifierInfo *II : DD->cpus()) {
3061 // Get the name of the target function so we can look it up/create it.
3062 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3063 getCPUSpecificMangling(*this, II->getName());
3064
3065 llvm::Constant *Func = GetGlobalValue(MangledName);
3066
3067 if (!Func) {
3068 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3069 if (ExistingDecl.getDecl() &&
3070 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3071 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3072 Func = GetGlobalValue(MangledName);
3073 } else {
3074 if (!ExistingDecl.getDecl())
3075 ExistingDecl = GD.getWithMultiVersionIndex(Index);
3076
3077 Func = GetOrCreateLLVMFunction(
3078 MangledName, DeclTy, ExistingDecl,
3079 /*ForVTable=*/false, /*DontDefer=*/true,
3080 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3081 }
3082 }
3083
3084 llvm::SmallVector<StringRef, 32> Features;
3085 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3086 llvm::transform(Features, Features.begin(),
3087 [](StringRef Str) { return Str.substr(1); });
3088 Features.erase(std::remove_if(
3089 Features.begin(), Features.end(), [&Target](StringRef Feat) {
3090 return !Target.validateCpuSupports(Feat);
3091 }), Features.end());
3092 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3093 ++Index;
3094 }
3095
3096 llvm::sort(
3097 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3098 const CodeGenFunction::MultiVersionResolverOption &RHS) {
3099 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3100 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3101 });
3102
3103 // If the list contains multiple 'default' versions, such as when it contains
3104 // 'pentium' and 'generic', don't emit the call to the generic one (since we
3105 // always run on at least a 'pentium'). We do this by deleting the 'least
3106 // advanced' (read, lowest mangling letter).
3107 while (Options.size() > 1 &&
3108 CodeGenFunction::GetX86CpuSupportsMask(
3109 (Options.end() - 2)->Conditions.Features) == 0) {
3110 StringRef LHSName = (Options.end() - 2)->Function->getName();
3111 StringRef RHSName = (Options.end() - 1)->Function->getName();
3112 if (LHSName.compare(RHSName) < 0)
3113 Options.erase(Options.end() - 2);
3114 else
3115 Options.erase(Options.end() - 1);
3116 }
3117
3118 CodeGenFunction CGF(*this);
3119 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3120
3121 if (getTarget().supportsIFunc()) {
3122 std::string AliasName = getMangledNameImpl(
3123 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3124 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3125 if (!AliasFunc) {
3126 auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3127 AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3128 /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3129 auto *GA = llvm::GlobalAlias::create(
3130 DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3131 GA->setLinkage(llvm::Function::WeakODRLinkage);
3132 SetCommonAttributes(GD, GA);
3133 }
3134 }
3135}
3136
3137/// If a dispatcher for the specified mangled name is not in the module, create
3138/// and return an llvm Function with the specified type.
3139llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3140 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3141 std::string MangledName =
3142 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3143
3144 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3145 // a separate resolver).
3146 std::string ResolverName = MangledName;
3147 if (getTarget().supportsIFunc())
3148 ResolverName += ".ifunc";
3149 else if (FD->isTargetMultiVersion())
3150 ResolverName += ".resolver";
3151
3152 // If this already exists, just return that one.
3153 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3154 return ResolverGV;
3155
3156 // Since this is the first time we've created this IFunc, make sure
3157 // that we put this multiversioned function into the list to be
3158 // replaced later if necessary (target multiversioning only).
3159 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
3160 MultiVersionFuncs.push_back(GD);
3161
3162 if (getTarget().supportsIFunc()) {
3163 llvm::Type *ResolverType = llvm::FunctionType::get(
3164 llvm::PointerType::get(
3165 DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3166 false);
3167 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3168 MangledName + ".resolver", ResolverType, GlobalDecl{},
3169 /*ForVTable=*/false);
3170 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3171 DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3172 GIF->setName(ResolverName);
3173 SetCommonAttributes(FD, GIF);
3174
3175 return GIF;
3176 }
3177
3178 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3179 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3180 assert(isa<llvm::GlobalValue>(Resolver) &&((isa<llvm::GlobalValue>(Resolver) && "Resolver should be created for the first time"
) ? static_cast<void> (0) : __assert_fail ("isa<llvm::GlobalValue>(Resolver) && \"Resolver should be created for the first time\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3181, __PRETTY_FUNCTION__))
3181 "Resolver should be created for the first time")((isa<llvm::GlobalValue>(Resolver) && "Resolver should be created for the first time"
) ? static_cast<void> (0) : __assert_fail ("isa<llvm::GlobalValue>(Resolver) && \"Resolver should be created for the first time\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3181, __PRETTY_FUNCTION__))
;
3182 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3183 return Resolver;
3184}
3185
3186/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3187/// module, create and return an llvm Function with the specified type. If there
3188/// is something in the module with the specified name, return it potentially
3189/// bitcasted to the right type.
3190///
3191/// If D is non-null, it specifies a decl that correspond to this. This is used
3192/// to set the attributes on the function when it is first created.
3193llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3194 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3195 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3196 ForDefinition_t IsForDefinition) {
3197 const Decl *D = GD.getDecl();
3198
3199 // Any attempts to use a MultiVersion function should result in retrieving
3200 // the iFunc instead. Name Mangling will handle the rest of the changes.
3201 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3202 // For the device mark the function as one that should be emitted.
3203 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3204 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3205 !DontDefer && !IsForDefinition) {
3206 if (const FunctionDecl *FDDef = FD->getDefinition()) {
3207 GlobalDecl GDDef;
3208 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3209 GDDef = GlobalDecl(CD, GD.getCtorType());
3210 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3211 GDDef = GlobalDecl(DD, GD.getDtorType());
3212 else
3213 GDDef = GlobalDecl(FDDef);
3214 EmitGlobal(GDDef);
3215 }
3216 }
3217
3218 if (FD->isMultiVersion()) {
3219 if (FD->hasAttr<TargetAttr>())
3220 UpdateMultiVersionNames(GD, FD);
3221 if (!IsForDefinition)
3222 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3223 }
3224 }
3225
3226 // Lookup the entry, lazily creating it if necessary.
3227 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3228 if (Entry) {
3229 if (WeakRefReferences.erase(Entry)) {
3230 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3231 if (FD && !FD->hasAttr<WeakAttr>())
3232 Entry->setLinkage(llvm::Function::ExternalLinkage);
3233 }
3234
3235 // Handle dropped DLL attributes.
3236 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3237 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3238 setDSOLocal(Entry);
3239 }
3240
3241 // If there are two attempts to define the same mangled name, issue an
3242 // error.
3243 if (IsForDefinition && !Entry->isDeclaration()) {
3244 GlobalDecl OtherGD;
3245 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3246 // to make sure that we issue an error only once.
3247 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3248 (GD.getCanonicalDecl().getDecl() !=
3249 OtherGD.getCanonicalDecl().getDecl()) &&
3250 DiagnosedConflictingDefinitions.insert(GD).second) {
3251 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3252 << MangledName;
3253 getDiags().Report(OtherGD.getDecl()->getLocation(),
3254 diag::note_previous_definition);
3255 }
3256 }
3257
3258 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3259 (Entry->getValueType() == Ty)) {
3260 return Entry;
3261 }
3262
3263 // Make sure the result is of the correct type.
3264 // (If function is requested for a definition, we always need to create a new
3265 // function, not just return a bitcast.)
3266 if (!IsForDefinition)
3267 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3268 }
3269
3270 // This function doesn't have a complete type (for example, the return
3271 // type is an incomplete struct). Use a fake type instead, and make
3272 // sure not to try to set attributes.
3273 bool IsIncompleteFunction = false;
3274
3275 llvm::FunctionType *FTy;
3276 if (isa<llvm::FunctionType>(Ty)) {
3277 FTy = cast<llvm::FunctionType>(Ty);
3278 } else {
3279 FTy = llvm::FunctionType::get(VoidTy, false);
3280 IsIncompleteFunction = true;
3281 }
3282
3283 llvm::Function *F =
3284 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3285 Entry ? StringRef() : MangledName, &getModule());
3286
3287 // If we already created a function with the same mangled name (but different
3288 // type) before, take its name and add it to the list of functions to be
3289 // replaced with F at the end of CodeGen.
3290 //
3291 // This happens if there is a prototype for a function (e.g. "int f()") and
3292 // then a definition of a different type (e.g. "int f(int x)").
3293 if (Entry) {
3294 F->takeName(Entry);
3295
3296 // This might be an implementation of a function without a prototype, in
3297 // which case, try to do special replacement of calls which match the new
3298 // prototype. The really key thing here is that we also potentially drop
3299 // arguments from the call site so as to make a direct call, which makes the
3300 // inliner happier and suppresses a number of optimizer warnings (!) about
3301 // dropping arguments.
3302 if (!Entry->use_empty()) {
3303 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3304 Entry->removeDeadConstantUsers();
3305 }
3306
3307 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3308 F, Entry->getValueType()->getPointerTo());
3309 addGlobalValReplacement(Entry, BC);
3310 }
3311
3312 assert(F->getName() == MangledName && "name was uniqued!")((F->getName() == MangledName && "name was uniqued!"
) ? static_cast<void> (0) : __assert_fail ("F->getName() == MangledName && \"name was uniqued!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3312, __PRETTY_FUNCTION__))
;
3313 if (D)
3314 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3315 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3316 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3317 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3318 }
3319
3320 if (!DontDefer) {
3321 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3322 // each other bottoming out with the base dtor. Therefore we emit non-base
3323 // dtors on usage, even if there is no dtor definition in the TU.
3324 if (D && isa<CXXDestructorDecl>(D) &&
3325 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3326 GD.getDtorType()))
3327 addDeferredDeclToEmit(GD);
3328
3329 // This is the first use or definition of a mangled name. If there is a
3330 // deferred decl with this name, remember that we need to emit it at the end
3331 // of the file.
3332 auto DDI = DeferredDecls.find(MangledName);
3333 if (DDI != DeferredDecls.end()) {
3334 // Move the potentially referenced deferred decl to the
3335 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3336 // don't need it anymore).
3337 addDeferredDeclToEmit(DDI->second);
3338 DeferredDecls.erase(DDI);
3339
3340 // Otherwise, there are cases we have to worry about where we're
3341 // using a declaration for which we must emit a definition but where
3342 // we might not find a top-level definition:
3343 // - member functions defined inline in their classes
3344 // - friend functions defined inline in some class
3345 // - special member functions with implicit definitions
3346 // If we ever change our AST traversal to walk into class methods,
3347 // this will be unnecessary.
3348 //
3349 // We also don't emit a definition for a function if it's going to be an
3350 // entry in a vtable, unless it's already marked as used.
3351 } else if (getLangOpts().CPlusPlus && D) {
3352 // Look for a declaration that's lexically in a record.
3353 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3354 FD = FD->getPreviousDecl()) {
3355 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3356 if (FD->doesThisDeclarationHaveABody()) {
3357 addDeferredDeclToEmit(GD.getWithDecl(FD));
3358 break;
3359 }
3360 }
3361 }
3362 }
3363 }
3364
3365 // Make sure the result is of the requested type.
3366 if (!IsIncompleteFunction) {
3367 assert(F->getFunctionType() == Ty)((F->getFunctionType() == Ty) ? static_cast<void> (0
) : __assert_fail ("F->getFunctionType() == Ty", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3367, __PRETTY_FUNCTION__))
;
3368 return F;
3369 }
3370
3371 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3372 return llvm::ConstantExpr::getBitCast(F, PTy);
3373}
3374
3375/// GetAddrOfFunction - Return the address of the given function. If Ty is
3376/// non-null, then this function will use the specified type if it has to
3377/// create it (this occurs when we see a definition of the function).
3378llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3379 llvm::Type *Ty,
3380 bool ForVTable,
3381 bool DontDefer,
3382 ForDefinition_t IsForDefinition) {
3383 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&((!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
"consteval function should never be emitted") ? static_cast<
void> (0) : __assert_fail ("!cast<FunctionDecl>(GD.getDecl())->isConsteval() && \"consteval function should never be emitted\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3384, __PRETTY_FUNCTION__))
3384 "consteval function should never be emitted")((!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
"consteval function should never be emitted") ? static_cast<
void> (0) : __assert_fail ("!cast<FunctionDecl>(GD.getDecl())->isConsteval() && \"consteval function should never be emitted\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3384, __PRETTY_FUNCTION__))
;
3385 // If there was no specific requested type, just convert it now.
3386 if (!Ty) {
3387 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3388 Ty = getTypes().ConvertType(FD->getType());
3389 }
3390
3391 // Devirtualized destructor calls may come through here instead of via
3392 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3393 // of the complete destructor when necessary.
3394 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3395 if (getTarget().getCXXABI().isMicrosoft() &&
3396 GD.getDtorType() == Dtor_Complete &&
3397 DD->getParent()->getNumVBases() == 0)
3398 GD = GlobalDecl(DD, Dtor_Base);
3399 }
3400
3401 StringRef MangledName = getMangledName(GD);
3402 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3403 /*IsThunk=*/false, llvm::AttributeList(),
3404 IsForDefinition);
3405}
3406
3407static const FunctionDecl *
3408GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3409 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3410 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3411
3412 IdentifierInfo &CII = C.Idents.get(Name);
3413 for (const auto &Result : DC->lookup(&CII))
3414 if (const auto FD = dyn_cast<FunctionDecl>(Result))
3415 return FD;
3416
3417 if (!C.getLangOpts().CPlusPlus)
3418 return nullptr;
3419
3420 // Demangle the premangled name from getTerminateFn()
3421 IdentifierInfo &CXXII =
3422 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3423 ? C.Idents.get("terminate")
3424 : C.Idents.get(Name);
3425
3426 for (const auto &N : {"__cxxabiv1", "std"}) {
3427 IdentifierInfo &NS = C.Idents.get(N);
3428 for (const auto &Result : DC->lookup(&NS)) {
3429 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3430 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
3431 for (const auto &Result : LSD->lookup(&NS))
3432 if ((ND = dyn_cast<NamespaceDecl>(Result)))
3433 break;
3434
3435 if (ND)
3436 for (const auto &Result : ND->lookup(&CXXII))
3437 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3438 return FD;
3439 }
3440 }
3441
3442 return nullptr;
3443}
3444
3445/// CreateRuntimeFunction - Create a new runtime function with the specified
3446/// type and name.
3447llvm::FunctionCallee
3448CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3449 llvm::AttributeList ExtraAttrs, bool Local,
3450 bool AssumeConvergent) {
3451 if (AssumeConvergent) {
3452 ExtraAttrs =
3453 ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3454 llvm::Attribute::Convergent);
3455 }
3456
3457 llvm::Constant *C =
3458 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3459 /*DontDefer=*/false, /*IsThunk=*/false,
3460 ExtraAttrs);
3461
3462 if (auto *F = dyn_cast<llvm::Function>(C)) {
3463 if (F->empty()) {
3464 F->setCallingConv(getRuntimeCC());
3465
3466 // In Windows Itanium environments, try to mark runtime functions
3467 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3468 // will link their standard library statically or dynamically. Marking
3469 // functions imported when they are not imported can cause linker errors
3470 // and warnings.
3471 if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3472 !getCodeGenOpts().LTOVisibilityPublicStd) {
3473 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3474 if (!FD || FD->hasAttr<DLLImportAttr>()) {
3475 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3476 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3477 }
3478 }
3479 setDSOLocal(F);
3480 }
3481 }
3482
3483 return {FTy, C};
3484}
3485
3486/// isTypeConstant - Determine whether an object of this type can be emitted
3487/// as a constant.
3488///
3489/// If ExcludeCtor is true, the duration when the object's constructor runs
3490/// will not be considered. The caller will need to verify that the object is
3491/// not written to during its construction.
3492bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3493 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3494 return false;
3495
3496 if (Context.getLangOpts().CPlusPlus) {
3497 if (const CXXRecordDecl *Record
3498 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3499 return ExcludeCtor && !Record->hasMutableFields() &&
3500 Record->hasTrivialDestructor();
3501 }
3502
3503 return true;
3504}
3505
3506/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3507/// create and return an llvm GlobalVariable with the specified type. If there
3508/// is something in the module with the specified name, return it potentially
3509/// bitcasted to the right type.
3510///
3511/// If D is non-null, it specifies a decl that correspond to this. This is used
3512/// to set the attributes on the global when it is first created.
3513///
3514/// If IsForDefinition is true, it is guaranteed that an actual global with
3515/// type Ty will be returned, not conversion of a variable with the same
3516/// mangled name but some other type.
3517llvm::Constant *
3518CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3519 llvm::PointerType *Ty,
3520 const VarDecl *D,
3521 ForDefinition_t IsForDefinition) {
3522 // Lookup the entry, lazily creating it if necessary.
3523 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3524 if (Entry) {
3525 if (WeakRefReferences.erase(Entry)) {
3526 if (D && !D->hasAttr<WeakAttr>())
3527 Entry->setLinkage(llvm::Function::ExternalLinkage);
3528 }
3529
3530 // Handle dropped DLL attributes.
3531 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3532 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3533
3534 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3535 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3536
3537 if (Entry->getType() == Ty)
3538 return Entry;
3539
3540 // If there are two attempts to define the same mangled name, issue an
3541 // error.
3542 if (IsForDefinition && !Entry->isDeclaration()) {
3543 GlobalDecl OtherGD;
3544 const VarDecl *OtherD;
3545
3546 // Check that D is not yet in DiagnosedConflictingDefinitions is required
3547 // to make sure that we issue an error only once.
3548 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3549 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3550 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3551 OtherD->hasInit() &&
3552 DiagnosedConflictingDefinitions.insert(D).second) {
3553 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3554 << MangledName;
3555 getDiags().Report(OtherGD.getDecl()->getLocation(),
3556 diag::note_previous_definition);
3557 }
3558 }
3559
3560 // Make sure the result is of the correct type.
3561 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3562 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3563
3564 // (If global is requested for a definition, we always need to create a new
3565 // global, not just return a bitcast.)
3566 if (!IsForDefinition)
3567 return llvm::ConstantExpr::getBitCast(Entry, Ty);
3568 }
3569
3570 auto AddrSpace = GetGlobalVarAddressSpace(D);
3571 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3572
3573 auto *GV = new llvm::GlobalVariable(
3574 getModule(), Ty->getElementType(), false,
3575 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3576 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3577
3578 // If we already created a global with the same mangled name (but different
3579 // type) before, take its name and remove it from its parent.
3580 if (Entry) {
3581 GV->takeName(Entry);
3582
3583 if (!Entry->use_empty()) {
3584 llvm::Constant *NewPtrForOldDecl =
3585 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3586 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3587 }
3588
3589 Entry->eraseFromParent();
3590 }
3591
3592 // This is the first use or definition of a mangled name. If there is a
3593 // deferred decl with this name, remember that we need to emit it at the end
3594 // of the file.
3595 auto DDI = DeferredDecls.find(MangledName);
3596 if (DDI != DeferredDecls.end()) {
3597 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3598 // list, and remove it from DeferredDecls (since we don't need it anymore).
3599 addDeferredDeclToEmit(DDI->second);
3600 DeferredDecls.erase(DDI);
3601 }
3602
3603 // Handle things which are present even on external declarations.
3604 if (D) {
3605 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3606 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3607
3608 // FIXME: This code is overly simple and should be merged with other global
3609 // handling.
3610 GV->setConstant(isTypeConstant(D->getType(), false));
3611
3612 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3613
3614 setLinkageForGV(GV, D);
3615
3616 if (D->getTLSKind()) {
3617 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3618 CXXThreadLocals.push_back(D);
3619 setTLSMode(GV, *D);
3620 }
3621
3622 setGVProperties(GV, D);
3623
3624 // If required by the ABI, treat declarations of static data members with
3625 // inline initializers as definitions.
3626 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3627 EmitGlobalVarDefinition(D);
3628 }
3629
3630 // Emit section information for extern variables.
3631 if (D->hasExternalStorage()) {
3632 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3633 GV->setSection(SA->getName());
3634 }
3635
3636 // Handle XCore specific ABI requirements.
3637 if (getTriple().getArch() == llvm::Triple::xcore &&
3638 D->getLanguageLinkage() == CLanguageLinkage &&
3639 D->getType().isConstant(Context) &&
3640 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3641 GV->setSection(".cp.rodata");
3642
3643 // Check if we a have a const declaration with an initializer, we may be
3644 // able to emit it as available_externally to expose it's value to the
3645 // optimizer.
3646 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3647 D->getType().isConstQualified() && !GV->hasInitializer() &&
3648 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3649 const auto *Record =
3650 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3651 bool HasMutableFields = Record && Record->hasMutableFields();
3652 if (!HasMutableFields) {
3653 const VarDecl *InitDecl;
3654 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3655 if (InitExpr) {
3656 ConstantEmitter emitter(*this);
3657 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3658 if (Init) {
3659 auto *InitType = Init->getType();
3660 if (GV->getValueType() != InitType) {
3661 // The type of the initializer does not match the definition.
3662 // This happens when an initializer has a different type from
3663 // the type of the global (because of padding at the end of a
3664 // structure for instance).
3665 GV->setName(StringRef());
3666 // Make a new global with the correct type, this is now guaranteed
3667 // to work.
3668 auto *NewGV = cast<llvm::GlobalVariable>(
3669 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3670 ->stripPointerCasts());
3671
3672 // Erase the old global, since it is no longer used.
3673 GV->eraseFromParent();
3674 GV = NewGV;
3675 } else {
3676 GV->setInitializer(Init);
3677 GV->setConstant(true);
3678 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3679 }
3680 emitter.finalize(GV);
3681 }
3682 }
3683 }
3684 }
3685 }
3686
3687 if (GV->isDeclaration())
3688 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3689
3690 LangAS ExpectedAS =
3691 D ? D->getType().getAddressSpace()
3692 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3693 assert(getContext().getTargetAddressSpace(ExpectedAS) ==((getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace
()) ? static_cast<void> (0) : __assert_fail ("getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3694, __PRETTY_FUNCTION__))
3694 Ty->getPointerAddressSpace())((getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace
()) ? static_cast<void> (0) : __assert_fail ("getContext().getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3694, __PRETTY_FUNCTION__))
;
3695 if (AddrSpace != ExpectedAS)
3696 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3697 ExpectedAS, Ty);
3698
3699 return GV;
3700}
3701
3702llvm::Constant *
3703CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
3704 const Decl *D = GD.getDecl();
3705
3706 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3707 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3708 /*DontDefer=*/false, IsForDefinition);
3709
3710 if (isa<CXXMethodDecl>(D)) {
3711 auto FInfo =
3712 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
3713 auto Ty = getTypes().GetFunctionType(*FInfo);
3714 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3715 IsForDefinition);
3716 }
3717
3718 if (isa<FunctionDecl>(D)) {
3719 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3720 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3721 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3722 IsForDefinition);
3723 }
3724
3725 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
3726}
3727
3728llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3729 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3730 unsigned Alignment) {
3731 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3732 llvm::GlobalVariable *OldGV = nullptr;
3733
3734 if (GV) {
3735 // Check if the variable has the right type.
3736 if (GV->getValueType() == Ty)
3737 return GV;
3738
3739 // Because C++ name mangling, the only way we can end up with an already
3740 // existing global with the same name is if it has been declared extern "C".
3741 assert(GV->isDeclaration() && "Declaration has wrong type!")((GV->isDeclaration() && "Declaration has wrong type!"
) ? static_cast<void> (0) : __assert_fail ("GV->isDeclaration() && \"Declaration has wrong type!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3741, __PRETTY_FUNCTION__))
;
3742 OldGV = GV;
3743 }
3744
3745 // Create a new variable.
3746 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3747 Linkage, nullptr, Name);
3748
3749 if (OldGV) {
3750 // Replace occurrences of the old variable if needed.
3751 GV->takeName(OldGV);
3752
3753 if (!OldGV->use_empty()) {
3754 llvm::Constant *NewPtrForOldDecl =
3755 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3756 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3757 }
3758
3759 OldGV->eraseFromParent();
3760 }
3761
3762 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3763 !GV->hasAvailableExternallyLinkage())
3764 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3765
3766 GV->setAlignment(llvm::MaybeAlign(Alignment));
3767
3768 return GV;
3769}
3770
3771/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3772/// given global variable. If Ty is non-null and if the global doesn't exist,
3773/// then it will be created with the specified type instead of whatever the
3774/// normal requested type would be. If IsForDefinition is true, it is guaranteed
3775/// that an actual global with type Ty will be returned, not conversion of a
3776/// variable with the same mangled name but some other type.
3777llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3778 llvm::Type *Ty,
3779 ForDefinition_t IsForDefinition) {
3780 assert(D->hasGlobalStorage() && "Not a global variable")((D->hasGlobalStorage() && "Not a global variable"
) ? static_cast<void> (0) : __assert_fail ("D->hasGlobalStorage() && \"Not a global variable\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3780, __PRETTY_FUNCTION__))
;
3781 QualType ASTTy = D->getType();
3782 if (!Ty)
3783 Ty = getTypes().ConvertTypeForMem(ASTTy);
3784
3785 llvm::PointerType *PTy =
3786 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3787
3788 StringRef MangledName = getMangledName(D);
3789 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3790}
3791
3792/// CreateRuntimeVariable - Create a new runtime global variable with the
3793/// specified type and name.
3794llvm::Constant *
3795CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3796 StringRef Name) {
3797 auto PtrTy =
3798 getContext().getLangOpts().OpenCL
3799 ? llvm::PointerType::get(
3800 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
3801 : llvm::PointerType::getUnqual(Ty);
3802 auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
3803 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3804 return Ret;
3805}
3806
3807void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3808 assert(!D->getInit() && "Cannot emit definite definitions here!")((!D->getInit() && "Cannot emit definite definitions here!"
) ? static_cast<void> (0) : __assert_fail ("!D->getInit() && \"Cannot emit definite definitions here!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3808, __PRETTY_FUNCTION__))
;
3809
3810 StringRef MangledName = getMangledName(D);
3811 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3812
3813 // We already have a definition, not declaration, with the same mangled name.
3814 // Emitting of declaration is not required (and actually overwrites emitted
3815 // definition).
3816 if (GV && !GV->isDeclaration())
3817 return;
3818
3819 // If we have not seen a reference to this variable yet, place it into the
3820 // deferred declarations table to be emitted if needed later.
3821 if (!MustBeEmitted(D) && !GV) {
3822 DeferredDecls[MangledName] = D;
3823 return;
3824 }
3825
3826 // The tentative definition is the only definition.
3827 EmitGlobalVarDefinition(D);
3828}
3829
3830void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
3831 EmitExternalVarDeclaration(D);
3832}
3833
3834CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3835 return Context.toCharUnitsFromBits(
3836 getDataLayout().getTypeStoreSizeInBits(Ty));
3837}
3838
3839LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3840 LangAS AddrSpace = LangAS::Default;
3841 if (LangOpts.OpenCL) {
3842 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3843 assert(AddrSpace == LangAS::opencl_global ||((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_global_device || AddrSpace == LangAS::opencl_global_host
|| AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS
::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace
) ? static_cast<void> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3848, __PRETTY_FUNCTION__))
3844 AddrSpace == LangAS::opencl_global_device ||((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_global_device || AddrSpace == LangAS::opencl_global_host
|| AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS
::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace
) ? static_cast<void> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3848, __PRETTY_FUNCTION__))
3845 AddrSpace == LangAS::opencl_global_host ||((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_global_device || AddrSpace == LangAS::opencl_global_host
|| AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS
::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace
) ? static_cast<void> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3848, __PRETTY_FUNCTION__))
3846 AddrSpace == LangAS::opencl_constant ||((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_global_device || AddrSpace == LangAS::opencl_global_host
|| AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS
::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace
) ? static_cast<void> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3848, __PRETTY_FUNCTION__))
3847 AddrSpace == LangAS::opencl_local ||((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_global_device || AddrSpace == LangAS::opencl_global_host
|| AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS
::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace
) ? static_cast<void> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3848, __PRETTY_FUNCTION__))
3848 AddrSpace >= LangAS::FirstTargetAddressSpace)((AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::
opencl_global_device || AddrSpace == LangAS::opencl_global_host
|| AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS
::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace
) ? static_cast<void> (0) : __assert_fail ("AddrSpace == LangAS::opencl_global || AddrSpace == LangAS::opencl_global_device || AddrSpace == LangAS::opencl_global_host || AddrSpace == LangAS::opencl_constant || AddrSpace == LangAS::opencl_local || AddrSpace >= LangAS::FirstTargetAddressSpace"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3848, __PRETTY_FUNCTION__))
;
3849 return AddrSpace;
3850 }
3851
3852 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3853 if (D && D->hasAttr<CUDAConstantAttr>())
3854 return LangAS::cuda_constant;
3855 else if (D && D->hasAttr<CUDASharedAttr>())
3856 return LangAS::cuda_shared;
3857 else if (D && D->hasAttr<CUDADeviceAttr>())
3858 return LangAS::cuda_device;
3859 else if (D && D->getType().isConstQualified())
3860 return LangAS::cuda_constant;
3861 else
3862 return LangAS::cuda_device;
3863 }
3864
3865 if (LangOpts.OpenMP) {
3866 LangAS AS;
3867 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3868 return AS;
3869 }
3870 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3871}
3872
3873LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3874 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3875 if (LangOpts.OpenCL)
3876 return LangAS::opencl_constant;
3877 if (auto AS = getTarget().getConstantAddressSpace())
3878 return AS.getValue();
3879 return LangAS::Default;
3880}
3881
3882// In address space agnostic languages, string literals are in default address
3883// space in AST. However, certain targets (e.g. amdgcn) request them to be
3884// emitted in constant address space in LLVM IR. To be consistent with other
3885// parts of AST, string literal global variables in constant address space
3886// need to be casted to default address space before being put into address
3887// map and referenced by other part of CodeGen.
3888// In OpenCL, string literals are in constant address space in AST, therefore
3889// they should not be casted to default address space.
3890static llvm::Constant *
3891castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3892 llvm::GlobalVariable *GV) {
3893 llvm::Constant *Cast = GV;
3894 if (!CGM.getLangOpts().OpenCL) {
3895 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3896 if (AS != LangAS::Default)
3897 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3898 CGM, GV, AS.getValue(), LangAS::Default,
3899 GV->getValueType()->getPointerTo(
3900 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3901 }
3902 }
3903 return Cast;
3904}
3905
3906template<typename SomeDecl>
3907void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3908 llvm::GlobalValue *GV) {
3909 if (!getLangOpts().CPlusPlus)
3910 return;
3911
3912 // Must have 'used' attribute, or else inline assembly can't rely on
3913 // the name existing.
3914 if (!D->template hasAttr<UsedAttr>())
3915 return;
3916
3917 // Must have internal linkage and an ordinary name.
3918 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3919 return;
3920
3921 // Must be in an extern "C" context. Entities declared directly within
3922 // a record are not extern "C" even if the record is in such a context.
3923 const SomeDecl *First = D->getFirstDecl();
3924 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3925 return;
3926
3927 // OK, this is an internal linkage entity inside an extern "C" linkage
3928 // specification. Make a note of that so we can give it the "expected"
3929 // mangled name if nothing else is using that name.
3930 std::pair<StaticExternCMap::iterator, bool> R =
3931 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3932
3933 // If we have multiple internal linkage entities with the same name
3934 // in extern "C" regions, none of them gets that name.
3935 if (!R.second)
3936 R.first->second = nullptr;
3937}
3938
3939static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3940 if (!CGM.supportsCOMDAT())
3941 return false;
3942
3943 // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
3944 // them being "merged" by the COMDAT Folding linker optimization.
3945 if (D.hasAttr<CUDAGlobalAttr>())
3946 return false;
3947
3948 if (D.hasAttr<SelectAnyAttr>())
3949 return true;
3950
3951 GVALinkage Linkage;
3952 if (auto *VD = dyn_cast<VarDecl>(&D))
3953 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3954 else
3955 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3956
3957 switch (Linkage) {
3958 case GVA_Internal:
3959 case GVA_AvailableExternally:
3960 case GVA_StrongExternal:
3961 return false;
3962 case GVA_DiscardableODR:
3963 case GVA_StrongODR:
3964 return true;
3965 }
3966 llvm_unreachable("No such linkage")::llvm::llvm_unreachable_internal("No such linkage", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 3966)
;
3967}
3968
3969void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3970 llvm::GlobalObject &GO) {
3971 if (!shouldBeInCOMDAT(*this, D))
3972 return;
3973 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3974}
3975
3976/// Pass IsTentative as true if you want to create a tentative definition.
3977void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3978 bool IsTentative) {
3979 // OpenCL global variables of sampler type are translated to function calls,
3980 // therefore no need to be translated.
3981 QualType ASTTy = D->getType();
3982 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
1
Assuming field 'OpenCL' is 0
3983 return;
3984
3985 // If this is OpenMP device, check if it is legal to emit this global
3986 // normally.
3987 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
2
Assuming field 'OpenMPIsDevice' is 0
3
Taking false branch
3988 OpenMPRuntime->emitTargetGlobalVariable(D))
3989 return;
3990
3991 llvm::Constant *Init = nullptr;
3992 bool NeedsGlobalCtor = false;
3993 bool NeedsGlobalDtor =
3994 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4
Assuming the condition is false
3995
3996 const VarDecl *InitDecl;
3997 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3998
3999 Optional<ConstantEmitter> emitter;
4000
4001 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4002 // as part of their declaration." Sema has already checked for
4003 // error cases, so we just need to set Init to UndefValue.
4004 bool IsCUDASharedVar =
4005 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
5
Assuming field 'CUDAIsDevice' is 0
4006 // Shadows of initialized device-side global variables are also left
4007 // undefined.
4008 bool IsCUDAShadowVar =
4009 !getLangOpts().CUDAIsDevice
5.1
Field 'CUDAIsDevice' is 0
5.1
Field 'CUDAIsDevice' is 0
&&
4010 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4011 D->hasAttr<CUDASharedAttr>());
4012 bool IsCUDADeviceShadowVar =
4013 getLangOpts().CUDAIsDevice
5.2
Field 'CUDAIsDevice' is 0
5.2
Field 'CUDAIsDevice' is 0
&&
4014 (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4015 D->getType()->isCUDADeviceBuiltinTextureType());
4016 // HIP pinned shadow of initialized host-side global variables are also
4017 // left undefined.
4018 if (getLangOpts().CUDA &&
6
Assuming field 'CUDA' is 0
4019 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4020 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
4021 else if (D->hasAttr<LoaderUninitializedAttr>())
7
Calling 'Decl::hasAttr'
9
Returning from 'Decl::hasAttr'
10
Taking false branch
4022 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
4023 else if (!InitExpr) {
11
Assuming 'InitExpr' is non-null
12
Taking false branch
4024 // This is a tentative definition; tentative definitions are
4025 // implicitly initialized with { 0 }.
4026 //
4027 // Note that tentative definitions are only emitted at the end of
4028 // a translation unit, so they should never have incomplete
4029 // type. In addition, EmitTentativeDefinition makes sure that we
4030 // never attempt to emit a tentative definition if a real one
4031 // exists. A use may still exists, however, so we still may need
4032 // to do a RAUW.
4033 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type")((!ASTTy->isIncompleteType() && "Unexpected incomplete type"
) ? static_cast<void> (0) : __assert_fail ("!ASTTy->isIncompleteType() && \"Unexpected incomplete type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4033, __PRETTY_FUNCTION__))
;
4034 Init = EmitNullConstant(D->getType());
4035 } else {
4036 initializedGlobalDecl = GlobalDecl(D);
4037 emitter.emplace(*this);
4038 Init = emitter->tryEmitForInitializer(*InitDecl);
4039
4040 if (!Init) {
13
Assuming 'Init' is non-null
14
Taking false branch
4041 QualType T = InitExpr->getType();
4042 if (D->getType()->isReferenceType())
4043 T = D->getType();
4044
4045 if (getLangOpts().CPlusPlus) {
4046 Init = EmitNullConstant(T);
4047 NeedsGlobalCtor = true;
4048 } else {
4049 ErrorUnsupported(D, "static initializer");
4050 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4051 }
4052 } else {
4053 // We don't need an initializer, so remove the entry for the delayed
4054 // initializer position (just in case this entry was delayed) if we
4055 // also don't need to register a destructor.
4056 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
15
Assuming field 'CPlusPlus' is 0
4057 DelayedCXXInitPosition.erase(D);
4058 }
4059 }
4060
4061 llvm::Type* InitType = Init->getType();
4062 llvm::Constant *Entry =
4063 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
16
Assuming 'IsTentative' is true
4064
4065 // Strip off pointer casts if we got them.
4066 Entry = Entry->stripPointerCasts();
4067
4068 // Entry is now either a Function or GlobalVariable.
4069 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
17
Assuming 'Entry' is a 'GlobalVariable'
4070
4071 // We have a definition after a declaration with the wrong type.
4072 // We must make a new GlobalVariable* and update everything that used OldGV
4073 // (a declaration or tentative definition) with the new GlobalVariable*
4074 // (which will be a definition).
4075 //
4076 // This happens if there is a prototype for a global (e.g.
4077 // "extern int x[];") and then a definition of a different type (e.g.
4078 // "int x[10];"). This also happens when an initializer has a different type
4079 // from the type of the global (this happens with unions).
4080 if (!GV
17.1
'GV' is non-null
17.1
'GV' is non-null
|| GV->getValueType() != InitType ||
18
Assuming the condition is false
20
Taking false branch
4081 GV->getType()->getAddressSpace() !=
19
Assuming the condition is false
4082 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4083
4084 // Move the old entry aside so that we'll create a new one.
4085 Entry->setName(StringRef());
4086
4087 // Make a new global with the correct type, this is now guaranteed to work.
4088 GV = cast<llvm::GlobalVariable>(
4089 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4090 ->stripPointerCasts());
4091
4092 // Replace all uses of the old global with the new global
4093 llvm::Constant *NewPtrForOldDecl =
4094 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4095 Entry->replaceAllUsesWith(NewPtrForOldDecl);
4096
4097 // Erase the old global, since it is no longer used.
4098 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4099 }
4100
4101 MaybeHandleStaticInExternC(D, GV);
4102
4103 if (D->hasAttr<AnnotateAttr>())
21
Taking false branch
4104 AddGlobalAnnotations(D, GV);
4105
4106 // Set the llvm linkage type as appropriate.
4107 llvm::GlobalValue::LinkageTypes Linkage =
4108 getLLVMLinkageVarDefinition(D, GV->isConstant());
4109
4110 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4111 // the device. [...]"
4112 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4113 // __device__, declares a variable that: [...]
4114 // Is accessible from all the threads within the grid and from the host
4115 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4116 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4117 if (GV
21.1
'GV' is non-null
21.1
'GV' is non-null
&& LangOpts.CUDA) {
22
Assuming field 'CUDA' is not equal to 0
23
Taking true branch
4118 if (LangOpts.CUDAIsDevice) {
24
Assuming field 'CUDAIsDevice' is 0
25
Taking false branch
4119 if (Linkage != llvm::GlobalValue::InternalLinkage &&
4120 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
4121 GV->setExternallyInitialized(true);
4122 } else {
4123 // Host-side shadows of external declarations of device-side
4124 // global variables become internal definitions. These have to
4125 // be internal in order to prevent name conflicts with global
4126 // host variables with the same name in a different TUs.
4127 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
26
Calling 'Decl::hasAttr'
28
Returning from 'Decl::hasAttr'
29
Calling 'Decl::hasAttr'
31
Returning from 'Decl::hasAttr'
32
Taking false branch
4128 Linkage = llvm::GlobalValue::InternalLinkage;
4129 // Shadow variables and their properties must be registered with CUDA
4130 // runtime. Skip Extern global variables, which will be registered in
4131 // the TU where they are defined.
4132 if (!D->hasExternalStorage())
4133 getCUDARuntime().registerDeviceVar(D, *GV, !D->hasDefinition(),
4134 D->hasAttr<CUDAConstantAttr>());
4135 } else if (D->hasAttr<CUDASharedAttr>()) {
33
Calling 'Decl::hasAttr'
35
Returning from 'Decl::hasAttr'
36
Taking false branch
4136 // __shared__ variables are odd. Shadows do get created, but
4137 // they are not registered with the CUDA runtime, so they
4138 // can't really be used to access their device-side
4139 // counterparts. It's not clear yet whether it's nvcc's bug or
4140 // a feature, but we've got to do the same for compatibility.
4141 Linkage = llvm::GlobalValue::InternalLinkage;
4142 } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
37
Assuming the condition is true
38
Taking true branch
4143 D->getType()->isCUDADeviceBuiltinTextureType()) {
4144 // Builtin surfaces and textures and their template arguments are
4145 // also registered with CUDA runtime.
4146 Linkage = llvm::GlobalValue::InternalLinkage;
4147 const ClassTemplateSpecializationDecl *TD =
4148 cast<ClassTemplateSpecializationDecl>(
4149 D->getType()->getAs<RecordType>()->getDecl());
39
Assuming the object is not a 'RecordType'
40
Called C++ object pointer is null
4150 const TemplateArgumentList &Args = TD->getTemplateArgs();
4151 if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {
4152 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-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4154, __PRETTY_FUNCTION__))
4153 "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-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4154, __PRETTY_FUNCTION__))
4154 "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-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4154, __PRETTY_FUNCTION__))
;
4155 auto SurfType = Args[1].getAsIntegral();
4156 if (!D->hasExternalStorage())
4157 getCUDARuntime().registerDeviceSurf(D, *GV, !D->hasDefinition(),
4158 SurfType.getSExtValue());
4159 } else {
4160 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-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4162, __PRETTY_FUNCTION__))
4161 "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-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4162, __PRETTY_FUNCTION__))
4162 "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-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4162, __PRETTY_FUNCTION__))
;
4163 auto TexType = Args[1].getAsIntegral();
4164 auto Normalized = Args[2].getAsIntegral();
4165 if (!D->hasExternalStorage())
4166 getCUDARuntime().registerDeviceTex(D, *GV, !D->hasDefinition(),
4167 TexType.getSExtValue(),
4168 Normalized.getZExtValue());
4169 }
4170 }
4171 }
4172 }
4173
4174 GV->setInitializer(Init);
4175 if (emitter)
4176 emitter->finalize(GV);
4177
4178 // If it is safe to mark the global 'constant', do so now.
4179 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4180 isTypeConstant(D->getType(), true));
4181
4182 // If it is in a read-only section, mark it 'constant'.
4183 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4184 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4185 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4186 GV->setConstant(true);
4187 }
4188
4189 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4190
4191 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4192 // function is only defined alongside the variable, not also alongside
4193 // callers. Normally, all accesses to a thread_local go through the
4194 // thread-wrapper in order to ensure initialization has occurred, underlying
4195 // variable will never be used other than the thread-wrapper, so it can be
4196 // converted to internal linkage.
4197 //
4198 // However, if the variable has the 'constinit' attribute, it _can_ be
4199 // referenced directly, without calling the thread-wrapper, so the linkage
4200 // must not be changed.
4201 //
4202 // Additionally, if the variable isn't plain external linkage, e.g. if it's
4203 // weak or linkonce, the de-duplication semantics are important to preserve,
4204 // so we don't change the linkage.
4205 if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4206 Linkage == llvm::GlobalValue::ExternalLinkage &&
4207 Context.getTargetInfo().getTriple().isOSDarwin() &&
4208 !D->hasAttr<ConstInitAttr>())
4209 Linkage = llvm::GlobalValue::InternalLinkage;
4210
4211 GV->setLinkage(Linkage);
4212 if (D->hasAttr<DLLImportAttr>())
4213 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4214 else if (D->hasAttr<DLLExportAttr>())
4215 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4216 else
4217 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4218
4219 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4220 // common vars aren't constant even if declared const.
4221 GV->setConstant(false);
4222 // Tentative definition of global variables may be initialized with
4223 // non-zero null pointers. In this case they should have weak linkage
4224 // since common linkage must have zero initializer and must not have
4225 // explicit section therefore cannot have non-zero initial value.
4226 if (!GV->getInitializer()->isNullValue())
4227 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4228 }
4229
4230 setNonAliasAttributes(D, GV);
4231
4232 if (D->getTLSKind() && !GV->isThreadLocal()) {
4233 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4234 CXXThreadLocals.push_back(D);
4235 setTLSMode(GV, *D);
4236 }
4237
4238 maybeSetTrivialComdat(*D, *GV);
4239
4240 // Emit the initializer function if necessary.
4241 if (NeedsGlobalCtor || NeedsGlobalDtor)
4242 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4243
4244 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4245
4246 // Emit global variable debug information.
4247 if (CGDebugInfo *DI = getModuleDebugInfo())
4248 if (getCodeGenOpts().hasReducedDebugInfo())
4249 DI->EmitGlobalVariable(GV, D);
4250}
4251
4252void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4253 if (CGDebugInfo *DI = getModuleDebugInfo())
4254 if (getCodeGenOpts().hasReducedDebugInfo()) {
4255 QualType ASTTy = D->getType();
4256 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4257 llvm::PointerType *PTy =
4258 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4259 llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4260 DI->EmitExternalVariable(
4261 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4262 }
4263}
4264
4265static bool isVarDeclStrongDefinition(const ASTContext &Context,
4266 CodeGenModule &CGM, const VarDecl *D,
4267 bool NoCommon) {
4268 // Don't give variables common linkage if -fno-common was specified unless it
4269 // was overridden by a NoCommon attribute.
4270 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4271 return true;
4272
4273 // C11 6.9.2/2:
4274 // A declaration of an identifier for an object that has file scope without
4275 // an initializer, and without a storage-class specifier or with the
4276 // storage-class specifier static, constitutes a tentative definition.
4277 if (D->getInit() || D->hasExternalStorage())
4278 return true;
4279
4280 // A variable cannot be both common and exist in a section.
4281 if (D->hasAttr<SectionAttr>())
4282 return true;
4283
4284 // A variable cannot be both common and exist in a section.
4285 // We don't try to determine which is the right section in the front-end.
4286 // If no specialized section name is applicable, it will resort to default.
4287 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4288 D->hasAttr<PragmaClangDataSectionAttr>() ||
4289 D->hasAttr<PragmaClangRelroSectionAttr>() ||
4290 D->hasAttr<PragmaClangRodataSectionAttr>())
4291 return true;
4292
4293 // Thread local vars aren't considered common linkage.
4294 if (D->getTLSKind())
4295 return true;
4296
4297 // Tentative definitions marked with WeakImportAttr are true definitions.
4298 if (D->hasAttr<WeakImportAttr>())
4299 return true;
4300
4301 // A variable cannot be both common and exist in a comdat.
4302 if (shouldBeInCOMDAT(CGM, *D))
4303 return true;
4304
4305 // Declarations with a required alignment do not have common linkage in MSVC
4306 // mode.
4307 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4308 if (D->hasAttr<AlignedAttr>())
4309 return true;
4310 QualType VarType = D->getType();
4311 if (Context.isAlignmentRequired(VarType))
4312 return true;
4313
4314 if (const auto *RT = VarType->getAs<RecordType>()) {
4315 const RecordDecl *RD = RT->getDecl();
4316 for (const FieldDecl *FD : RD->fields()) {
4317 if (FD->isBitField())
4318 continue;
4319 if (FD->hasAttr<AlignedAttr>())
4320 return true;
4321 if (Context.isAlignmentRequired(FD->getType()))
4322 return true;
4323 }
4324 }
4325 }
4326
4327 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4328 // common symbols, so symbols with greater alignment requirements cannot be
4329 // common.
4330 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4331 // alignments for common symbols via the aligncomm directive, so this
4332 // restriction only applies to MSVC environments.
4333 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4334 Context.getTypeAlignIfKnown(D->getType()) >
4335 Context.toBits(CharUnits::fromQuantity(32)))
4336 return true;
4337
4338 return false;
4339}
4340
4341llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4342 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4343 if (Linkage == GVA_Internal)
4344 return llvm::Function::InternalLinkage;
4345
4346 if (D->hasAttr<WeakAttr>()) {
4347 if (IsConstantVariable)
4348 return llvm::GlobalVariable::WeakODRLinkage;
4349 else
4350 return llvm::GlobalVariable::WeakAnyLinkage;
4351 }
4352
4353 if (const auto *FD = D->getAsFunction())
4354 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4355 return llvm::GlobalVariable::LinkOnceAnyLinkage;
4356
4357 // We are guaranteed to have a strong definition somewhere else,
4358 // so we can use available_externally linkage.
4359 if (Linkage == GVA_AvailableExternally)
4360 return llvm::GlobalValue::AvailableExternallyLinkage;
4361
4362 // Note that Apple's kernel linker doesn't support symbol
4363 // coalescing, so we need to avoid linkonce and weak linkages there.
4364 // Normally, this means we just map to internal, but for explicit
4365 // instantiations we'll map to external.
4366
4367 // In C++, the compiler has to emit a definition in every translation unit
4368 // that references the function. We should use linkonce_odr because
4369 // a) if all references in this translation unit are optimized away, we
4370 // don't need to codegen it. b) if the function persists, it needs to be
4371 // merged with other definitions. c) C++ has the ODR, so we know the
4372 // definition is dependable.
4373 if (Linkage == GVA_DiscardableODR)
4374 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4375 : llvm::Function::InternalLinkage;
4376
4377 // An explicit instantiation of a template has weak linkage, since
4378 // explicit instantiations can occur in multiple translation units
4379 // and must all be equivalent. However, we are not allowed to
4380 // throw away these explicit instantiations.
4381 //
4382 // We don't currently support CUDA device code spread out across multiple TUs,
4383 // so say that CUDA templates are either external (for kernels) or internal.
4384 // This lets llvm perform aggressive inter-procedural optimizations.
4385 if (Linkage == GVA_StrongODR) {
4386 if (Context.getLangOpts().AppleKext)
4387 return llvm::Function::ExternalLinkage;
4388 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
4389 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4390 : llvm::Function::InternalLinkage;
4391 return llvm::Function::WeakODRLinkage;
4392 }
4393
4394 // C++ doesn't have tentative definitions and thus cannot have common
4395 // linkage.
4396 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4397 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4398 CodeGenOpts.NoCommon))
4399 return llvm::GlobalVariable::CommonLinkage;
4400
4401 // selectany symbols are externally visible, so use weak instead of
4402 // linkonce. MSVC optimizes away references to const selectany globals, so
4403 // all definitions should be the same and ODR linkage should be used.
4404 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4405 if (D->hasAttr<SelectAnyAttr>())
4406 return llvm::GlobalVariable::WeakODRLinkage;
4407
4408 // Otherwise, we have strong external linkage.
4409 assert(Linkage == GVA_StrongExternal)((Linkage == GVA_StrongExternal) ? static_cast<void> (0
) : __assert_fail ("Linkage == GVA_StrongExternal", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4409, __PRETTY_FUNCTION__))
;
4410 return llvm::GlobalVariable::ExternalLinkage;
4411}
4412
4413llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4414 const VarDecl *VD, bool IsConstant) {
4415 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4416 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4417}
4418
4419/// Replace the uses of a function that was declared with a non-proto type.
4420/// We want to silently drop extra arguments from call sites
4421static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4422 llvm::Function *newFn) {
4423 // Fast path.
4424 if (old->use_empty()) return;
4425
4426 llvm::Type *newRetTy = newFn->getReturnType();
4427 SmallVector<llvm::Value*, 4> newArgs;
4428 SmallVector<llvm::OperandBundleDef, 1> newBundles;
4429
4430 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4431 ui != ue; ) {
4432 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4433 llvm::User *user = use->getUser();
4434
4435 // Recognize and replace uses of bitcasts. Most calls to
4436 // unprototyped functions will use bitcasts.
4437 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4438 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4439 replaceUsesOfNonProtoConstant(bitcast, newFn);
4440 continue;
4441 }
4442
4443 // Recognize calls to the function.
4444 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4445 if (!callSite) continue;
4446 if (!callSite->isCallee(&*use))
4447 continue;
4448
4449 // If the return types don't match exactly, then we can't
4450 // transform this call unless it's dead.
4451 if (callSite->getType() != newRetTy && !callSite->use_empty())
4452 continue;
4453
4454 // Get the call site's attribute list.
4455 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4456 llvm::AttributeList oldAttrs = callSite->getAttributes();
4457
4458 // If the function was passed too few arguments, don't transform.
4459 unsigned newNumArgs = newFn->arg_size();
4460 if (callSite->arg_size() < newNumArgs)
4461 continue;
4462
4463 // If extra arguments were passed, we silently drop them.
4464 // If any of the types mismatch, we don't transform.
4465 unsigned argNo = 0;
4466 bool dontTransform = false;
4467 for (llvm::Argument &A : newFn->args()) {
4468 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4469 dontTransform = true;
4470 break;
4471 }
4472
4473 // Add any parameter attributes.
4474 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4475 argNo++;
4476 }
4477 if (dontTransform)
4478 continue;
4479
4480 // Okay, we can transform this. Create the new call instruction and copy
4481 // over the required information.
4482 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4483
4484 // Copy over any operand bundles.
4485 callSite->getOperandBundlesAsDefs(newBundles);
4486
4487 llvm::CallBase *newCall;
4488 if (dyn_cast<llvm::CallInst>(callSite)) {
4489 newCall =
4490 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4491 } else {
4492 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4493 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4494 oldInvoke->getUnwindDest(), newArgs,
4495 newBundles, "", callSite);
4496 }
4497 newArgs.clear(); // for the next iteration
4498
4499 if (!newCall->getType()->isVoidTy())
4500 newCall->takeName(callSite);
4501 newCall->setAttributes(llvm::AttributeList::get(
4502 newFn->getContext(), oldAttrs.getFnAttributes(),
4503 oldAttrs.getRetAttributes(), newArgAttrs));
4504 newCall->setCallingConv(callSite->getCallingConv());
4505
4506 // Finally, remove the old call, replacing any uses with the new one.
4507 if (!callSite->use_empty())
4508 callSite->replaceAllUsesWith(newCall);
4509
4510 // Copy debug location attached to CI.
4511 if (callSite->getDebugLoc())
4512 newCall->setDebugLoc(callSite->getDebugLoc());
4513
4514 callSite->eraseFromParent();
4515 }
4516}
4517
4518/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4519/// implement a function with no prototype, e.g. "int foo() {}". If there are
4520/// existing call uses of the old function in the module, this adjusts them to
4521/// call the new function directly.
4522///
4523/// This is not just a cleanup: the always_inline pass requires direct calls to
4524/// functions to be able to inline them. If there is a bitcast in the way, it
4525/// won't inline them. Instcombine normally deletes these calls, but it isn't
4526/// run at -O0.
4527static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4528 llvm::Function *NewFn) {
4529 // If we're redefining a global as a function, don't transform it.
4530 if (!isa<llvm::Function>(Old)) return;
4531
4532 replaceUsesOfNonProtoConstant(Old, NewFn);
4533}
4534
4535void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4536 auto DK = VD->isThisDeclarationADefinition();
4537 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4538 return;
4539
4540 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4541 // If we have a definition, this might be a deferred decl. If the
4542 // instantiation is explicit, make sure we emit it at the end.
4543 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4544 GetAddrOfGlobalVar(VD);
4545
4546 EmitTopLevelDecl(VD);
4547}
4548
4549void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4550 llvm::GlobalValue *GV) {
4551 const auto *D = cast<FunctionDecl>(GD.getDecl());
4552
4553 // Compute the function info and LLVM type.
4554 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4555 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4556
4557 // Get or create the prototype for the function.
4558 if (!GV || (GV->getValueType() != Ty))
4559 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4560 /*DontDefer=*/true,
4561 ForDefinition));
4562
4563 // Already emitted.
4564 if (!GV->isDeclaration())
4565 return;
4566
4567 // We need to set linkage and visibility on the function before
4568 // generating code for it because various parts of IR generation
4569 // want to propagate this information down (e.g. to local static
4570 // declarations).
4571 auto *Fn = cast<llvm::Function>(GV);
4572 setFunctionLinkage(GD, Fn);
4573
4574 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4575 setGVProperties(Fn, GD);
4576
4577 MaybeHandleStaticInExternC(D, Fn);
4578
4579
4580 maybeSetTrivialComdat(*D, *Fn);
4581
4582 CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
4583
4584 setNonAliasAttributes(GD, Fn);
4585 SetLLVMFunctionAttributesForDefinition(D, Fn);
4586
4587 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4588 AddGlobalCtor(Fn, CA->getPriority());
4589 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4590 AddGlobalDtor(Fn, DA->getPriority());
4591 if (D->hasAttr<AnnotateAttr>())
4592 AddGlobalAnnotations(D, Fn);
4593}
4594
4595void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4596 const auto *D = cast<ValueDecl>(GD.getDecl());
4597 const AliasAttr *AA = D->getAttr<AliasAttr>();
4598 assert(AA && "Not an alias?")((AA && "Not an alias?") ? static_cast<void> (0
) : __assert_fail ("AA && \"Not an alias?\"", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4598, __PRETTY_FUNCTION__))
;
4599
4600 StringRef MangledName = getMangledName(GD);
4601
4602 if (AA->getAliasee() == MangledName) {
4603 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4604 return;
4605 }
4606
4607 // If there is a definition in the module, then it wins over the alias.
4608 // This is dubious, but allow it to be safe. Just ignore the alias.
4609 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4610 if (Entry && !Entry->isDeclaration())
4611 return;
4612
4613 Aliases.push_back(GD);
4614
4615 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4616
4617 // Create a reference to the named value. This ensures that it is emitted
4618 // if a deferred decl.
4619 llvm::Constant *Aliasee;
4620 llvm::GlobalValue::LinkageTypes LT;
4621 if (isa<llvm::FunctionType>(DeclTy)) {
4622 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4623 /*ForVTable=*/false);
4624 LT = getFunctionLinkage(GD);
4625 } else {
4626 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4627 llvm::PointerType::getUnqual(DeclTy),
4628 /*D=*/nullptr);
4629 LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
4630 D->getType().isConstQualified());
4631 }
4632
4633 // Create the new alias itself, but don't set a name yet.
4634 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
4635 auto *GA =
4636 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
4637
4638 if (Entry) {
4639 if (GA->getAliasee() == Entry) {
4640 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4641 return;
4642 }
4643
4644 assert(Entry->isDeclaration())((Entry->isDeclaration()) ? static_cast<void> (0) : __assert_fail
("Entry->isDeclaration()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4644, __PRETTY_FUNCTION__))
;
4645
4646 // If there is a declaration in the module, then we had an extern followed
4647 // by the alias, as in:
4648 // extern int test6();
4649 // ...
4650 // int test6() __attribute__((alias("test7")));
4651 //
4652 // Remove it and replace uses of it with the alias.
4653 GA->takeName(Entry);
4654
4655 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4656 Entry->getType()));
4657 Entry->eraseFromParent();
4658 } else {
4659 GA->setName(MangledName);
4660 }
4661
4662 // Set attributes which are particular to an alias; this is a
4663 // specialization of the attributes which may be set on a global
4664 // variable/function.
4665 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4666 D->isWeakImported()) {
4667 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4668 }
4669
4670 if (const auto *VD = dyn_cast<VarDecl>(D))
4671 if (VD->getTLSKind())
4672 setTLSMode(GA, *VD);
4673
4674 SetCommonAttributes(GD, GA);
4675}
4676
4677void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4678 const auto *D = cast<ValueDecl>(GD.getDecl());
4679 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4680 assert(IFA && "Not an ifunc?")((IFA && "Not an ifunc?") ? static_cast<void> (
0) : __assert_fail ("IFA && \"Not an ifunc?\"", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4680, __PRETTY_FUNCTION__))
;
4681
4682 StringRef MangledName = getMangledName(GD);
4683
4684 if (IFA->getResolver() == MangledName) {
4685 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4686 return;
4687 }
4688
4689 // Report an error if some definition overrides ifunc.
4690 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4691 if (Entry && !Entry->isDeclaration()) {
4692 GlobalDecl OtherGD;
4693 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4694 DiagnosedConflictingDefinitions.insert(GD).second) {
4695 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4696 << MangledName;
4697 Diags.Report(OtherGD.getDecl()->getLocation(),
4698 diag::note_previous_definition);
4699 }
4700 return;
4701 }
4702
4703 Aliases.push_back(GD);
4704
4705 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4706 llvm::Constant *Resolver =
4707 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4708 /*ForVTable=*/false);
4709 llvm::GlobalIFunc *GIF =
4710 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4711 "", Resolver, &getModule());
4712 if (Entry) {
4713 if (GIF->getResolver() == Entry) {
4714 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4715 return;
4716 }
4717 assert(Entry->isDeclaration())((Entry->isDeclaration()) ? static_cast<void> (0) : __assert_fail
("Entry->isDeclaration()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4717, __PRETTY_FUNCTION__))
;
4718
4719 // If there is a declaration in the module, then we had an extern followed
4720 // by the ifunc, as in:
4721 // extern int test();
4722 // ...
4723 // int test() __attribute__((ifunc("resolver")));
4724 //
4725 // Remove it and replace uses of it with the ifunc.
4726 GIF->takeName(Entry);
4727
4728 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4729 Entry->getType()));
4730 Entry->eraseFromParent();
4731 } else
4732 GIF->setName(MangledName);
4733
4734 SetCommonAttributes(GD, GIF);
4735}
4736
4737llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4738 ArrayRef<llvm::Type*> Tys) {
4739 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4740 Tys);
4741}
4742
4743static llvm::StringMapEntry<llvm::GlobalVariable *> &
4744GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4745 const StringLiteral *Literal, bool TargetIsLSB,
4746 bool &IsUTF16, unsigned &StringLength) {
4747 StringRef String = Literal->getString();
4748 unsigned NumBytes = String.size();
4749
4750 // Check for simple case.
4751 if (!Literal->containsNonAsciiOrNull()) {
4752 StringLength = NumBytes;
4753 return *Map.insert(std::make_pair(String, nullptr)).first;
4754 }
4755
4756 // Otherwise, convert the UTF8 literals into a string of shorts.
4757 IsUTF16 = true;
4758
4759 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4760 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4761 llvm::UTF16 *ToPtr = &ToBuf[0];
4762
4763 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4764 ToPtr + NumBytes, llvm::strictConversion);
4765
4766 // ConvertUTF8toUTF16 returns the length in ToPtr.
4767 StringLength = ToPtr - &ToBuf[0];
4768
4769 // Add an explicit null.
4770 *ToPtr = 0;
4771 return *Map.insert(std::make_pair(
4772 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4773 (StringLength + 1) * 2),
4774 nullptr)).first;
4775}
4776
4777ConstantAddress
4778CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4779 unsigned StringLength = 0;
4780 bool isUTF16 = false;
4781 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4782 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4783 getDataLayout().isLittleEndian(), isUTF16,
4784 StringLength);
4785
4786 if (auto *C = Entry.second)
4787 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4788
4789 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4790 llvm::Constant *Zeros[] = { Zero, Zero };
4791
4792 const ASTContext &Context = getContext();
4793 const llvm::Triple &Triple = getTriple();
4794
4795 const auto CFRuntime = getLangOpts().CFRuntime;
4796 const bool IsSwiftABI =
4797 static_cast<unsigned>(CFRuntime) >=
4798 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4799 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4800
4801 // If we don't already have it, get __CFConstantStringClassReference.
4802 if (!CFConstantStringClassRef) {
4803 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
4804 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4805 Ty = llvm::ArrayType::get(Ty, 0);
4806
4807 switch (CFRuntime) {
4808 default: break;
4809 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH[[gnu::fallthrough]];
4810 case LangOptions::CoreFoundationABI::Swift5_0:
4811 CFConstantStringClassName =
4812 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4813 : "$s10Foundation19_NSCFConstantStringCN";
4814 Ty = IntPtrTy;
4815 break;
4816 case LangOptions::CoreFoundationABI::Swift4_2:
4817 CFConstantStringClassName =
4818 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4819 : "$S10Foundation19_NSCFConstantStringCN";
4820 Ty = IntPtrTy;
4821 break;
4822 case LangOptions::CoreFoundationABI::Swift4_1:
4823 CFConstantStringClassName =
4824 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4825 : "__T010Foundation19_NSCFConstantStringCN";
4826 Ty = IntPtrTy;
4827 break;
4828 }
4829
4830 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
4831
4832 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4833 llvm::GlobalValue *GV = nullptr;
4834
4835 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4836 IdentifierInfo &II = Context.Idents.get(GV->getName());
4837 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
4838 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4839
4840 const VarDecl *VD = nullptr;
4841 for (const auto &Result : DC->lookup(&II))
4842 if ((VD = dyn_cast<VarDecl>(Result)))
4843 break;
4844
4845 if (Triple.isOSBinFormatELF()) {
4846 if (!VD)
4847 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4848 } else {
4849 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4850 if (!VD || !VD->hasAttr<DLLExportAttr>())
4851 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4852 else
4853 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4854 }
4855
4856 setDSOLocal(GV);
4857 }
4858 }
4859
4860 // Decay array -> ptr
4861 CFConstantStringClassRef =
4862 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4863 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4864 }
4865
4866 QualType CFTy = Context.getCFConstantStringType();
4867
4868 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4869
4870 ConstantInitBuilder Builder(*this);
4871 auto Fields = Builder.beginStruct(STy);
4872
4873 // Class pointer.
4874 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4875
4876 // Flags.
4877 if (IsSwiftABI) {
4878 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4879 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4880 } else {
4881 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4882 }
4883
4884 // String pointer.
4885 llvm::Constant *C = nullptr;
4886 if (isUTF16) {
4887 auto Arr = llvm::makeArrayRef(
4888 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4889 Entry.first().size() / 2);
4890 C = llvm::ConstantDataArray::get(VMContext, Arr);
4891 } else {
4892 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4893 }
4894
4895 // Note: -fwritable-strings doesn't make the backing store strings of
4896 // CFStrings writable. (See <rdar://problem/10657500>)
4897 auto *GV =
4898 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4899 llvm::GlobalValue::PrivateLinkage, C, ".str");
4900 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4901 // Don't enforce the target's minimum global alignment, since the only use
4902 // of the string is via this class initializer.
4903 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4904 : Context.getTypeAlignInChars(Context.CharTy);
4905 GV->setAlignment(Align.getAsAlign());
4906
4907 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4908 // Without it LLVM can merge the string with a non unnamed_addr one during
4909 // LTO. Doing that changes the section it ends in, which surprises ld64.
4910 if (Triple.isOSBinFormatMachO())
4911 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4912 : "__TEXT,__cstring,cstring_literals");
4913 // Make sure the literal ends up in .rodata to allow for safe ICF and for
4914 // the static linker to adjust permissions to read-only later on.
4915 else if (Triple.isOSBinFormatELF())
4916 GV->setSection(".rodata");
4917
4918 // String.
4919 llvm::Constant *Str =
4920 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4921
4922 if (isUTF16)
4923 // Cast the UTF16 string to the correct type.
4924 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4925 Fields.add(Str);
4926
4927 // String length.
4928 llvm::IntegerType *LengthTy =
4929 llvm::IntegerType::get(getModule().getContext(),
4930 Context.getTargetInfo().getLongWidth());
4931 if (IsSwiftABI) {
4932 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4933 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4934 LengthTy = Int32Ty;
4935 else
4936 LengthTy = IntPtrTy;
4937 }
4938 Fields.addInt(LengthTy, StringLength);
4939
4940 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
4941 // properly aligned on 32-bit platforms.
4942 CharUnits Alignment =
4943 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
4944
4945 // The struct.
4946 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4947 /*isConstant=*/false,
4948 llvm::GlobalVariable::PrivateLinkage);
4949 GV->addAttribute("objc_arc_inert");
4950 switch (Triple.getObjectFormat()) {
4951 case llvm::Triple::UnknownObjectFormat:
4952 llvm_unreachable("unknown file format")::llvm::llvm_unreachable_internal("unknown file format", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4952)
;
4953 case llvm::Triple::GOFF:
4954 llvm_unreachable("GOFF is not yet implemented")::llvm::llvm_unreachable_internal("GOFF is not yet implemented"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4954)
;
4955 case llvm::Triple::XCOFF:
4956 llvm_unreachable("XCOFF is not yet implemented")::llvm::llvm_unreachable_internal("XCOFF is not yet implemented"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 4956)
;
4957 case llvm::Triple::COFF:
4958 case llvm::Triple::ELF:
4959 case llvm::Triple::Wasm:
4960 GV->setSection("cfstring");
4961 break;
4962 case llvm::Triple::MachO:
4963 GV->setSection("__DATA,__cfstring");
4964 break;
4965 }
4966 Entry.second = GV;
4967
4968 return ConstantAddress(GV, Alignment);
4969}
4970
4971bool CodeGenModule::getExpressionLocationsEnabled() const {
4972 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4973}
4974
4975QualType CodeGenModule::getObjCFastEnumerationStateType() {
4976 if (ObjCFastEnumerationStateType.isNull()) {
4977 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4978 D->startDefinition();
4979
4980 QualType FieldTypes[] = {
4981 Context.UnsignedLongTy,
4982 Context.getPointerType(Context.getObjCIdType()),
4983 Context.getPointerType(Context.UnsignedLongTy),
4984 Context.getConstantArrayType(Context.UnsignedLongTy,
4985 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
4986 };
4987
4988 for (size_t i = 0; i < 4; ++i) {
4989 FieldDecl *Field = FieldDecl::Create(Context,
4990 D,
4991 SourceLocation(),
4992 SourceLocation(), nullptr,
4993 FieldTypes[i], /*TInfo=*/nullptr,
4994 /*BitWidth=*/nullptr,
4995 /*Mutable=*/false,
4996 ICIS_NoInit);
4997 Field->setAccess(AS_public);
4998 D->addDecl(Field);
4999 }
5000
5001 D->completeDefinition();
5002 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5003 }
5004
5005 return ObjCFastEnumerationStateType;
5006}
5007
5008llvm::Constant *
5009CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5010 assert(!E->getType()->isPointerType() && "Strings are always arrays")((!E->getType()->isPointerType() && "Strings are always arrays"
) ? static_cast<void> (0) : __assert_fail ("!E->getType()->isPointerType() && \"Strings are always arrays\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 5010, __PRETTY_FUNCTION__))
;
5011
5012 // Don't emit it as the address of the string, emit the string data itself
5013 // as an inline array.
5014 if (E->getCharByteWidth() == 1) {
5015 SmallString<64> Str(E->getString());
5016
5017 // Resize the string to the right size, which is indicated by its type.
5018 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5019 Str.resize(CAT->getSize().getZExtValue());
5020 return llvm::ConstantDataArray::getString(VMContext, Str, false);
5021 }
5022
5023 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5024 llvm::Type *ElemTy = AType->getElementType();
5025 unsigned NumElements = AType->getNumElements();
5026
5027 // Wide strings have either 2-byte or 4-byte elements.
5028 if (ElemTy->getPrimitiveSizeInBits() == 16) {
5029 SmallVector<uint16_t, 32> Elements;
5030 Elements.reserve(NumElements);
5031
5032 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5033 Elements.push_back(E->getCodeUnit(i));
5034 Elements.resize(NumElements);
5035 return llvm::ConstantDataArray::get(VMContext, Elements);
5036 }
5037
5038 assert(ElemTy->getPrimitiveSizeInBits() == 32)((ElemTy->getPrimitiveSizeInBits() == 32) ? static_cast<
void> (0) : __assert_fail ("ElemTy->getPrimitiveSizeInBits() == 32"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 5038, __PRETTY_FUNCTION__))
;
5039 SmallVector<uint32_t, 32> Elements;
5040 Elements.reserve(NumElements);
5041
5042 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5043 Elements.push_back(E->getCodeUnit(i));
5044 Elements.resize(NumElements);
5045 return llvm::ConstantDataArray::get(VMContext, Elements);
5046}
5047
5048static llvm::GlobalVariable *
5049GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5050 CodeGenModule &CGM, StringRef GlobalName,
5051 CharUnits Alignment) {
5052 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5053 CGM.getStringLiteralAddressSpace());
5054
5055 llvm::Module &M = CGM.getModule();
5056 // Create a global variable for this string
5057 auto *GV = new llvm::GlobalVariable(
5058 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5059 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5060 GV->setAlignment(Alignment.getAsAlign());
5061 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5062 if (GV->isWeakForLinker()) {
5063 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals")((CGM.supportsCOMDAT() && "Only COFF uses weak string literals"
) ? static_cast<void> (0) : __assert_fail ("CGM.supportsCOMDAT() && \"Only COFF uses weak string literals\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 5063, __PRETTY_FUNCTION__))
;
5064 GV->setComdat(M.getOrInsertComdat(GV->getName()));
5065 }
5066 CGM.setDSOLocal(GV);
5067
5068 return GV;
5069}
5070
5071/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5072/// constant array for the given string literal.
5073ConstantAddress
5074CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5075 StringRef Name) {
5076 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5077
5078 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5079 llvm::GlobalVariable **Entry = nullptr;
5080 if (!LangOpts.WritableStrings) {
5081 Entry = &ConstantStringMap[C];
5082 if (auto GV = *Entry) {
5083 if (Alignment.getQuantity() > GV->getAlignment())
5084 GV->setAlignment(Alignment.getAsAlign());
5085 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5086 Alignment);
5087 }
5088 }
5089
5090 SmallString<256> MangledNameBuffer;
5091 StringRef GlobalVariableName;
5092 llvm::GlobalValue::LinkageTypes LT;
5093
5094 // Mangle the string literal if that's how the ABI merges duplicate strings.
5095 // Don't do it if they are writable, since we don't want writes in one TU to
5096 // affect strings in another.
5097 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5098 !LangOpts.WritableStrings) {
5099 llvm::raw_svector_ostream Out(MangledNameBuffer);
5100 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5101 LT = llvm::GlobalValue::LinkOnceODRLinkage;
5102 GlobalVariableName = MangledNameBuffer;
5103 } else {
5104 LT = llvm::GlobalValue::PrivateLinkage;
5105 GlobalVariableName = Name;
5106 }
5107
5108 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5109 if (Entry)
5110 *Entry = GV;
5111
5112 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
5113 QualType());
5114
5115 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5116 Alignment);
5117}
5118
5119/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5120/// array for the given ObjCEncodeExpr node.
5121ConstantAddress
5122CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5123 std::string Str;
5124 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5125
5126 return GetAddrOfConstantCString(Str);
5127}
5128
5129/// GetAddrOfConstantCString - Returns a pointer to a character array containing
5130/// the literal and a terminating '\0' character.
5131/// The result has pointer to array type.
5132ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5133 const std::string &Str, const char *GlobalName) {
5134 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5135 CharUnits Alignment =
5136 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5137
5138 llvm::Constant *C =
5139 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5140
5141 // Don't share any string literals if strings aren't constant.
5142 llvm::GlobalVariable **Entry = nullptr;
5143 if (!LangOpts.WritableStrings) {
5144 Entry = &ConstantStringMap[C];
5145 if (auto GV = *Entry) {
5146 if (Alignment.getQuantity() > GV->getAlignment())
5147 GV->setAlignment(Alignment.getAsAlign());
5148 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5149 Alignment);
5150 }
5151 }
5152
5153 // Get the default prefix if a name wasn't specified.
5154 if (!GlobalName)
5155 GlobalName = ".str";
5156 // Create a global variable for this.
5157 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5158 GlobalName, Alignment);
5159 if (Entry)
5160 *Entry = GV;
5161
5162 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5163 Alignment);
5164}
5165
5166ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5167 const MaterializeTemporaryExpr *E, const Expr *Init) {
5168 assert((E->getStorageDuration() == SD_Static ||(((E->getStorageDuration() == SD_Static || E->getStorageDuration
() == SD_Thread) && "not a global temporary") ? static_cast
<void> (0) : __assert_fail ("(E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && \"not a global temporary\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 5169, __PRETTY_FUNCTION__))
5169 E->getStorageDuration() == SD_Thread) && "not a global temporary")(((E->getStorageDuration() == SD_Static || E->getStorageDuration
() == SD_Thread) && "not a global temporary") ? static_cast
<void> (0) : __assert_fail ("(E->getStorageDuration() == SD_Static || E->getStorageDuration() == SD_Thread) && \"not a global temporary\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 5169, __PRETTY_FUNCTION__))
;
5170 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5171
5172 // If we're not materializing a subobject of the temporary, keep the
5173 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5174 QualType MaterializedType = Init->getType();
5175 if (Init == E->getSubExpr())
5176 MaterializedType = E->getType();
5177
5178 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5179
5180 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
5181 return ConstantAddress(Slot, Align);
5182
5183 // FIXME: If an externally-visible declaration extends multiple temporaries,
5184 // we need to give each temporary the same name in every translation unit (and
5185 // we also need to make the temporaries externally-visible).
5186 SmallString<256> Name;
5187 llvm::raw_svector_ostream Out(Name);
5188 getCXXABI().getMangleContext().mangleReferenceTemporary(
5189 VD, E->getManglingNumber(), Out);
5190
5191 APValue *Value = nullptr;
5192 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5193 // If the initializer of the extending declaration is a constant
5194 // initializer, we should have a cached constant initializer for this
5195 // temporary. Note that this might have a different value from the value
5196 // computed by evaluating the initializer if the surrounding constant
5197 // expression modifies the temporary.
5198 Value = E->getOrCreateValue(false);
5199 }
5200
5201 // Try evaluating it now, it might have a constant initializer.
5202 Expr::EvalResult EvalResult;
5203 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5204 !EvalResult.hasSideEffects())
5205 Value = &EvalResult.Val;
5206
5207 LangAS AddrSpace =
5208 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5209
5210 Optional<ConstantEmitter> emitter;
5211 llvm::Constant *InitialValue = nullptr;
5212 bool Constant = false;
5213 llvm::Type *Type;
5214 if (Value) {
5215 // The temporary has a constant initializer, use it.
5216 emitter.emplace(*this);
5217 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5218 MaterializedType);
5219 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5220 Type = InitialValue->getType();
5221 } else {
5222 // No initializer, the initialization will be provided when we
5223 // initialize the declaration which performed lifetime extension.
5224 Type = getTypes().ConvertTypeForMem(MaterializedType);
5225 }
5226
5227 // Create a global variable for this lifetime-extended temporary.
5228 llvm::GlobalValue::LinkageTypes Linkage =
5229 getLLVMLinkageVarDefinition(VD, Constant);
5230 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5231 const VarDecl *InitVD;
5232 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5233 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5234 // Temporaries defined inside a class get linkonce_odr linkage because the
5235 // class can be defined in multiple translation units.
5236 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5237 } else {
5238 // There is no need for this temporary to have external linkage if the
5239 // VarDecl has external linkage.
5240 Linkage = llvm::GlobalVariable::InternalLinkage;
5241 }
5242 }
5243 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5244 auto *GV = new llvm::GlobalVariable(
5245 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5246 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5247 if (emitter) emitter->finalize(GV);
5248 setGVProperties(GV, VD);
5249 GV->setAlignment(Align.getAsAlign());
5250 if (supportsCOMDAT() && GV->isWeakForLinker())
5251 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5252 if (VD->getTLSKind())
5253 setTLSMode(GV, *VD);
5254 llvm::Constant *CV = GV;
5255 if (AddrSpace != LangAS::Default)
5256 CV = getTargetCodeGenInfo().performAddrSpaceCast(
5257 *this, GV, AddrSpace, LangAS::Default,
5258 Type->getPointerTo(
5259 getContext().getTargetAddressSpace(LangAS::Default)));
5260 MaterializedGlobalTemporaryMap[E] = CV;
5261 return ConstantAddress(CV, Align);
5262}
5263
5264/// EmitObjCPropertyImplementations - Emit information for synthesized
5265/// properties for an implementation.
5266void CodeGenModule::EmitObjCPropertyImplementations(const
5267 ObjCImplementationDecl *D) {
5268 for (const auto *PID : D->property_impls()) {
5269 // Dynamic is just for type-checking.
5270 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5271 ObjCPropertyDecl *PD = PID->getPropertyDecl();
5272
5273 // Determine which methods need to be implemented, some may have
5274 // been overridden. Note that ::isPropertyAccessor is not the method
5275 // we want, that just indicates if the decl came from a
5276 // property. What we want to know is if the method is defined in
5277 // this implementation.
5278 auto *Getter = PID->getGetterMethodDecl();
5279 if (!Getter || Getter->isSynthesizedAccessorStub())
5280 CodeGenFunction(*this).GenerateObjCGetter(
5281 const_cast<ObjCImplementationDecl *>(D), PID);
5282 auto *Setter = PID->getSetterMethodDecl();
5283 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5284 CodeGenFunction(*this).GenerateObjCSetter(
5285 const_cast<ObjCImplementationDecl *>(D), PID);
5286 }
5287 }
5288}
5289
5290static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5291 const ObjCInterfaceDecl *iface = impl->getClassInterface();
5292 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5293 ivar; ivar = ivar->getNextIvar())
5294 if (ivar->getType().isDestructedType())
5295 return true;
5296
5297 return false;
5298}
5299
5300static bool AllTrivialInitializers(CodeGenModule &CGM,
5301 ObjCImplementationDecl *D) {
5302 CodeGenFunction CGF(CGM);
5303 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5304 E = D->init_end(); B != E; ++B) {
5305 CXXCtorInitializer *CtorInitExp = *B;
5306 Expr *Init = CtorInitExp->getInit();
5307 if (!CGF.isTrivialInitializer(Init))
5308 return false;
5309 }
5310 return true;
5311}
5312
5313/// EmitObjCIvarInitializations - Emit information for ivar initialization
5314/// for an implementation.
5315void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5316 // We might need a .cxx_destruct even if we don't have any ivar initializers.
5317 if (needsDestructMethod(D)) {
5318 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5319 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5320 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5321 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5322 getContext().VoidTy, nullptr, D,
5323 /*isInstance=*/true, /*isVariadic=*/false,
5324 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5325 /*isImplicitlyDeclared=*/true,
5326 /*isDefined=*/false, ObjCMethodDecl::Required);
5327 D->addInstanceMethod(DTORMethod);
5328 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5329 D->setHasDestructors(true);
5330 }
5331
5332 // If the implementation doesn't have any ivar initializers, we don't need
5333 // a .cxx_construct.
5334 if (D->getNumIvarInitializers() == 0 ||
5335 AllTrivialInitializers(*this, D))
5336 return;
5337
5338 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5339 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5340 // The constructor returns 'self'.
5341 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5342 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5343 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5344 /*isVariadic=*/false,
5345 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5346 /*isImplicitlyDeclared=*/true,
5347 /*isDefined=*/false, ObjCMethodDecl::Required);
5348 D->addInstanceMethod(CTORMethod);
5349 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5350 D->setHasNonZeroConstructors(true);
5351}
5352
5353// EmitLinkageSpec - Emit all declarations in a linkage spec.
5354void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5355 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5356 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5357 ErrorUnsupported(LSD, "linkage spec");
5358 return;
5359 }
5360
5361 EmitDeclContext(LSD);
5362}
5363
5364void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5365 for (auto *I : DC->decls()) {
5366 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5367 // are themselves considered "top-level", so EmitTopLevelDecl on an
5368 // ObjCImplDecl does not recursively visit them. We need to do that in
5369 // case they're nested inside another construct (LinkageSpecDecl /
5370 // ExportDecl) that does stop them from being considered "top-level".
5371 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5372 for (auto *M : OID->methods())
5373 EmitTopLevelDecl(M);
5374 }
5375
5376 EmitTopLevelDecl(I);
5377 }
5378}
5379
5380/// EmitTopLevelDecl - Emit code for a single top level declaration.
5381void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5382 // Ignore dependent declarations.
5383 if (D->isTemplated())
5384 return;
5385
5386 // Consteval function shouldn't be emitted.
5387 if (auto *FD = dyn_cast<FunctionDecl>(D))
5388 if (FD->isConsteval())
5389 return;
5390
5391 switch (D->getKind()) {
5392 case Decl::CXXConversion:
5393 case Decl::CXXMethod:
5394 case Decl::Function:
5395 EmitGlobal(cast<FunctionDecl>(D));
5396 // Always provide some coverage mapping
5397 // even for the functions that aren't emitted.
5398 AddDeferredUnusedCoverageMapping(D);
5399 break;
5400
5401 case Decl::CXXDeductionGuide:
5402 // Function-like, but does not result in code emission.
5403 break;
5404
5405 case Decl::Var:
5406 case Decl::Decomposition:
5407 case Decl::VarTemplateSpecialization:
5408 EmitGlobal(cast<VarDecl>(D));
5409 if (auto *DD = dyn_cast<DecompositionDecl>(D))
5410 for (auto *B : DD->bindings())
5411 if (auto *HD = B->getHoldingVar())
5412 EmitGlobal(HD);
5413 break;
5414
5415 // Indirect fields from global anonymous structs and unions can be
5416 // ignored; only the actual variable requires IR gen support.
5417 case Decl::IndirectField:
5418 break;
5419
5420 // C++ Decls
5421 case Decl::Namespace:
5422 EmitDeclContext(cast<NamespaceDecl>(D));
5423 break;
5424 case Decl::ClassTemplateSpecialization: {
5425 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5426 if (CGDebugInfo *DI = getModuleDebugInfo())
5427 if (Spec->getSpecializationKind() ==
5428 TSK_ExplicitInstantiationDefinition &&
5429 Spec->hasDefinition())
5430 DI->completeTemplateDefinition(*Spec);
5431 } LLVM_FALLTHROUGH[[gnu::fallthrough]];
5432 case Decl::CXXRecord: {
5433 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
5434 if (CGDebugInfo *DI = getModuleDebugInfo()) {
5435 if (CRD->hasDefinition())
5436 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5437 if (auto *ES = D->getASTContext().getExternalSource())
5438 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5439 DI->completeUnusedClass(*CRD);
5440 }
5441 // Emit any static data members, they may be definitions.
5442 for (auto *I : CRD->decls())
5443 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5444 EmitTopLevelDecl(I);
5445 break;
5446 }
5447 // No code generation needed.
5448 case Decl::UsingShadow:
5449 case Decl::ClassTemplate:
5450 case Decl::VarTemplate:
5451 case Decl::Concept:
5452 case Decl::VarTemplatePartialSpecialization:
5453 case Decl::FunctionTemplate:
5454 case Decl::TypeAliasTemplate:
5455 case Decl::Block:
5456 case Decl::Empty:
5457 case Decl::Binding:
5458 break;
5459 case Decl::Using: // using X; [C++]
5460 if (CGDebugInfo *DI = getModuleDebugInfo())
5461 DI->EmitUsingDecl(cast<UsingDecl>(*D));
5462 break;
5463 case Decl::NamespaceAlias:
5464 if (CGDebugInfo *DI = getModuleDebugInfo())
5465 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5466 break;
5467 case Decl::UsingDirective: // using namespace X; [C++]
5468 if (CGDebugInfo *DI = getModuleDebugInfo())
5469 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5470 break;
5471 case Decl::CXXConstructor:
5472 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5473 break;
5474 case Decl::CXXDestructor:
5475 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5476 break;
5477
5478 case Decl::StaticAssert:
5479 // Nothing to do.
5480 break;
5481
5482 // Objective-C Decls
5483
5484 // Forward declarations, no (immediate) code generation.
5485 case Decl::ObjCInterface:
5486 case Decl::ObjCCategory:
5487 break;
5488
5489 case Decl::ObjCProtocol: {
5490 auto *Proto = cast<ObjCProtocolDecl>(D);
5491 if (Proto->isThisDeclarationADefinition())
5492 ObjCRuntime->GenerateProtocol(Proto);
5493 break;
5494 }
5495
5496 case Decl::ObjCCategoryImpl:
5497 // Categories have properties but don't support synthesize so we
5498 // can ignore them here.
5499 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5500 break;
5501
5502 case Decl::ObjCImplementation: {
5503 auto *OMD = cast<ObjCImplementationDecl>(D);
5504 EmitObjCPropertyImplementations(OMD);
5505 EmitObjCIvarInitializations(OMD);
5506 ObjCRuntime->GenerateClass(OMD);
5507 // Emit global variable debug information.
5508 if (CGDebugInfo *DI = getModuleDebugInfo())
5509 if (getCodeGenOpts().hasReducedDebugInfo())
5510 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5511 OMD->getClassInterface()), OMD->getLocation());
5512 break;
5513 }
5514 case Decl::ObjCMethod: {
5515 auto *OMD = cast<ObjCMethodDecl>(D);
5516 // If this is not a prototype, emit the body.
5517 if (OMD->getBody())
5518 CodeGenFunction(*this).GenerateObjCMethod(OMD);
5519 break;
5520 }
5521 case Decl::ObjCCompatibleAlias:
5522 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5523 break;
5524
5525 case Decl::PragmaComment: {
5526 const auto *PCD = cast<PragmaCommentDecl>(D);
5527 switch (PCD->getCommentKind()) {
5528 case PCK_Unknown:
5529 llvm_unreachable("unexpected pragma comment kind")::llvm::llvm_unreachable_internal("unexpected pragma comment kind"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 5529)
;
5530 case PCK_Linker:
5531 AppendLinkerOptions(PCD->getArg());
5532 break;
5533 case PCK_Lib:
5534 AddDependentLib(PCD->getArg());
5535 break;
5536 case PCK_Compiler:
5537 case PCK_ExeStr:
5538 case PCK_User:
5539 break; // We ignore all of these.
5540 }
5541 break;
5542 }
5543
5544 case Decl::PragmaDetectMismatch: {
5545 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5546 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5547 break;
5548 }
5549
5550 case Decl::LinkageSpec:
5551 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5552 break;
5553
5554 case Decl::FileScopeAsm: {
5555 // File-scope asm is ignored during device-side CUDA compilation.
5556 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5557 break;
5558 // File-scope asm is ignored during device-side OpenMP compilation.
5559 if (LangOpts.OpenMPIsDevice)
5560 break;
5561 auto *AD = cast<FileScopeAsmDecl>(D);
5562 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5563 break;
5564 }
5565
5566 case Decl::Import: {
5567 auto *Import = cast<ImportDecl>(D);
5568
5569 // If we've already imported this module, we're done.
5570 if (!ImportedModules.insert(Import->getImportedModule()))
5571 break;
5572
5573 // Emit debug information for direct imports.
5574 if (!Import->getImportedOwningModule()) {
5575 if (CGDebugInfo *DI = getModuleDebugInfo())
5576 DI->EmitImportDecl(*Import);
5577 }
5578
5579 // Find all of the submodules and emit the module initializers.
5580 llvm::SmallPtrSet<clang::Module *, 16> Visited;
5581 SmallVector<clang::Module *, 16> Stack;
5582 Visited.insert(Import->getImportedModule());
5583 Stack.push_back(Import->getImportedModule());
5584
5585 while (!Stack.empty()) {
5586 clang::Module *Mod = Stack.pop_back_val();
5587 if (!EmittedModuleInitializers.insert(Mod).second)
5588 continue;
5589
5590 for (auto *D : Context.getModuleInitializers(Mod))
5591 EmitTopLevelDecl(D);
5592
5593 // Visit the submodules of this module.
5594 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5595 SubEnd = Mod->submodule_end();
5596 Sub != SubEnd; ++Sub) {
5597 // Skip explicit children; they need to be explicitly imported to emit
5598 // the initializers.
5599 if ((*Sub)->IsExplicit)
5600 continue;
5601
5602 if (Visited.insert(*Sub).second)
5603 Stack.push_back(*Sub);
5604 }
5605 }
5606 break;
5607 }
5608
5609 case Decl::Export:
5610 EmitDeclContext(cast<ExportDecl>(D));
5611 break;
5612
5613 case Decl::OMPThreadPrivate:
5614 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5615 break;
5616
5617 case Decl::OMPAllocate:
5618 break;
5619
5620 case Decl::OMPDeclareReduction:
5621 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5622 break;
5623
5624 case Decl::OMPDeclareMapper:
5625 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5626 break;
5627
5628 case Decl::OMPRequires:
5629 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5630 break;
5631
5632 case Decl::Typedef:
5633 case Decl::TypeAlias: // using foo = bar; [C++11]
5634 if (CGDebugInfo *DI = getModuleDebugInfo())
5635 DI->EmitAndRetainType(
5636 getContext().getTypedefType(cast<TypedefNameDecl>(D)));
5637 break;
5638
5639 case Decl::Record:
5640 if (CGDebugInfo *DI = getModuleDebugInfo())
5641 if (cast<RecordDecl>(D)->getDefinition())
5642 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5643 break;
5644
5645 case Decl::Enum:
5646 if (CGDebugInfo *DI = getModuleDebugInfo())
5647 if (cast<EnumDecl>(D)->getDefinition())
5648 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
5649 break;
5650
5651 default:
5652 // Make sure we handled everything we should, every other kind is a
5653 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
5654 // function. Need to recode Decl::Kind to do that easily.
5655 assert(isa<TypeDecl>(D) && "Unsupported decl kind")((isa<TypeDecl>(D) && "Unsupported decl kind") ?
static_cast<void> (0) : __assert_fail ("isa<TypeDecl>(D) && \"Unsupported decl kind\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 5655, __PRETTY_FUNCTION__))
;
5656 break;
5657 }
5658}
5659
5660void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5661 // Do we need to generate coverage mapping?
5662 if (!CodeGenOpts.CoverageMapping)
5663 return;
5664 switch (D->getKind()) {
5665 case Decl::CXXConversion:
5666 case Decl::CXXMethod:
5667 case Decl::Function:
5668 case Decl::ObjCMethod:
5669 case Decl::CXXConstructor:
5670 case Decl::CXXDestructor: {
5671 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5672 break;
5673 SourceManager &SM = getContext().getSourceManager();
5674 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5675 break;
5676 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5677 if (I == DeferredEmptyCoverageMappingDecls.end())
5678 DeferredEmptyCoverageMappingDecls[D] = true;
5679 break;
5680 }
5681 default:
5682 break;
5683 };
5684}
5685
5686void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5687 // Do we need to generate coverage mapping?
5688 if (!CodeGenOpts.CoverageMapping)
5689 return;
5690 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5691 if (Fn->isTemplateInstantiation())
5692 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5693 }
5694 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5695 if (I == DeferredEmptyCoverageMappingDecls.end())
5696 DeferredEmptyCoverageMappingDecls[D] = false;
5697 else
5698 I->second = false;
5699}
5700
5701void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5702 // We call takeVector() here to avoid use-after-free.
5703 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5704 // we deserialize function bodies to emit coverage info for them, and that
5705 // deserializes more declarations. How should we handle that case?
5706 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5707 if (!Entry.second)
5708 continue;
5709 const Decl *D = Entry.first;
5710 switch (D->getKind()) {
5711 case Decl::CXXConversion:
5712 case Decl::CXXMethod:
5713 case Decl::Function:
5714 case Decl::ObjCMethod: {
5715 CodeGenPGO PGO(*this);
5716 GlobalDecl GD(cast<FunctionDecl>(D));
5717 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5718 getFunctionLinkage(GD));
5719 break;
5720 }
5721 case Decl::CXXConstructor: {
5722 CodeGenPGO PGO(*this);
5723 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5724 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5725 getFunctionLinkage(GD));
5726 break;
5727 }
5728 case Decl::CXXDestructor: {
5729 CodeGenPGO PGO(*this);
5730 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5731 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5732 getFunctionLinkage(GD));
5733 break;
5734 }
5735 default:
5736 break;
5737 };
5738 }
5739}
5740
5741void CodeGenModule::EmitMainVoidAlias() {
5742 // In order to transition away from "__original_main" gracefully, emit an
5743 // alias for "main" in the no-argument case so that libc can detect when
5744 // new-style no-argument main is in used.
5745 if (llvm::Function *F = getModule().getFunction("main")) {
5746 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
5747 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
5748 addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
5749 }
5750}
5751
5752/// Turns the given pointer into a constant.
5753static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5754 const void *Ptr) {
5755 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
5756 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5757 return llvm::ConstantInt::get(i64, PtrInt);
5758}
5759
5760static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5761 llvm::NamedMDNode *&GlobalMetadata,
5762 GlobalDecl D,
5763 llvm::GlobalValue *Addr) {
5764 if (!GlobalMetadata)
5765 GlobalMetadata =
5766 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5767
5768 // TODO: should we report variant information for ctors/dtors?
5769 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5770 llvm::ConstantAsMetadata::get(GetPointerConstant(
5771 CGM.getLLVMContext(), D.getDecl()))};
5772 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
5773}
5774
5775/// For each function which is declared within an extern "C" region and marked
5776/// as 'used', but has internal linkage, create an alias from the unmangled
5777/// name to the mangled name if possible. People expect to be able to refer
5778/// to such functions with an unmangled name from inline assembly within the
5779/// same translation unit.
5780void CodeGenModule::EmitStaticExternCAliases() {
5781 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
5782 return;
5783 for (auto &I : StaticExternCValues) {
5784 IdentifierInfo *Name = I.first;
5785 llvm::GlobalValue *Val = I.second;
5786 if (Val && !getModule().getNamedValue(Name->getName()))
5787 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
5788 }
5789}
5790
5791bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5792 GlobalDecl &Result) const {
5793 auto Res = Manglings.find(MangledName);
5794 if (Res == Manglings.end())
5795 return false;
5796 Result = Res->getValue();
5797 return true;
5798}
5799
5800/// Emits metadata nodes associating all the global values in the
5801/// current module with the Decls they came from. This is useful for
5802/// projects using IR gen as a subroutine.
5803///
5804/// Since there's currently no way to associate an MDNode directly
5805/// with an llvm::GlobalValue, we create a global named metadata
5806/// with the name 'clang.global.decl.ptrs'.
5807void CodeGenModule::EmitDeclMetadata() {
5808 llvm::NamedMDNode *GlobalMetadata = nullptr;
5809
5810 for (auto &I : MangledDeclNames) {
5811 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
5812 // Some mangled names don't necessarily have an associated GlobalValue
5813 // in this module, e.g. if we mangled it for DebugInfo.
5814 if (Addr)
5815 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
5816 }
5817}
5818
5819/// Emits metadata nodes for all the local variables in the current
5820/// function.
5821void CodeGenFunction::EmitDeclMetadata() {
5822 if (LocalDeclMap.empty()) return;
5823
5824 llvm::LLVMContext &Context = getLLVMContext();
5825
5826 // Find the unique metadata ID for this name.
5827 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5828
5829 llvm::NamedMDNode *GlobalMetadata = nullptr;
5830
5831 for (auto &I : LocalDeclMap) {
5832 const Decl *D = I.first;
5833 llvm::Value *Addr = I.second.getPointer();
5834 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5835 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
5836 Alloca->setMetadata(
5837 DeclPtrKind, llvm::MDNode::get(
5838 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5839 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5840 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5841 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5842 }
5843 }
5844}
5845
5846void CodeGenModule::EmitVersionIdentMetadata() {
5847 llvm::NamedMDNode *IdentMetadata =
5848 TheModule.getOrInsertNamedMetadata("llvm.ident");
5849 std::string Version = getClangFullVersion();
5850 llvm::LLVMContext &Ctx = TheModule.getContext();
5851
5852 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5853 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5854}
5855
5856void CodeGenModule::EmitCommandLineMetadata() {
5857 llvm::NamedMDNode *CommandLineMetadata =
5858 TheModule.getOrInsertNamedMetadata("llvm.commandline");
5859 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5860 llvm::LLVMContext &Ctx = TheModule.getContext();
5861
5862 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5863 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5864}
5865
5866void CodeGenModule::EmitCoverageFile() {
5867 if (getCodeGenOpts().CoverageDataFile.empty() &&
5868 getCodeGenOpts().CoverageNotesFile.empty())
5869 return;
5870
5871 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5872 if (!CUNode)
5873 return;
5874
5875 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5876 llvm::LLVMContext &Ctx = TheModule.getContext();
5877 auto *CoverageDataFile =
5878 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5879 auto *CoverageNotesFile =
5880 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5881 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5882 llvm::MDNode *CU = CUNode->getOperand(i);
5883 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5884 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5885 }
5886}
5887
5888llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5889 bool ForEH) {
5890 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5891 // FIXME: should we even be calling this method if RTTI is disabled
5892 // and it's not for EH?
5893 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
5894 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
5895 getTriple().isNVPTX()))
5896 return llvm::Constant::getNullValue(Int8PtrTy);
5897
5898 if (ForEH && Ty->isObjCObjectPointerType() &&
5899 LangOpts.ObjCRuntime.isGNUFamily())
5900 return ObjCRuntime->GetEHType(Ty);
5901
5902 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5903}
5904
5905void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5906 // Do not emit threadprivates in simd-only mode.
5907 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5908 return;
5909 for (auto RefExpr : D->varlists()) {
5910 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5911 bool PerformInit =
5912 VD->getAnyInitializer() &&
5913 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5914 /*ForRef=*/false);
5915
5916 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5917 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5918 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5919 CXXGlobalInits.push_back(InitFunction);
5920 }
5921}
5922
5923llvm::Metadata *
5924CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5925 StringRef Suffix) {
5926 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5927 if (InternalId)
5928 return InternalId;
5929
5930 if (isExternallyVisible(T->getLinkage())) {
5931 std::string OutName;
5932 llvm::raw_string_ostream Out(OutName);
5933 getCXXABI().getMangleContext().mangleTypeName(T, Out);
5934 Out << Suffix;
5935
5936 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5937 } else {
5938 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5939 llvm::ArrayRef<llvm::Metadata *>());
5940 }
5941
5942 return InternalId;
5943}
5944
5945llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5946 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5947}
5948
5949llvm::Metadata *
5950CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5951 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5952}
5953
5954// Generalize pointer types to a void pointer with the qualifiers of the
5955// originally pointed-to type, e.g. 'const char *' and 'char * const *'
5956// generalize to 'const void *' while 'char *' and 'const char **' generalize to
5957// 'void *'.
5958static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5959 if (!Ty->isPointerType())
5960 return Ty;
5961
5962 return Ctx.getPointerType(
5963 QualType(Ctx.VoidTy).withCVRQualifiers(
5964 Ty->getPointeeType().getCVRQualifiers()));
5965}
5966
5967// Apply type generalization to a FunctionType's return and argument types
5968static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5969 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5970 SmallVector<QualType, 8> GeneralizedParams;
5971 for (auto &Param : FnType->param_types())
5972 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5973
5974 return Ctx.getFunctionType(
5975 GeneralizeType(Ctx, FnType->getReturnType()),
5976 GeneralizedParams, FnType->getExtProtoInfo());
5977 }
5978
5979 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5980 return Ctx.getFunctionNoProtoType(
5981 GeneralizeType(Ctx, FnType->getReturnType()));
5982
5983 llvm_unreachable("Encountered unknown FunctionType")::llvm::llvm_unreachable_internal("Encountered unknown FunctionType"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/CodeGen/CodeGenModule.cpp"
, 5983)
;
5984}
5985
5986llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
5987 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5988 GeneralizedMetadataIdMap, ".generalized");
5989}
5990
5991/// Returns whether this module needs the "all-vtables" type identifier.
5992bool CodeGenModule::NeedAllVtablesTypeId() const {
5993 // Returns true if at least one of vtable-based CFI checkers is enabled and
5994 // is not in the trapping mode.
5995 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5996 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5997 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5998 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5999 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
6000 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
6001 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
6002 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
6003}
6004
6005void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
6006 CharUnits Offset,
6007 const CXXRecordDecl *RD) {
6008 llvm::Metadata *MD =
6009 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
6010 VTable->addTypeMetadata(Offset.getQuantity(), MD);
6011
6012 if (CodeGenOpts.SanitizeCfiCrossDso)
6013 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
6014 VTable->addTypeMetadata(Offset.getQuantity(),
6015 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
6016
6017 if (NeedAllVtablesTypeId()) {
6018 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
6019 VTable->addTypeMetadata(Offset.getQuantity(), MD);
6020 }
6021}
6022
6023llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
6024 if (!SanStats)
6025 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
6026
6027 return *SanStats;
6028}
6029llvm::Value *
6030CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
6031 CodeGenFunction &CGF) {
6032 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6033 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6034 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6035 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
6036 "__translate_sampler_initializer"),
6037 {C});
6038}
6039
6040CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
6041 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
6042 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
6043 /* forPointeeType= */ true);
6044}
6045
6046CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
6047 LValueBaseInfo *BaseInfo,
6048 TBAAAccessInfo *TBAAInfo,
6049 bool forPointeeType) {
6050 if (TBAAInfo)
6051 *TBAAInfo = getTBAAAccessInfo(T);
6052
6053 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
6054 // that doesn't return the information we need to compute BaseInfo.
6055
6056 // Honor alignment typedef attributes even on incomplete types.
6057 // We also honor them straight for C++ class types, even as pointees;
6058 // there's an expressivity gap here.
6059 if (auto TT = T->getAs<TypedefType>()) {
6060 if (auto Align = TT->getDecl()->getMaxAlignment()) {
6061 if (BaseInfo)
6062 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
6063 return getContext().toCharUnitsFromBits(Align);
6064 }
6065 }
6066
6067 bool AlignForArray = T->isArrayType();
6068
6069 // Analyze the base element type, so we don't get confused by incomplete
6070 // array types.
6071 T = getContext().getBaseElementType(T);
6072
6073 if (T->isIncompleteType()) {
6074 // We could try to replicate the logic from
6075 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
6076 // type is incomplete, so it's impossible to test. We could try to reuse
6077 // getTypeAlignIfKnown, but that doesn't return the information we need
6078 // to set BaseInfo. So just ignore the possibility that the alignment is
6079 // greater than one.
6080 if (BaseInfo)
6081 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6082 return CharUnits::One();
6083 }
6084
6085 if (BaseInfo)
6086 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6087
6088 CharUnits Alignment;
6089 // For C++ class pointees, we don't know whether we're pointing at a
6090 // base or a complete object, so we generally need to use the
6091 // non-virtual alignment.
6092 const CXXRecordDecl *RD;
6093 if (forPointeeType && !AlignForArray && (RD = T->getAsCXXRecordDecl())) {
6094 Alignment = getClassPointerAlignment(RD);
6095 } else {
6096 Alignment = getContext().getTypeAlignInChars(T);
6097 if (T.getQualifiers().hasUnaligned())
6098 Alignment = CharUnits::One();
6099 }
6100
6101 // Cap to the global maximum type alignment unless the alignment
6102 // was somehow explicit on the type.
6103 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
6104 if (Alignment.getQuantity() > MaxAlign &&
6105 !getContext().isAlignmentRequired(T))
6106 Alignment = CharUnits::fromQuantity(MaxAlign);
6107 }
6108 return Alignment;
6109}
6110
6111bool CodeGenModule::stopAutoInit() {
6112 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
6113 if (StopAfter) {
6114 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
6115 // used
6116 if (NumAutoVarInit >= StopAfter) {
6117 return true;
6118 }
6119 if (!NumAutoVarInit) {
6120 unsigned DiagID = getDiags().getCustomDiagID(
6121 DiagnosticsEngine::Warning,
6122 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
6123 "number of times ftrivial-auto-var-init=%1 gets applied.");
6124 getDiags().Report(DiagID)
6125 << StopAfter
6126 << (getContext().getLangOpts().getTrivialAutoVarInit() ==
6127 LangOptions::TrivialAutoVarInitKind::Zero
6128 ? "zero"
6129 : "pattern");
6130 }
6131 ++NumAutoVarInit;
6132 }
6133 return false;
6134}

/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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());
8
Returning zero, which participates in a condition later
27
Returning zero, which participates in a condition later
30
Returning zero, which participates in a condition later
34
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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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-12~++20200927111121+5811d723998/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,
1250 NamedDecl *const>;
1251
1252 class iterator : public IteratorBase {
1253 value_type SingleElement;
1254
1255 public:
1256 explicit iterator(pointer Pos, value_type Single = nullptr)
1257 : IteratorBase(Pos), SingleElement(Single) {}
1258
1259 reference operator*() const {
1260 return SingleElement ? SingleElement : IteratorBase::operator*();
1261 }
1262 };
1263
1264 using const_iterator = iterator;
1265 using pointer = iterator::pointer;
1266 using reference = iterator::reference;
1267
1268 iterator begin() const { return iterator(Result.begin(), Single); }
1269 iterator end() const { return iterator(Result.end(), Single); }
1270
1271 bool empty() const { return Result.empty(); }
1272 pointer data() const { return Single ? &Single : Result.data(); }
1273 size_t size() const { return Single ? 1 : Result.size(); }
1274 reference front() const { return Single ? Single : Result.front(); }
1275 reference back() const { return Single ? Single : Result.back(); }
1276 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1277
1278 // FIXME: Remove this from the interface
1279 DeclContextLookupResult slice(size_t N) const {
1280 DeclContextLookupResult Sliced = Result.slice(N);
1281 Sliced.Single = Single;
1282 return Sliced;
1283 }
1284};
1285
1286/// DeclContext - This is used only as base class of specific decl types that
1287/// can act as declaration contexts. These decls are (only the top classes
1288/// that directly derive from DeclContext are mentioned, not their subclasses):
1289///
1290/// TranslationUnitDecl
1291/// ExternCContext
1292/// NamespaceDecl
1293/// TagDecl
1294/// OMPDeclareReductionDecl
1295/// OMPDeclareMapperDecl
1296/// FunctionDecl
1297/// ObjCMethodDecl
1298/// ObjCContainerDecl
1299/// LinkageSpecDecl
1300/// ExportDecl
1301/// BlockDecl
1302/// CapturedDecl
1303class DeclContext {
1304 /// For makeDeclVisibleInContextImpl
1305 friend class ASTDeclReader;
1306 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1307 /// hasNeedToReconcileExternalVisibleStorage
1308 friend class ExternalASTSource;
1309 /// For CreateStoredDeclsMap
1310 friend class DependentDiagnostic;
1311 /// For hasNeedToReconcileExternalVisibleStorage,
1312 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1313 friend class ASTWriter;
1314
1315 // We use uint64_t in the bit-fields below since some bit-fields
1316 // cross the unsigned boundary and this breaks the packing.
1317
1318 /// Stores the bits used by DeclContext.
1319 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1320 /// methods in DeclContext should be updated appropriately.
1321 class DeclContextBitfields {
1322 friend class DeclContext;
1323 /// DeclKind - This indicates which class this is.
1324 uint64_t DeclKind : 7;
1325
1326 /// Whether this declaration context also has some external
1327 /// storage that contains additional declarations that are lexically
1328 /// part of this context.
1329 mutable uint64_t ExternalLexicalStorage : 1;
1330
1331 /// Whether this declaration context also has some external
1332 /// storage that contains additional declarations that are visible
1333 /// in this context.
1334 mutable uint64_t ExternalVisibleStorage : 1;
1335
1336 /// Whether this declaration context has had externally visible
1337 /// storage added since the last lookup. In this case, \c LookupPtr's
1338 /// invariant may not hold and needs to be fixed before we perform
1339 /// another lookup.
1340 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1341
1342 /// If \c true, this context may have local lexical declarations
1343 /// that are missing from the lookup table.
1344 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1345
1346 /// If \c true, the external source may have lexical declarations
1347 /// that are missing from the lookup table.
1348 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1349
1350 /// If \c true, lookups should only return identifier from
1351 /// DeclContext scope (for example TranslationUnit). Used in
1352 /// LookupQualifiedName()
1353 mutable uint64_t UseQualifiedLookup : 1;
1354 };
1355
1356 /// Number of bits in DeclContextBitfields.
1357 enum { NumDeclContextBits = 13 };
1358
1359 /// Stores the bits used by TagDecl.
1360 /// If modified NumTagDeclBits and the accessor
1361 /// methods in TagDecl should be updated appropriately.
1362 class TagDeclBitfields {
1363 friend class TagDecl;
1364 /// For the bits in DeclContextBitfields
1365 uint64_t : NumDeclContextBits;
1366
1367 /// The TagKind enum.
1368 uint64_t TagDeclKind : 3;
1369
1370 /// True if this is a definition ("struct foo {};"), false if it is a
1371 /// declaration ("struct foo;"). It is not considered a definition
1372 /// until the definition has been fully processed.
1373 uint64_t IsCompleteDefinition : 1;
1374
1375 /// True if this is currently being defined.
1376 uint64_t IsBeingDefined : 1;
1377
1378 /// True if this tag declaration is "embedded" (i.e., defined or declared
1379 /// for the very first time) in the syntax of a declarator.
1380 uint64_t IsEmbeddedInDeclarator : 1;
1381
1382 /// True if this tag is free standing, e.g. "struct foo;".
1383 uint64_t IsFreeStanding : 1;
1384
1385 /// Indicates whether it is possible for declarations of this kind
1386 /// to have an out-of-date definition.
1387 ///
1388 /// This option is only enabled when modules are enabled.
1389 uint64_t MayHaveOutOfDateDef : 1;
1390
1391 /// Has the full definition of this type been required by a use somewhere in
1392 /// the TU.
1393 uint64_t IsCompleteDefinitionRequired : 1;
1394 };
1395
1396 /// Number of non-inherited bits in TagDeclBitfields.
1397 enum { NumTagDeclBits = 9 };
1398
1399 /// Stores the bits used by EnumDecl.
1400 /// If modified NumEnumDeclBit and the accessor
1401 /// methods in EnumDecl should be updated appropriately.
1402 class EnumDeclBitfields {
1403 friend class EnumDecl;
1404 /// For the bits in DeclContextBitfields.
1405 uint64_t : NumDeclContextBits;
1406 /// For the bits in TagDeclBitfields.
1407 uint64_t : NumTagDeclBits;
1408
1409 /// Width in bits required to store all the non-negative
1410 /// enumerators of this enum.
1411 uint64_t NumPositiveBits : 8;
1412
1413 /// Width in bits required to store all the negative
1414 /// enumerators of this enum.
1415 uint64_t NumNegativeBits : 8;
1416
1417 /// True if this tag declaration is a scoped enumeration. Only
1418 /// possible in C++11 mode.
1419 uint64_t IsScoped : 1;
1420
1421 /// If this tag declaration is a scoped enum,
1422 /// then this is true if the scoped enum was declared using the class
1423 /// tag, false if it was declared with the struct tag. No meaning is
1424 /// associated if this tag declaration is not a scoped enum.
1425 uint64_t IsScopedUsingClassTag : 1;
1426
1427 /// True if this is an enumeration with fixed underlying type. Only
1428 /// possible in C++11, Microsoft extensions, or Objective C mode.
1429 uint64_t IsFixed : 1;
1430
1431 /// True if a valid hash is stored in ODRHash.
1432 uint64_t HasODRHash : 1;
1433 };
1434
1435 /// Number of non-inherited bits in EnumDeclBitfields.
1436 enum { NumEnumDeclBits = 20 };
1437
1438 /// Stores the bits used by RecordDecl.
1439 /// If modified NumRecordDeclBits and the accessor
1440 /// methods in RecordDecl should be updated appropriately.
1441 class RecordDeclBitfields {
1442 friend class RecordDecl;
1443 /// For the bits in DeclContextBitfields.
1444 uint64_t : NumDeclContextBits;
1445 /// For the bits in TagDeclBitfields.
1446 uint64_t : NumTagDeclBits;
1447
1448 /// This is true if this struct ends with a flexible
1449 /// array member (e.g. int X[]) or if this union contains a struct that does.
1450 /// If so, this cannot be contained in arrays or other structs as a member.
1451 uint64_t HasFlexibleArrayMember : 1;
1452
1453 /// Whether this is the type of an anonymous struct or union.
1454 uint64_t AnonymousStructOrUnion : 1;
1455
1456 /// This is true if this struct has at least one member
1457 /// containing an Objective-C object pointer type.
1458 uint64_t HasObjectMember : 1;
1459
1460 /// This is true if struct has at least one member of
1461 /// 'volatile' type.
1462 uint64_t HasVolatileMember : 1;
1463
1464 /// Whether the field declarations of this record have been loaded
1465 /// from external storage. To avoid unnecessary deserialization of
1466 /// methods/nested types we allow deserialization of just the fields
1467 /// when needed.
1468 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1469
1470 /// Basic properties of non-trivial C structs.
1471 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1472 uint64_t NonTrivialToPrimitiveCopy : 1;
1473 uint64_t NonTrivialToPrimitiveDestroy : 1;
1474
1475 /// The following bits indicate whether this is or contains a C union that
1476 /// is non-trivial to default-initialize, destruct, or copy. These bits
1477 /// imply the associated basic non-triviality predicates declared above.
1478 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1479 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1480 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1481
1482 /// Indicates whether this struct is destroyed in the callee.
1483 uint64_t ParamDestroyedInCallee : 1;
1484
1485 /// Represents the way this type is passed to a function.
1486 uint64_t ArgPassingRestrictions : 2;
1487 };
1488
1489 /// Number of non-inherited bits in RecordDeclBitfields.
1490 enum { NumRecordDeclBits = 14 };
1491
1492 /// Stores the bits used by OMPDeclareReductionDecl.
1493 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1494 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1495 class OMPDeclareReductionDeclBitfields {
1496 friend class OMPDeclareReductionDecl;
1497 /// For the bits in DeclContextBitfields
1498 uint64_t : NumDeclContextBits;
1499
1500 /// Kind of initializer,
1501 /// function call or omp_priv<init_expr> initializtion.
1502 uint64_t InitializerKind : 2;
1503 };
1504
1505 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1506 enum { NumOMPDeclareReductionDeclBits = 2 };
1507
1508 /// Stores the bits used by FunctionDecl.
1509 /// If modified NumFunctionDeclBits and the accessor
1510 /// methods in FunctionDecl and CXXDeductionGuideDecl
1511 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1512 class FunctionDeclBitfields {
1513 friend class FunctionDecl;
1514 /// For IsCopyDeductionCandidate
1515 friend class CXXDeductionGuideDecl;
1516 /// For the bits in DeclContextBitfields.
1517 uint64_t : NumDeclContextBits;
1518
1519 uint64_t SClass : 3;
1520 uint64_t IsInline : 1;
1521 uint64_t IsInlineSpecified : 1;
1522
1523 uint64_t IsVirtualAsWritten : 1;
1524 uint64_t IsPure : 1;
1525 uint64_t HasInheritedPrototype : 1;
1526 uint64_t HasWrittenPrototype : 1;
1527 uint64_t IsDeleted : 1;
1528 /// Used by CXXMethodDecl
1529 uint64_t IsTrivial : 1;
1530
1531 /// This flag indicates whether this function is trivial for the purpose of
1532 /// calls. This is meaningful only when this function is a copy/move
1533 /// constructor or a destructor.
1534 uint64_t IsTrivialForCall : 1;
1535
1536 uint64_t IsDefaulted : 1;
1537 uint64_t IsExplicitlyDefaulted : 1;
1538 uint64_t HasDefaultedFunctionInfo : 1;
1539 uint64_t HasImplicitReturnZero : 1;
1540 uint64_t IsLateTemplateParsed : 1;
1541
1542 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1543 uint64_t ConstexprKind : 2;
1544 uint64_t InstantiationIsPending : 1;
1545
1546 /// Indicates if the function uses __try.
1547 uint64_t UsesSEHTry : 1;
1548
1549 /// Indicates if the function was a definition
1550 /// but its body was skipped.
1551 uint64_t HasSkippedBody : 1;
1552
1553 /// Indicates if the function declaration will
1554 /// have a body, once we're done parsing it.
1555 uint64_t WillHaveBody : 1;
1556
1557 /// Indicates that this function is a multiversioned
1558 /// function using attribute 'target'.
1559 uint64_t IsMultiVersion : 1;
1560
1561 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1562 /// the Deduction Guide is the implicitly generated 'copy
1563 /// deduction candidate' (is used during overload resolution).
1564 uint64_t IsCopyDeductionCandidate : 1;
1565
1566 /// Store the ODRHash after first calculation.
1567 uint64_t HasODRHash : 1;
1568
1569 /// Indicates if the function uses Floating Point Constrained Intrinsics
1570 uint64_t UsesFPIntrin : 1;
1571 };
1572
1573 /// Number of non-inherited bits in FunctionDeclBitfields.
1574 enum { NumFunctionDeclBits = 27 };
1575
1576 /// Stores the bits used by CXXConstructorDecl. If modified
1577 /// NumCXXConstructorDeclBits and the accessor
1578 /// methods in CXXConstructorDecl should be updated appropriately.
1579 class CXXConstructorDeclBitfields {
1580 friend class CXXConstructorDecl;
1581 /// For the bits in DeclContextBitfields.
1582 uint64_t : NumDeclContextBits;
1583 /// For the bits in FunctionDeclBitfields.
1584 uint64_t : NumFunctionDeclBits;
1585
1586 /// 24 bits to fit in the remaining available space.
1587 /// Note that this makes CXXConstructorDeclBitfields take
1588 /// exactly 64 bits and thus the width of NumCtorInitializers
1589 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1590 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1591 uint64_t NumCtorInitializers : 21;
1592 uint64_t IsInheritingConstructor : 1;
1593
1594 /// Whether this constructor has a trail-allocated explicit specifier.
1595 uint64_t HasTrailingExplicitSpecifier : 1;
1596 /// If this constructor does't have a trail-allocated explicit specifier.
1597 /// Whether this constructor is explicit specified.
1598 uint64_t IsSimpleExplicit : 1;
1599 };
1600
1601 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1602 enum {
1603 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1604 };
1605
1606 /// Stores the bits used by ObjCMethodDecl.
1607 /// If modified NumObjCMethodDeclBits and the accessor
1608 /// methods in ObjCMethodDecl should be updated appropriately.
1609 class ObjCMethodDeclBitfields {
1610 friend class ObjCMethodDecl;
1611
1612 /// For the bits in DeclContextBitfields.
1613 uint64_t : NumDeclContextBits;
1614
1615 /// The conventional meaning of this method; an ObjCMethodFamily.
1616 /// This is not serialized; instead, it is computed on demand and
1617 /// cached.
1618 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1619
1620 /// instance (true) or class (false) method.
1621 uint64_t IsInstance : 1;
1622 uint64_t IsVariadic : 1;
1623
1624 /// True if this method is the getter or setter for an explicit property.
1625 uint64_t IsPropertyAccessor : 1;
1626
1627 /// True if this method is a synthesized property accessor stub.
1628 uint64_t IsSynthesizedAccessorStub : 1;
1629
1630 /// Method has a definition.
1631 uint64_t IsDefined : 1;
1632
1633 /// Method redeclaration in the same interface.
1634 uint64_t IsRedeclaration : 1;
1635
1636 /// Is redeclared in the same interface.
1637 mutable uint64_t HasRedeclaration : 1;
1638
1639 /// \@required/\@optional
1640 uint64_t DeclImplementation : 2;
1641
1642 /// in, inout, etc.
1643 uint64_t objcDeclQualifier : 7;
1644
1645 /// Indicates whether this method has a related result type.
1646 uint64_t RelatedResultType : 1;
1647
1648 /// Whether the locations of the selector identifiers are in a
1649 /// "standard" position, a enum SelectorLocationsKind.
1650 uint64_t SelLocsKind : 2;
1651
1652 /// Whether this method overrides any other in the class hierarchy.
1653 ///
1654 /// A method is said to override any method in the class's
1655 /// base classes, its protocols, or its categories' protocols, that has
1656 /// the same selector and is of the same kind (class or instance).
1657 /// A method in an implementation is not considered as overriding the same
1658 /// method in the interface or its categories.
1659 uint64_t IsOverriding : 1;
1660
1661 /// Indicates if the method was a definition but its body was skipped.
1662 uint64_t HasSkippedBody : 1;
1663 };
1664
1665 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1666 enum { NumObjCMethodDeclBits = 24 };
1667
1668 /// Stores the bits used by ObjCContainerDecl.
1669 /// If modified NumObjCContainerDeclBits and the accessor
1670 /// methods in ObjCContainerDecl should be updated appropriately.
1671 class ObjCContainerDeclBitfields {
1672 friend class ObjCContainerDecl;
1673 /// For the bits in DeclContextBitfields
1674 uint32_t : NumDeclContextBits;
1675
1676 // Not a bitfield but this saves space.
1677 // Note that ObjCContainerDeclBitfields is full.
1678 SourceLocation AtStart;
1679 };
1680
1681 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1682 /// Note that here we rely on the fact that SourceLocation is 32 bits
1683 /// wide. We check this with the static_assert in the ctor of DeclContext.
1684 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1685
1686 /// Stores the bits used by LinkageSpecDecl.
1687 /// If modified NumLinkageSpecDeclBits and the accessor
1688 /// methods in LinkageSpecDecl should be updated appropriately.
1689 class LinkageSpecDeclBitfields {
1690 friend class LinkageSpecDecl;
1691 /// For the bits in DeclContextBitfields.
1692 uint64_t : NumDeclContextBits;
1693
1694 /// The language for this linkage specification with values
1695 /// in the enum LinkageSpecDecl::LanguageIDs.
1696 uint64_t Language : 3;
1697
1698 /// True if this linkage spec has braces.
1699 /// This is needed so that hasBraces() returns the correct result while the
1700 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1701 /// not used, so it doesn't need to be serialized.
1702 uint64_t HasBraces : 1;
1703 };
1704
1705 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1706 enum { NumLinkageSpecDeclBits = 4 };
1707
1708 /// Stores the bits used by BlockDecl.
1709 /// If modified NumBlockDeclBits and the accessor
1710 /// methods in BlockDecl should be updated appropriately.
1711 class BlockDeclBitfields {
1712 friend class BlockDecl;
1713 /// For the bits in DeclContextBitfields.
1714 uint64_t : NumDeclContextBits;
1715
1716 uint64_t IsVariadic : 1;
1717 uint64_t CapturesCXXThis : 1;
1718 uint64_t BlockMissingReturnType : 1;
1719 uint64_t IsConversionFromLambda : 1;
1720
1721 /// A bit that indicates this block is passed directly to a function as a
1722 /// non-escaping parameter.
1723 uint64_t DoesNotEscape : 1;
1724
1725 /// A bit that indicates whether it's possible to avoid coying this block to
1726 /// the heap when it initializes or is assigned to a local variable with
1727 /// automatic storage.
1728 uint64_t CanAvoidCopyToHeap : 1;
1729 };
1730
1731 /// Number of non-inherited bits in BlockDeclBitfields.
1732 enum { NumBlockDeclBits = 5 };
1733
1734 /// Pointer to the data structure used to lookup declarations
1735 /// within this context (or a DependentStoredDeclsMap if this is a
1736 /// dependent context). We maintain the invariant that, if the map
1737 /// contains an entry for a DeclarationName (and we haven't lazily
1738 /// omitted anything), then it contains all relevant entries for that
1739 /// name (modulo the hasExternalDecls() flag).
1740 mutable StoredDeclsMap *LookupPtr = nullptr;
1741
1742protected:
1743 /// This anonymous union stores the bits belonging to DeclContext and classes
1744 /// deriving from it. The goal is to use otherwise wasted
1745 /// space in DeclContext to store data belonging to derived classes.
1746 /// The space saved is especially significient when pointers are aligned
1747 /// to 8 bytes. In this case due to alignment requirements we have a
1748 /// little less than 8 bytes free in DeclContext which we can use.
1749 /// We check that none of the classes in this union is larger than
1750 /// 8 bytes with static_asserts in the ctor of DeclContext.
1751 union {
1752 DeclContextBitfields DeclContextBits;
1753 TagDeclBitfields TagDeclBits;
1754 EnumDeclBitfields EnumDeclBits;
1755 RecordDeclBitfields RecordDeclBits;
1756 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1757 FunctionDeclBitfields FunctionDeclBits;
1758 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1759 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1760 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1761 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1762 BlockDeclBitfields BlockDeclBits;
1763
1764 static_assert(sizeof(DeclContextBitfields) <= 8,
1765 "DeclContextBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(TagDeclBitfields) <= 8,
1767 "TagDeclBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(EnumDeclBitfields) <= 8,
1769 "EnumDeclBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(RecordDeclBitfields) <= 8,
1771 "RecordDeclBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1773 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1775 "FunctionDeclBitfields is larger than 8 bytes!");
1776 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1777 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1778 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1779 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1780 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1781 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1782 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1783 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1784 static_assert(sizeof(BlockDeclBitfields) <= 8,
1785 "BlockDeclBitfields is larger than 8 bytes!");
1786 };
1787
1788 /// FirstDecl - The first declaration stored within this declaration
1789 /// context.
1790 mutable Decl *FirstDecl = nullptr;
1791
1792 /// LastDecl - The last declaration stored within this declaration
1793 /// context. FIXME: We could probably cache this value somewhere
1794 /// outside of the DeclContext, to reduce the size of DeclContext by
1795 /// another pointer.
1796 mutable Decl *LastDecl = nullptr;
1797
1798 /// Build up a chain of declarations.
1799 ///
1800 /// \returns the first/last pair of declarations.
1801 static std::pair<Decl *, Decl *>
1802 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1803
1804 DeclContext(Decl::Kind K);
1805
1806public:
1807 ~DeclContext();
1808
1809 Decl::Kind getDeclKind() const {
1810 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1811 }
1812
1813 const char *getDeclKindName() const;
1814
1815 /// getParent - Returns the containing DeclContext.
1816 DeclContext *getParent() {
1817 return cast<Decl>(this)->getDeclContext();
1818 }
1819 const DeclContext *getParent() const {
1820 return const_cast<DeclContext*>(this)->getParent();
1821 }
1822
1823 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1824 /// different from getParent, e.g.:
1825 ///
1826 /// namespace A {
1827 /// struct S;
1828 /// }
1829 /// struct A::S {}; // getParent() == namespace 'A'
1830 /// // getLexicalParent() == translation unit
1831 ///
1832 DeclContext *getLexicalParent() {
1833 return cast<Decl>(this)->getLexicalDeclContext();
1834 }
1835 const DeclContext *getLexicalParent() const {
1836 return const_cast<DeclContext*>(this)->getLexicalParent();
1837 }
1838
1839 DeclContext *getLookupParent();
1840
1841 const DeclContext *getLookupParent() const {
1842 return const_cast<DeclContext*>(this)->getLookupParent();
1843 }
1844
1845 ASTContext &getParentASTContext() const {
1846 return cast<Decl>(this)->getASTContext();
1847 }
1848
1849 bool isClosure() const { return getDeclKind() == Decl::Block; }
1850
1851 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1852 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1853 const BlockDecl *getInnermostBlockDecl() const;
1854
1855 bool isObjCContainer() const {
1856 switch (getDeclKind()) {
1857 case Decl::ObjCCategory:
1858 case Decl::ObjCCategoryImpl:
1859 case Decl::ObjCImplementation:
1860 case Decl::ObjCInterface:
1861 case Decl::ObjCProtocol:
1862 return true;
1863 default:
1864 return false;
1865 }
1866 }
1867
1868 bool isFunctionOrMethod() const {
1869 switch (getDeclKind()) {
1870 case Decl::Block:
1871 case Decl::Captured:
1872 case Decl::ObjCMethod:
1873 return true;
1874 default:
1875 return getDeclKind() >= Decl::firstFunction &&
1876 getDeclKind() <= Decl::lastFunction;
1877 }
1878 }
1879
1880 /// Test whether the context supports looking up names.
1881 bool isLookupContext() const {
1882 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1883 getDeclKind() != Decl::Export;
1884 }
1885
1886 bool isFileContext() const {
1887 return getDeclKind() == Decl::TranslationUnit ||
1888 getDeclKind() == Decl::Namespace;
1889 }
1890
1891 bool isTranslationUnit() const {
1892 return getDeclKind() == Decl::TranslationUnit;
1893 }
1894
1895 bool isRecord() const {
1896 return getDeclKind() >= Decl::firstRecord &&
1897 getDeclKind() <= Decl::lastRecord;
1898 }
1899
1900 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1901
1902 bool isStdNamespace() const;
1903
1904 bool isInlineNamespace() const;
1905
1906 /// Determines whether this context is dependent on a
1907 /// template parameter.
1908 bool isDependentContext() const;
1909
1910 /// isTransparentContext - Determines whether this context is a
1911 /// "transparent" context, meaning that the members declared in this
1912 /// context are semantically declared in the nearest enclosing
1913 /// non-transparent (opaque) context but are lexically declared in
1914 /// this context. For example, consider the enumerators of an
1915 /// enumeration type:
1916 /// @code
1917 /// enum E {
1918 /// Val1
1919 /// };
1920 /// @endcode
1921 /// Here, E is a transparent context, so its enumerator (Val1) will
1922 /// appear (semantically) that it is in the same context of E.
1923 /// Examples of transparent contexts include: enumerations (except for
1924 /// C++0x scoped enums), and C++ linkage specifications.
1925 bool isTransparentContext() const;
1926
1927 /// Determines whether this context or some of its ancestors is a
1928 /// linkage specification context that specifies C linkage.
1929 bool isExternCContext() const;
1930
1931 /// Retrieve the nearest enclosing C linkage specification context.
1932 const LinkageSpecDecl *getExternCContext() const;
1933
1934 /// Determines whether this context or some of its ancestors is a
1935 /// linkage specification context that specifies C++ linkage.
1936 bool isExternCXXContext() const;
1937
1938 /// Determine whether this declaration context is equivalent
1939 /// to the declaration context DC.
1940 bool Equals(const DeclContext *DC) const {
1941 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1942 }
1943
1944 /// Determine whether this declaration context encloses the
1945 /// declaration context DC.
1946 bool Encloses(const DeclContext *DC) const;
1947
1948 /// Find the nearest non-closure ancestor of this context,
1949 /// i.e. the innermost semantic parent of this context which is not
1950 /// a closure. A context may be its own non-closure ancestor.
1951 Decl *getNonClosureAncestor();
1952 const Decl *getNonClosureAncestor() const {
1953 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1954 }
1955
1956 /// getPrimaryContext - There may be many different
1957 /// declarations of the same entity (including forward declarations
1958 /// of classes, multiple definitions of namespaces, etc.), each with
1959 /// a different set of declarations. This routine returns the
1960 /// "primary" DeclContext structure, which will contain the
1961 /// information needed to perform name lookup into this context.
1962 DeclContext *getPrimaryContext();
1963 const DeclContext *getPrimaryContext() const {
1964 return const_cast<DeclContext*>(this)->getPrimaryContext();
1965 }
1966
1967 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1968 /// other entities of the same name, or where it is a redeclaration if the
1969 /// two entities are compatible. This skips through transparent contexts.
1970 DeclContext *getRedeclContext();
1971 const DeclContext *getRedeclContext() const {
1972 return const_cast<DeclContext *>(this)->getRedeclContext();
1973 }
1974
1975 /// Retrieve the nearest enclosing namespace context.
1976 DeclContext *getEnclosingNamespaceContext();
1977 const DeclContext *getEnclosingNamespaceContext() const {
1978 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1979 }
1980
1981 /// Retrieve the outermost lexically enclosing record context.
1982 RecordDecl *getOuterLexicalRecordContext();
1983 const RecordDecl *getOuterLexicalRecordContext() const {
1984 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1985 }
1986
1987 /// Test if this context is part of the enclosing namespace set of
1988 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1989 /// isn't a namespace, this is equivalent to Equals().
1990 ///
1991 /// The enclosing namespace set of a namespace is the namespace and, if it is
1992 /// inline, its enclosing namespace, recursively.
1993 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1994
1995 /// Collects all of the declaration contexts that are semantically
1996 /// connected to this declaration context.
1997 ///
1998 /// For declaration contexts that have multiple semantically connected but
1999 /// syntactically distinct contexts, such as C++ namespaces, this routine
2000 /// retrieves the complete set of such declaration contexts in source order.
2001 /// For example, given:
2002 ///
2003 /// \code
2004 /// namespace N {
2005 /// int x;
2006 /// }
2007 /// namespace N {
2008 /// int y;
2009 /// }
2010 /// \endcode
2011 ///
2012 /// The \c Contexts parameter will contain both definitions of N.
2013 ///
2014 /// \param Contexts Will be cleared and set to the set of declaration
2015 /// contexts that are semanticaly connected to this declaration context,
2016 /// in source order, including this context (which may be the only result,
2017 /// for non-namespace contexts).
2018 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2019
2020 /// decl_iterator - Iterates through the declarations stored
2021 /// within this context.
2022 class decl_iterator {
2023 /// Current - The current declaration.
2024 Decl *Current = nullptr;
2025
2026 public:
2027 using value_type = Decl *;
2028 using reference = const value_type &;
2029 using pointer = const value_type *;
2030 using iterator_category = std::forward_iterator_tag;
2031 using difference_type = std::ptrdiff_t;
2032
2033 decl_iterator() = default;
2034 explicit decl_iterator(Decl *C) : Current(C) {}
2035
2036 reference operator*() const { return Current; }
2037
2038 // This doesn't meet the iterator requirements, but it's convenient
2039 value_type operator->() const { return Current; }
2040
2041 decl_iterator& operator++() {
2042 Current = Current->getNextDeclInContext();
2043 return *this;
2044 }
2045
2046 decl_iterator operator++(int) {
2047 decl_iterator tmp(*this);
2048 ++(*this);
2049 return tmp;
2050 }
2051
2052 friend bool operator==(decl_iterator x, decl_iterator y) {
2053 return x.Current == y.Current;
2054 }
2055
2056 friend bool operator!=(decl_iterator x, decl_iterator y) {
2057 return x.Current != y.Current;
2058 }
2059 };
2060
2061 using decl_range = llvm::iterator_range<decl_iterator>;
2062
2063 /// decls_begin/decls_end - Iterate over the declarations stored in
2064 /// this context.
2065 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2066 decl_iterator decls_begin() const;
2067 decl_iterator decls_end() const { return decl_iterator(); }
2068 bool decls_empty() const;
2069
2070 /// noload_decls_begin/end - Iterate over the declarations stored in this
2071 /// context that are currently loaded; don't attempt to retrieve anything
2072 /// from an external source.
2073 decl_range noload_decls() const {
2074 return decl_range(noload_decls_begin(), noload_decls_end());
2075 }
2076 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2077 decl_iterator noload_decls_end() const { return decl_iterator(); }
2078
2079 /// specific_decl_iterator - Iterates over a subrange of
2080 /// declarations stored in a DeclContext, providing only those that
2081 /// are of type SpecificDecl (or a class derived from it). This
2082 /// iterator is used, for example, to provide iteration over just
2083 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2084 template<typename SpecificDecl>
2085 class specific_decl_iterator {
2086 /// Current - The current, underlying declaration iterator, which
2087 /// will either be NULL or will point to a declaration of
2088 /// type SpecificDecl.
2089 DeclContext::decl_iterator Current;
2090
2091 /// SkipToNextDecl - Advances the current position up to the next
2092 /// declaration of type SpecificDecl that also meets the criteria
2093 /// required by Acceptable.
2094 void SkipToNextDecl() {
2095 while (*Current && !isa<SpecificDecl>(*Current))
2096 ++Current;
2097 }
2098
2099 public:
2100 using value_type = SpecificDecl *;
2101 // TODO: Add reference and pointer types (with some appropriate proxy type)
2102 // if we ever have a need for them.
2103 using reference = void;
2104 using pointer = void;
2105 using difference_type =
2106 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2107 using iterator_category = std::forward_iterator_tag;
2108
2109 specific_decl_iterator() = default;
2110
2111 /// specific_decl_iterator - Construct a new iterator over a
2112 /// subset of the declarations the range [C,
2113 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2114 /// member function of SpecificDecl that should return true for
2115 /// all of the SpecificDecl instances that will be in the subset
2116 /// of iterators. For example, if you want Objective-C instance
2117 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2118 /// &ObjCMethodDecl::isInstanceMethod.
2119 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2120 SkipToNextDecl();
2121 }
2122
2123 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2124
2125 // This doesn't meet the iterator requirements, but it's convenient
2126 value_type operator->() const { return **this; }
2127
2128 specific_decl_iterator& operator++() {
2129 ++Current;
2130 SkipToNextDecl();
2131 return *this;
2132 }
2133
2134 specific_decl_iterator operator++(int) {
2135 specific_decl_iterator tmp(*this);
2136 ++(*this);
2137 return tmp;
2138 }
2139
2140 friend bool operator==(const specific_decl_iterator& x,
2141 const specific_decl_iterator& y) {
2142 return x.Current == y.Current;
2143 }
2144
2145 friend bool operator!=(const specific_decl_iterator& x,
2146 const specific_decl_iterator& y) {
2147 return x.Current != y.Current;
2148 }
2149 };
2150
2151 /// Iterates over a filtered subrange of declarations stored
2152 /// in a DeclContext.
2153 ///
2154 /// This iterator visits only those declarations that are of type
2155 /// SpecificDecl (or a class derived from it) and that meet some
2156 /// additional run-time criteria. This iterator is used, for
2157 /// example, to provide access to the instance methods within an
2158 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2159 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2160 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2161 class filtered_decl_iterator {
2162 /// Current - The current, underlying declaration iterator, which
2163 /// will either be NULL or will point to a declaration of
2164 /// type SpecificDecl.
2165 DeclContext::decl_iterator Current;
2166
2167 /// SkipToNextDecl - Advances the current position up to the next
2168 /// declaration of type SpecificDecl that also meets the criteria
2169 /// required by Acceptable.
2170 void SkipToNextDecl() {
2171 while (*Current &&
2172 (!isa<SpecificDecl>(*Current) ||
2173 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2174 ++Current;
2175 }
2176
2177 public:
2178 using value_type = SpecificDecl *;
2179 // TODO: Add reference and pointer types (with some appropriate proxy type)
2180 // if we ever have a need for them.
2181 using reference = void;
2182 using pointer = void;
2183 using difference_type =
2184 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2185 using iterator_category = std::forward_iterator_tag;
2186
2187 filtered_decl_iterator() = default;
2188
2189 /// filtered_decl_iterator - Construct a new iterator over a
2190 /// subset of the declarations the range [C,
2191 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2192 /// member function of SpecificDecl that should return true for
2193 /// all of the SpecificDecl instances that will be in the subset
2194 /// of iterators. For example, if you want Objective-C instance
2195 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2196 /// &ObjCMethodDecl::isInstanceMethod.
2197 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2198 SkipToNextDecl();
2199 }
2200
2201 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2202 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2203
2204 filtered_decl_iterator& operator++() {
2205 ++Current;
2206 SkipToNextDecl();
2207 return *this;
2208 }
2209
2210 filtered_decl_iterator operator++(int) {
2211 filtered_decl_iterator tmp(*this);
2212 ++(*this);
2213 return tmp;
2214 }
2215
2216 friend bool operator==(const filtered_decl_iterator& x,
2217 const filtered_decl_iterator& y) {
2218 return x.Current == y.Current;
2219 }
2220
2221 friend bool operator!=(const filtered_decl_iterator& x,
2222 const filtered_decl_iterator& y) {
2223 return x.Current != y.Current;
2224 }
2225 };
2226
2227 /// Add the declaration D into this context.
2228 ///
2229 /// This routine should be invoked when the declaration D has first
2230 /// been declared, to place D into the context where it was
2231 /// (lexically) defined. Every declaration must be added to one
2232 /// (and only one!) context, where it can be visited via
2233 /// [decls_begin(), decls_end()). Once a declaration has been added
2234 /// to its lexical context, the corresponding DeclContext owns the
2235 /// declaration.
2236 ///
2237 /// If D is also a NamedDecl, it will be made visible within its
2238 /// semantic context via makeDeclVisibleInContext.
2239 void addDecl(Decl *D);
2240
2241 /// Add the declaration D into this context, but suppress
2242 /// searches for external declarations with the same name.
2243 ///
2244 /// Although analogous in function to addDecl, this removes an
2245 /// important check. This is only useful if the Decl is being
2246 /// added in response to an external search; in all other cases,
2247 /// addDecl() is the right function to use.
2248 /// See the ASTImporter for use cases.
2249 void addDeclInternal(Decl *D);
2250
2251 /// Add the declaration D to this context without modifying
2252 /// any lookup tables.
2253 ///
2254 /// This is useful for some operations in dependent contexts where
2255 /// the semantic context might not be dependent; this basically
2256 /// only happens with friends.
2257 void addHiddenDecl(Decl *D);
2258
2259 /// Removes a declaration from this context.
2260 void removeDecl(Decl *D);
2261
2262 /// Checks whether a declaration is in this context.
2263 bool containsDecl(Decl *D) const;
2264
2265 /// Checks whether a declaration is in this context.
2266 /// This also loads the Decls from the external source before the check.
2267 bool containsDeclAndLoad(Decl *D) const;
2268
2269 using lookup_result = DeclContextLookupResult;
2270 using lookup_iterator = lookup_result::iterator;
2271
2272 /// lookup - Find the declarations (if any) with the given Name in
2273 /// this context. Returns a range of iterators that contains all of
2274 /// the declarations with this name, with object, function, member,
2275 /// and enumerator names preceding any tag name. Note that this
2276 /// routine will not look into parent contexts.
2277 lookup_result lookup(DeclarationName Name) const;
2278
2279 /// Find the declarations with the given name that are visible
2280 /// within this context; don't attempt to retrieve anything from an
2281 /// external source.
2282 lookup_result noload_lookup(DeclarationName Name);
2283
2284 /// A simplistic name lookup mechanism that performs name lookup
2285 /// into this declaration context without consulting the external source.
2286 ///
2287 /// This function should almost never be used, because it subverts the
2288 /// usual relationship between a DeclContext and the external source.
2289 /// See the ASTImporter for the (few, but important) use cases.
2290 ///
2291 /// FIXME: This is very inefficient; replace uses of it with uses of
2292 /// noload_lookup.
2293 void localUncachedLookup(DeclarationName Name,
2294 SmallVectorImpl<NamedDecl *> &Results);
2295
2296 /// Makes a declaration visible within this context.
2297 ///
2298 /// This routine makes the declaration D visible to name lookup
2299 /// within this context and, if this is a transparent context,
2300 /// within its parent contexts up to the first enclosing
2301 /// non-transparent context. Making a declaration visible within a
2302 /// context does not transfer ownership of a declaration, and a
2303 /// declaration can be visible in many contexts that aren't its
2304 /// lexical context.
2305 ///
2306 /// If D is a redeclaration of an existing declaration that is
2307 /// visible from this context, as determined by
2308 /// NamedDecl::declarationReplaces, the previous declaration will be
2309 /// replaced with D.
2310 void makeDeclVisibleInContext(NamedDecl *D);
2311
2312 /// all_lookups_iterator - An iterator that provides a view over the results
2313 /// of looking up every possible name.
2314 class all_lookups_iterator;
2315
2316 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2317
2318 lookups_range lookups() const;
2319 // Like lookups(), but avoids loading external declarations.
2320 // If PreserveInternalState, avoids building lookup data structures too.
2321 lookups_range noload_lookups(bool PreserveInternalState) const;
2322
2323 /// Iterators over all possible lookups within this context.
2324 all_lookups_iterator lookups_begin() const;
2325 all_lookups_iterator lookups_end() const;
2326
2327 /// Iterators over all possible lookups within this context that are
2328 /// currently loaded; don't attempt to retrieve anything from an external
2329 /// source.
2330 all_lookups_iterator noload_lookups_begin() const;
2331 all_lookups_iterator noload_lookups_end() const;
2332
2333 struct udir_iterator;
2334
2335 using udir_iterator_base =
2336 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2337 std::random_access_iterator_tag,
2338 UsingDirectiveDecl *>;
2339
2340 struct udir_iterator : udir_iterator_base {
2341 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2342
2343 UsingDirectiveDecl *operator*() const;
2344 };
2345
2346 using udir_range = llvm::iterator_range<udir_iterator>;
2347
2348 udir_range using_directives() const;
2349
2350 // These are all defined in DependentDiagnostic.h.
2351 class ddiag_iterator;
2352
2353 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2354
2355 inline ddiag_range ddiags() const;
2356
2357 // Low-level accessors
2358
2359 /// Mark that there are external lexical declarations that we need
2360 /// to include in our lookup table (and that are not available as external
2361 /// visible lookups). These extra lookup results will be found by walking
2362 /// the lexical declarations of this context. This should be used only if
2363 /// setHasExternalLexicalStorage() has been called on any decl context for
2364 /// which this is the primary context.
2365 void setMustBuildLookupTable() {
2366 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-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h"
, 2367, __PRETTY_FUNCTION__))
2367 "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-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h"
, 2367, __PRETTY_FUNCTION__))
;
2368 DeclContextBits.HasLazyExternalLexicalLookups = true;
2369 }
2370
2371 /// Retrieve the internal representation of the lookup structure.
2372 /// This may omit some names if we are lazily building the structure.
2373 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2374
2375 /// Ensure the lookup structure is fully-built and return it.
2376 StoredDeclsMap *buildLookup();
2377
2378 /// Whether this DeclContext has external storage containing
2379 /// additional declarations that are lexically in this context.
2380 bool hasExternalLexicalStorage() const {
2381 return DeclContextBits.ExternalLexicalStorage;
2382 }
2383
2384 /// State whether this DeclContext has external storage for
2385 /// declarations lexically in this context.
2386 void setHasExternalLexicalStorage(bool ES = true) const {
2387 DeclContextBits.ExternalLexicalStorage = ES;
2388 }
2389
2390 /// Whether this DeclContext has external storage containing
2391 /// additional declarations that are visible in this context.
2392 bool hasExternalVisibleStorage() const {
2393 return DeclContextBits.ExternalVisibleStorage;
2394 }
2395
2396 /// State whether this DeclContext has external storage for
2397 /// declarations visible in this context.
2398 void setHasExternalVisibleStorage(bool ES = true) const {
2399 DeclContextBits.ExternalVisibleStorage = ES;
2400 if (ES && LookupPtr)
2401 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2402 }
2403
2404 /// Determine whether the given declaration is stored in the list of
2405 /// declarations lexically within this context.
2406 bool isDeclInLexicalTraversal(const Decl *D) const {
2407 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2408 D == LastDecl);
2409 }
2410
2411 bool setUseQualifiedLookup(bool use = true) const {
2412 bool old_value = DeclContextBits.UseQualifiedLookup;
2413 DeclContextBits.UseQualifiedLookup = use;
2414 return old_value;
2415 }
2416
2417 bool shouldUseQualifiedLookup() const {
2418 return DeclContextBits.UseQualifiedLookup;
2419 }
2420
2421 static bool classof(const Decl *D);
2422 static bool classof(const DeclContext *D) { return true; }
2423
2424 void dumpDeclContext() const;
2425 void dumpLookups() const;
2426 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2427 bool Deserialize = false) const;
2428
2429private:
2430 /// Whether this declaration context has had externally visible
2431 /// storage added since the last lookup. In this case, \c LookupPtr's
2432 /// invariant may not hold and needs to be fixed before we perform
2433 /// another lookup.
2434 bool hasNeedToReconcileExternalVisibleStorage() const {
2435 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2436 }
2437
2438 /// State that this declaration context has had externally visible
2439 /// storage added since the last lookup. In this case, \c LookupPtr's
2440 /// invariant may not hold and needs to be fixed before we perform
2441 /// another lookup.
2442 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2443 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2444 }
2445
2446 /// If \c true, this context may have local lexical declarations
2447 /// that are missing from the lookup table.
2448 bool hasLazyLocalLexicalLookups() const {
2449 return DeclContextBits.HasLazyLocalLexicalLookups;
2450 }
2451
2452 /// If \c true, this context may have local lexical declarations
2453 /// that are missing from the lookup table.
2454 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2455 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2456 }
2457
2458 /// If \c true, the external source may have lexical declarations
2459 /// that are missing from the lookup table.
2460 bool hasLazyExternalLexicalLookups() const {
2461 return DeclContextBits.HasLazyExternalLexicalLookups;
2462 }
2463
2464 /// If \c true, the external source may have lexical declarations
2465 /// that are missing from the lookup table.
2466 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2467 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2468 }
2469
2470 void reconcileExternalVisibleStorage() const;
2471 bool LoadLexicalDeclsFromExternalStorage() const;
2472
2473 /// Makes a declaration visible within this context, but
2474 /// suppresses searches for external declarations with the same
2475 /// name.
2476 ///
2477 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2478 /// use of addDeclInternal().
2479 void makeDeclVisibleInContextInternal(NamedDecl *D);
2480
2481 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2482
2483 void loadLazyLocalLexicalLookups();
2484 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2485 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2486 bool Rediscoverable);
2487 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2488};
2489
2490inline bool Decl::isTemplateParameter() const {
2491 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2492 getKind() == TemplateTemplateParm;
2493}
2494
2495// Specialization selected when ToTy is not a known subclass of DeclContext.
2496template <class ToTy,
2497 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2498struct cast_convert_decl_context {
2499 static const ToTy *doit(const DeclContext *Val) {
2500 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2501 }
2502
2503 static ToTy *doit(DeclContext *Val) {
2504 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2505 }
2506};
2507
2508// Specialization selected when ToTy is a known subclass of DeclContext.
2509template <class ToTy>
2510struct cast_convert_decl_context<ToTy, true> {
2511 static const ToTy *doit(const DeclContext *Val) {
2512 return static_cast<const ToTy*>(Val);
2513 }
2514
2515 static ToTy *doit(DeclContext *Val) {
2516 return static_cast<ToTy*>(Val);
2517 }
2518};
2519
2520} // namespace clang
2521
2522namespace llvm {
2523
2524/// isa<T>(DeclContext*)
2525template <typename To>
2526struct isa_impl<To, ::clang::DeclContext> {
2527 static bool doit(const ::clang::DeclContext &Val) {
2528 return To::classofKind(Val.getDeclKind());
2529 }
2530};
2531
2532/// cast<T>(DeclContext*)
2533template<class ToTy>
2534struct cast_convert_val<ToTy,
2535 const ::clang::DeclContext,const ::clang::DeclContext> {
2536 static const ToTy &doit(const ::clang::DeclContext &Val) {
2537 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2538 }
2539};
2540
2541template<class ToTy>
2542struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2543 static ToTy &doit(::clang::DeclContext &Val) {
2544 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2545 }
2546};
2547
2548template<class ToTy>
2549struct cast_convert_val<ToTy,
2550 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2551 static const ToTy *doit(const ::clang::DeclContext *Val) {
2552 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2553 }
2554};
2555
2556template<class ToTy>
2557struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2558 static ToTy *doit(::clang::DeclContext *Val) {
2559 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2560 }
2561};
2562
2563/// Implement cast_convert_val for Decl -> DeclContext conversions.
2564template<class FromTy>
2565struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2566 static ::clang::DeclContext &doit(const FromTy &Val) {
2567 return *FromTy::castToDeclContext(&Val);
2568 }
2569};
2570
2571template<class FromTy>
2572struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2573 static ::clang::DeclContext *doit(const FromTy *Val) {
2574 return FromTy::castToDeclContext(Val);
2575 }
2576};
2577
2578template<class FromTy>
2579struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2580 static const ::clang::DeclContext &doit(const FromTy &Val) {
2581 return *FromTy::castToDeclContext(&Val);
2582 }
2583};
2584
2585template<class FromTy>
2586struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2587 static const ::clang::DeclContext *doit(const FromTy *Val) {
2588 return FromTy::castToDeclContext(Val);
2589 }
2590};
2591
2592} // namespace llvm
2593
2594#endif // LLVM_CLANG_AST_DECLBASE_H