Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CodeGenModule.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/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~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/CodeGen/CodeGenModule.cpp

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