Bug Summary

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