Bug Summary

File:clang/lib/CodeGen/CodeGenModule.cpp
Warning:line 3486, column 27
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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/tools/clang/lib/CodeGen -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/clang/include -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-03-08-182450-10039-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/clang/lib/CodeGen/CodeGenModule.cpp

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