Bug Summary

File:clang/lib/CodeGen/CodeGenModule.cpp
Warning:line 376, column 53
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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