Debian Codegraph @

clang/lib/CodeGen/CodeGenModule.cpp

raw
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/ASTLambda.h"
32 #include "clang/AST/CharUnits.h"
33 #include "clang/AST/Decl.h"
34 #include "clang/AST/DeclCXX.h"
35 #include "clang/AST/DeclObjC.h"
36 #include "clang/AST/DeclTemplate.h"
37 #include "clang/AST/Mangle.h"
38 #include "clang/AST/RecursiveASTVisitor.h"
39 #include "clang/AST/StmtVisitor.h"
40 #include "clang/Basic/Builtins.h"
41 #include "clang/Basic/CodeGenOptions.h"
42 #include "clang/Basic/Diagnostic.h"
43 #include "clang/Basic/DiagnosticFrontend.h"
44 #include "clang/Basic/Module.h"
45 #include "clang/Basic/SourceManager.h"
46 #include "clang/Basic/TargetInfo.h"
47 #include "clang/Basic/Version.h"
48 #include "clang/CodeGen/BackendUtil.h"
49 #include "clang/CodeGen/ConstantInitBuilder.h"
50 #include "llvm/ADT/STLExtras.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSwitch.h"
53 #include "llvm/Analysis/TargetLibraryInfo.h"
54 #include "llvm/BinaryFormat/ELF.h"
55 #include "llvm/IR/AttributeMask.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/Hash.h"
70 #include "llvm/Support/TimeProfiler.h"
71 #include "llvm/TargetParser/AArch64TargetParser.h"
72 #include "llvm/TargetParser/RISCVISAInfo.h"
73 #include "llvm/TargetParser/Triple.h"
74 #include "llvm/TargetParser/X86TargetParser.h"
75 #include "llvm/Transforms/Instrumentation/KCFI.h"
76 #include "llvm/Transforms/Utils/BuildLibCalls.h"
77 #include <optional>
78 #include <set>
79
80 using namespace clang;
81 using namespace CodeGen;
82
83 static llvm::cl::opt<bool> LimitedCoverage(
84 "limited-coverage-experimental", llvm::cl::Hidden,
85 llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
86
87 static const char AnnotationSection[] = "llvm.metadata";
88 static constexpr auto ErrnoTBAAMDName = "llvm.errno.tbaa";
89
90 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
91 switch (CGM.getContext().getCXXABIKind()) {
92 case TargetCXXABI::AppleARM64:
93 case TargetCXXABI::Fuchsia:
94 case TargetCXXABI::GenericAArch64:
95 case TargetCXXABI::GenericARM:
96 case TargetCXXABI::iOS:
97 case TargetCXXABI::WatchOS:
98 case TargetCXXABI::GenericMIPS:
99 case TargetCXXABI::GenericItanium:
100 case TargetCXXABI::WebAssembly:
101 case TargetCXXABI::XL:
102 return CreateItaniumCXXABI(CGM);
103 case TargetCXXABI::Microsoft:
104 return CreateMicrosoftCXXABI(CGM);
105 }
106
107 llvm_unreachable("invalid C++ ABI kind");
108 }
109
110 static std::unique_ptr<TargetCodeGenInfo>
111 createTargetCodeGenInfo(CodeGenModule &CGM) {
112 const TargetInfo &Target = CGM.getTarget();
113 const llvm::Triple &Triple = Target.getTriple();
114 const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
115
116 switch (Triple.getArch()) {
117 default:
118 return createDefaultTargetCodeGenInfo(CGM);
119
120 case llvm::Triple::m68k:
121 return createM68kTargetCodeGenInfo(CGM);
122 case llvm::Triple::mips:
123 case llvm::Triple::mipsel:
124 if (Triple.getOS() == llvm::Triple::Win32)
125 return createWindowsMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true);
126 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true);
127
128 case llvm::Triple::mips64:
129 case llvm::Triple::mips64el:
130 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false);
131
132 case llvm::Triple::avr: {
133 // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
134 // on avrtiny. For passing return value, R18~R25 are used on avr, and
135 // R22~R25 are used on avrtiny.
136 unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18;
137 unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8;
138 return createAVRTargetCodeGenInfo(CGM, NPR, NRR);
139 }
140
141 case llvm::Triple::aarch64:
142 case llvm::Triple::aarch64_32:
143 case llvm::Triple::aarch64_be: {
144 AArch64ABIKind Kind = AArch64ABIKind::AAPCS;
145 if (Target.getABI() == "darwinpcs")
146 Kind = AArch64ABIKind::DarwinPCS;
147 else if (Triple.isOSWindows())
148 return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64);
149 else if (Target.getABI() == "aapcs-soft")
150 Kind = AArch64ABIKind::AAPCSSoft;
151
152 return createAArch64TargetCodeGenInfo(CGM, Kind);
153 }
154
155 case llvm::Triple::wasm32:
156 case llvm::Triple::wasm64: {
157 WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP;
158 if (Target.getABI() == "experimental-mv")
159 Kind = WebAssemblyABIKind::ExperimentalMV;
160 return createWebAssemblyTargetCodeGenInfo(CGM, Kind);
161 }
162
163 case llvm::Triple::arm:
164 case llvm::Triple::armeb:
165 case llvm::Triple::thumb:
166 case llvm::Triple::thumbeb: {
167 if (Triple.getOS() == llvm::Triple::Win32)
168 return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP);
169
170 ARMABIKind Kind = ARMABIKind::AAPCS;
171 StringRef ABIStr = Target.getABI();
172 if (ABIStr == "apcs-gnu")
173 Kind = ARMABIKind::APCS;
174 else if (ABIStr == "aapcs16")
175 Kind = ARMABIKind::AAPCS16_VFP;
176 else if (CodeGenOpts.FloatABI == "hard" ||
177 (CodeGenOpts.FloatABI != "soft" && Triple.isHardFloatABI()))
178 Kind = ARMABIKind::AAPCS_VFP;
179
180 return createARMTargetCodeGenInfo(CGM, Kind);
181 }
182
183 case llvm::Triple::ppc: {
184 if (Triple.isOSAIX())
185 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false);
186
187 bool IsSoftFloat =
188 CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe");
189 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
190 }
191 case llvm::Triple::ppcle: {
192 bool IsSoftFloat =
193 CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe");
194 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
195 }
196 case llvm::Triple::ppc64:
197 if (Triple.isOSAIX())
198 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true);
199
200 if (Triple.isOSBinFormatELF()) {
201 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1;
202 if (Target.getABI() == "elfv2")
203 Kind = PPC64_SVR4_ABIKind::ELFv2;
204 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
205
206 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
207 }
208 return createPPC64TargetCodeGenInfo(CGM);
209 case llvm::Triple::ppc64le: {
210 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
211 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2;
212 if (Target.getABI() == "elfv1")
213 Kind = PPC64_SVR4_ABIKind::ELFv1;
214 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
215
216 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
217 }
218
219 case llvm::Triple::nvptx:
220 case llvm::Triple::nvptx64:
221 return createNVPTXTargetCodeGenInfo(CGM);
222
223 case llvm::Triple::msp430:
224 return createMSP430TargetCodeGenInfo(CGM);
225
226 case llvm::Triple::riscv32:
227 case llvm::Triple::riscv64: {
228 StringRef ABIStr = Target.getABI();
229 unsigned XLen = Target.getPointerWidth(LangAS::Default);
230 unsigned ABIFLen = 0;
231 if (ABIStr.ends_with("f"))
232 ABIFLen = 32;
233 else if (ABIStr.ends_with("d"))
234 ABIFLen = 64;
235 bool EABI = ABIStr.ends_with("e");
236 return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen, EABI);
237 }
238
239 case llvm::Triple::systemz: {
240 bool SoftFloat = CodeGenOpts.FloatABI == "soft";
241 bool HasVector = !SoftFloat && Target.getABI() == "vector";
242 return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
243 }
244
245 case llvm::Triple::tce:
246 case llvm::Triple::tcele:
247 return createTCETargetCodeGenInfo(CGM);
248
249 case llvm::Triple::x86: {
250 bool IsDarwinVectorABI = Triple.isOSDarwin();
251 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
252
253 if (Triple.getOS() == llvm::Triple::Win32) {
254 return createWinX86_32TargetCodeGenInfo(
255 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
256 CodeGenOpts.NumRegisterParameters);
257 }
258 return createX86_32TargetCodeGenInfo(
259 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
260 CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft");
261 }
262
263 case llvm::Triple::x86_64: {
264 StringRef ABI = Target.getABI();
265 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512
266 : ABI == "avx" ? X86AVXABILevel::AVX
267 : X86AVXABILevel::None);
268
269 switch (Triple.getOS()) {
270 case llvm::Triple::UEFI:
271 case llvm::Triple::Win32:
272 return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel);
273 default:
274 return createX86_64TargetCodeGenInfo(CGM, AVXLevel);
275 }
276 }
277 case llvm::Triple::hexagon:
278 return createHexagonTargetCodeGenInfo(CGM);
279 case llvm::Triple::lanai:
280 return createLanaiTargetCodeGenInfo(CGM);
281 case llvm::Triple::r600:
282 return createAMDGPUTargetCodeGenInfo(CGM);
283 case llvm::Triple::amdgcn:
284 return createAMDGPUTargetCodeGenInfo(CGM);
285 case llvm::Triple::sparc:
286 return createSparcV8TargetCodeGenInfo(CGM);
287 case llvm::Triple::sparcv9:
288 return createSparcV9TargetCodeGenInfo(CGM);
289 case llvm::Triple::xcore:
290 return createXCoreTargetCodeGenInfo(CGM);
291 case llvm::Triple::arc:
292 return createARCTargetCodeGenInfo(CGM);
293 case llvm::Triple::spir:
294 case llvm::Triple::spir64:
295 return createCommonSPIRTargetCodeGenInfo(CGM);
296 case llvm::Triple::spirv32:
297 case llvm::Triple::spirv64:
298 case llvm::Triple::spirv:
299 return createSPIRVTargetCodeGenInfo(CGM);
300 case llvm::Triple::dxil:
301 return createDirectXTargetCodeGenInfo(CGM);
302 case llvm::Triple::ve:
303 return createVETargetCodeGenInfo(CGM);
304 case llvm::Triple::csky: {
305 bool IsSoftFloat = !Target.hasFeature("hard-float-abi");
306 bool hasFP64 =
307 Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df");
308 return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0
309 : hasFP64 ? 64
310 : 32);
311 }
312 case llvm::Triple::bpfeb:
313 case llvm::Triple::bpfel:
314 return createBPFTargetCodeGenInfo(CGM);
315 case llvm::Triple::loongarch32:
316 case llvm::Triple::loongarch64: {
317 StringRef ABIStr = Target.getABI();
318 unsigned ABIFRLen = 0;
319 if (ABIStr.ends_with("f"))
320 ABIFRLen = 32;
321 else if (ABIStr.ends_with("d"))
322 ABIFRLen = 64;
323 return createLoongArchTargetCodeGenInfo(
324 CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen);
325 }
326 }
327 }
328
329 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
330 if (!TheTargetCodeGenInfo)
331 TheTargetCodeGenInfo = createTargetCodeGenInfo(*this);
332 return *TheTargetCodeGenInfo;
333 }
334
335 static void checkDataLayoutConsistency(const TargetInfo &Target,
336 llvm::LLVMContext &Context,
337 const LangOptions &Opts) {
338 #ifndef NDEBUG
339 // Don't verify non-standard ABI configurations.
340 if (Opts.AlignDouble || Opts.OpenCL || Opts.HLSL)
341 return;
342
343 llvm::Triple Triple = Target.getTriple();
344 llvm::DataLayout DL(Target.getDataLayoutString());
345 auto Check = [&](const char *Name, llvm::Type *Ty, unsigned Alignment) {
346 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
347 llvm::Align ClangAlign(Alignment / 8);
348 if (DLAlign != ClangAlign) {
349 llvm::errs() << "For target " << Triple.str() << " type " << Name
350 << " mapping to " << *Ty << " has data layout alignment "
351 << DLAlign.value() << " while clang specifies "
352 << ClangAlign.value() << "\n";
353 abort();
354 }
355 };
356
357 Check("bool", llvm::Type::getIntNTy(Context, Target.BoolWidth),
358 Target.BoolAlign);
359 Check("short", llvm::Type::getIntNTy(Context, Target.ShortWidth),
360 Target.ShortAlign);
361 Check("int", llvm::Type::getIntNTy(Context, Target.IntWidth),
362 Target.IntAlign);
363 Check("long", llvm::Type::getIntNTy(Context, Target.LongWidth),
364 Target.LongAlign);
365 // FIXME: M68k specifies incorrect long long alignment in both LLVM and Clang.
366 if (Triple.getArch() != llvm::Triple::m68k)
367 Check("long long", llvm::Type::getIntNTy(Context, Target.LongLongWidth),
368 Target.LongLongAlign);
369 // FIXME: There are int128 alignment mismatches on multiple targets.
370 if (Target.hasInt128Type() && !Target.getTargetOpts().ForceEnableInt128 &&
371 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
372 Triple.getArch() != llvm::Triple::ve)
373 Check("__int128", llvm::Type::getIntNTy(Context, 128), Target.Int128Align);
374
375 if (Target.hasFloat16Type())
376 Check("half", llvm::Type::getFloatingPointTy(Context, *Target.HalfFormat),
377 Target.HalfAlign);
378 if (Target.hasBFloat16Type())
379 Check("bfloat", llvm::Type::getBFloatTy(Context), Target.BFloat16Align);
380 Check("float", llvm::Type::getFloatingPointTy(Context, *Target.FloatFormat),
381 Target.FloatAlign);
382 Check("double", llvm::Type::getFloatingPointTy(Context, *Target.DoubleFormat),
383 Target.DoubleAlign);
384 Check("long double",
385 llvm::Type::getFloatingPointTy(Context, *Target.LongDoubleFormat),
386 Target.LongDoubleAlign);
387 if (Target.hasFloat128Type())
388 Check("__float128", llvm::Type::getFP128Ty(Context), Target.Float128Align);
389 if (Target.hasIbm128Type())
390 Check("__ibm128", llvm::Type::getPPC_FP128Ty(Context), Target.Ibm128Align);
391
392 Check("void*", llvm::PointerType::getUnqual(Context), Target.PointerAlign);
393 #endif
394 }
395
396 CodeGenModule::CodeGenModule(ASTContext &C,
397 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
398 const HeaderSearchOptions &HSO,
399 const PreprocessorOptions &PPO,
400 const CodeGenOptions &CGO, llvm::Module &M,
401 DiagnosticsEngine &diags,
402 CoverageSourceInfo *CoverageInfo)
403 : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
404 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
405 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
406 VMContext(M.getContext()), VTables(*this), StackHandler(diags),
407 SanitizerMD(new SanitizerMetadata(*this)),
408 AtomicOpts(Target.getAtomicOpts()) {
409
410 // Initialize the type cache.
411 Types.reset(new CodeGenTypes(*this));
412 llvm::LLVMContext &LLVMContext = M.getContext();
413 VoidTy = llvm::Type::getVoidTy(LLVMContext);
414 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
415 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
416 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
417 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
418 HalfTy = llvm::Type::getHalfTy(LLVMContext);
419 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
420 FloatTy = llvm::Type::getFloatTy(LLVMContext);
421 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
422 PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
423 PointerAlignInBytes =
424 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
425 .getQuantity();
426 SizeSizeInBytes =
427 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
428 IntAlignInBytes =
429 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
430 CharTy =
431 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
432 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
433 IntPtrTy = llvm::IntegerType::get(LLVMContext,
434 C.getTargetInfo().getMaxPointerWidth());
435 Int8PtrTy = llvm::PointerType::get(LLVMContext,
436 C.getTargetAddressSpace(LangAS::Default));
437 const llvm::DataLayout &DL = M.getDataLayout();
438 AllocaInt8PtrTy =
439 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
440 GlobalsInt8PtrTy =
441 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
442 ConstGlobalsPtrTy = llvm::PointerType::get(
443 LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
444 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
445
446 // Build C++20 Module initializers.
447 // TODO: Add Microsoft here once we know the mangling required for the
448 // initializers.
449 CXX20ModuleInits =
450 LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
451 ItaniumMangleContext::MK_Itanium;
452
453 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
454
455 if (LangOpts.ObjC)
456 createObjCRuntime();
457 if (LangOpts.OpenCL)
458 createOpenCLRuntime();
459 if (LangOpts.OpenMP)
460 createOpenMPRuntime();
461 if (LangOpts.CUDA)
462 createCUDARuntime();
463 if (LangOpts.HLSL)
464 createHLSLRuntime();
465
466 // Enable TBAA unless it's suppressed. TSan and TySan need TBAA even at O0.
467 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
468 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
469 TBAA.reset(new CodeGenTBAA(Context, getTypes(), TheModule, CodeGenOpts,
470 getLangOpts()));
471
472 // If debug info or coverage generation is enabled, create the CGDebugInfo
473 // object.
474 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
475 CodeGenOpts.CoverageNotesFile.size() ||
476 CodeGenOpts.CoverageDataFile.size())
477 DebugInfo.reset(new CGDebugInfo(*this));
478 else if (getTriple().isOSWindows())
479 // On Windows targets, we want to emit compiler info even if debug info is
480 // otherwise disabled. Use a temporary CGDebugInfo instance to emit only
481 // basic compiler metadata.
482 CGDebugInfo(*this);
483
484 Block.GlobalUniqueCount = 0;
485
486 if (C.getLangOpts().ObjC)
487 ObjCData.reset(new ObjCEntrypoints());
488
489 if (CodeGenOpts.hasProfileClangUse()) {
490 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
491 CodeGenOpts.ProfileInstrumentUsePath, *FS,
492 CodeGenOpts.ProfileRemappingFile);
493 if (auto E = ReaderOrErr.takeError()) {
494 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
495 Diags.Report(diag::err_reading_profile)
496 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
497 });
498 return;
499 }
500 PGOReader = std::move(ReaderOrErr.get());
501 }
502
503 // If coverage mapping generation is enabled, create the
504 // CoverageMappingModuleGen object.
505 if (CodeGenOpts.CoverageMapping)
506 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
507
508 // Generate the module name hash here if needed.
509 if (CodeGenOpts.UniqueInternalLinkageNames &&
510 !getModule().getSourceFileName().empty()) {
511 std::string Path = getModule().getSourceFileName();
512 // Check if a path substitution is needed from the MacroPrefixMap.
513 for (const auto &Entry : LangOpts.MacroPrefixMap)
514 if (Path.rfind(Entry.first, 0) != std::string::npos) {
515 Path = Entry.second + Path.substr(Entry.first.size());
516 break;
517 }
518 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
519 }
520
521 // Record mregparm value now so it is visible through all of codegen.
522 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
523 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
524 CodeGenOpts.NumRegisterParameters);
525
526 // If there are any functions that are marked for Windows secure hot-patching,
527 // then build the list of functions now.
528 if (!CGO.MSSecureHotPatchFunctionsFile.empty() ||
529 !CGO.MSSecureHotPatchFunctionsList.empty()) {
530 if (!CGO.MSSecureHotPatchFunctionsFile.empty()) {
531 auto BufOrErr = FS->getBufferForFile(CGO.MSSecureHotPatchFunctionsFile);
532 if (BufOrErr) {
533 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
534 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(), true), E;
535 I != E; ++I)
536 this->MSHotPatchFunctions.push_back(std::string{*I});
537 } else {
538 auto &DE = Context.getDiagnostics();
539 DE.Report(diag::err_open_hotpatch_file_failed)
540 << CGO.MSSecureHotPatchFunctionsFile
541 << BufOrErr.getError().message();
542 }
543 }
544
545 for (const auto &FuncName : CGO.MSSecureHotPatchFunctionsList)
546 this->MSHotPatchFunctions.push_back(FuncName);
547
548 llvm::sort(this->MSHotPatchFunctions);
549 }
550
551 if (!Context.getAuxTargetInfo())
552 checkDataLayoutConsistency(Context.getTargetInfo(), LLVMContext, LangOpts);
553 }
554
555 CodeGenModule::~CodeGenModule() {}
556
557 void CodeGenModule::createObjCRuntime() {
558 // This is just isGNUFamily(), but we want to force implementors of
559 // new ABIs to decide how best to do this.
560 switch (LangOpts.ObjCRuntime.getKind()) {
561 case ObjCRuntime::GNUstep:
562 case ObjCRuntime::GCC:
563 case ObjCRuntime::ObjFW:
564 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
565 return;
566
567 case ObjCRuntime::FragileMacOSX:
568 case ObjCRuntime::MacOSX:
569 case ObjCRuntime::iOS:
570 case ObjCRuntime::WatchOS:
571 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
572 return;
573 }
574 llvm_unreachable("bad runtime kind");
575 }
576
577 void CodeGenModule::createOpenCLRuntime() {
578 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
579 }
580
581 void CodeGenModule::createOpenMPRuntime() {
582 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
583 Diags.Report(diag::err_omp_host_ir_file_not_found)
584 << LangOpts.OMPHostIRFile;
585
586 // Select a specialized code generation class based on the target, if any.
587 // If it does not exist use the default implementation.
588 switch (getTriple().getArch()) {
589 case llvm::Triple::nvptx:
590 case llvm::Triple::nvptx64:
591 case llvm::Triple::amdgcn:
592 case llvm::Triple::spirv64:
593 assert(
594 getLangOpts().OpenMPIsTargetDevice &&
595 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
596 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
597 break;
598 default:
599 if (LangOpts.OpenMPSimd)
600 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
601 else
602 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
603 break;
604 }
605 }
606
607 void CodeGenModule::createCUDARuntime() {
608 CUDARuntime.reset(CreateNVCUDARuntime(*this));
609 }
610
611 void CodeGenModule::createHLSLRuntime() {
612 HLSLRuntime.reset(new CGHLSLRuntime(*this));
613 }
614
615 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
616 Replacements[Name] = C;
617 }
618
619 void CodeGenModule::applyReplacements() {
620 for (auto &I : Replacements) {
621 StringRef MangledName = I.first;
622 llvm::Constant *Replacement = I.second;
623 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
624 if (!Entry)
625 continue;
626 auto *OldF = cast<llvm::Function>(Entry);
627 auto *NewF = dyn_cast<llvm::Function>(Replacement);
628 if (!NewF) {
629 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
630 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
631 } else {
632 auto *CE = cast<llvm::ConstantExpr>(Replacement);
633 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
634 CE->getOpcode() == llvm::Instruction::GetElementPtr);
635 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
636 }
637 }
638
639 // Replace old with new, but keep the old order.
640 OldF->replaceAllUsesWith(Replacement);
641 if (NewF) {
642 NewF->removeFromParent();
643 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
644 NewF);
645 }
646 OldF->eraseFromParent();
647 }
648 }
649
650 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
651 GlobalValReplacements.push_back(std::make_pair(GV, C));
652 }
653
654 void CodeGenModule::applyGlobalValReplacements() {
655 for (auto &I : GlobalValReplacements) {
656 llvm::GlobalValue *GV = I.first;
657 llvm::Constant *C = I.second;
658
659 GV->replaceAllUsesWith(C);
660 GV->eraseFromParent();
661 }
662 }
663
664 // This is only used in aliases that we created and we know they have a
665 // linear structure.
666 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
667 const llvm::Constant *C;
668 if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
669 C = GA->getAliasee();
670 else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
671 C = GI->getResolver();
672 else
673 return GV;
674
675 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
676 if (!AliaseeGV)
677 return nullptr;
678
679 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
680 if (FinalGV == GV)
681 return nullptr;
682
683 return FinalGV;
684 }
685
686 static bool checkAliasedGlobal(
687 const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location,
688 bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
689 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
690 SourceRange AliasRange) {
691 GV = getAliasedGlobal(Alias);
692 if (!GV) {
693 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
694 return false;
695 }
696
697 if (GV->hasCommonLinkage()) {
698 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
699 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
700 Diags.Report(Location, diag::err_alias_to_common);
701 return false;
702 }
703 }
704
705 if (GV->isDeclaration()) {
706 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
707 Diags.Report(Location, diag::note_alias_requires_mangled_name)
708 << IsIFunc << IsIFunc;
709 // Provide a note if the given function is not found and exists as a
710 // mangled name.
711 for (const auto &[Decl, Name] : MangledDeclNames) {
712 if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) {
713 IdentifierInfo *II = ND->getIdentifier();
714 if (II && II->getName() == GV->getName()) {
715 Diags.Report(Location, diag::note_alias_mangled_name_alternative)
716 << Name
717 << FixItHint::CreateReplacement(
718 AliasRange,
719 (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")")
720 .str());
721 }
722 }
723 }
724 return false;
725 }
726
727 if (IsIFunc) {
728 // Check resolver function type.
729 const auto *F = dyn_cast<llvm::Function>(GV);
730 if (!F) {
731 Diags.Report(Location, diag::err_alias_to_undefined)
732 << IsIFunc << IsIFunc;
733 return false;
734 }
735
736 llvm::FunctionType *FTy = F->getFunctionType();
737 if (!FTy->getReturnType()->isPointerTy()) {
738 Diags.Report(Location, diag::err_ifunc_resolver_return);
739 return false;
740 }
741 }
742
743 return true;
744 }
745
746 // Emit a warning if toc-data attribute is requested for global variables that
747 // have aliases and remove the toc-data attribute.
748 static void checkAliasForTocData(llvm::GlobalVariable *GVar,
749 const CodeGenOptions &CodeGenOpts,
750 DiagnosticsEngine &Diags,
751 SourceLocation Location) {
752 if (GVar->hasAttribute("toc-data")) {
753 auto GVId = GVar->getName();
754 // Is this a global variable specified by the user as local?
755 if ((llvm::binary_search(CodeGenOpts.TocDataVarsUserSpecified, GVId))) {
756 Diags.Report(Location, diag::warn_toc_unsupported_type)
757 << GVId << "the variable has an alias";
758 }
759 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
760 llvm::AttributeSet NewAttributes =
761 CurrAttributes.removeAttribute(GVar->getContext(), "toc-data");
762 GVar->setAttributes(NewAttributes);
763 }
764 }
765
766 void CodeGenModule::checkAliases() {
767 // Check if the constructed aliases are well formed. It is really unfortunate
768 // that we have to do this in CodeGen, but we only construct mangled names
769 // and aliases during codegen.
770 bool Error = false;
771 DiagnosticsEngine &Diags = getDiags();
772 for (const GlobalDecl &GD : Aliases) {
773 const auto *D = cast<ValueDecl>(GD.getDecl());
774 SourceLocation Location;
775 SourceRange Range;
776 bool IsIFunc = D->hasAttr<IFuncAttr>();
777 if (const Attr *A = D->getDefiningAttr()) {
778 Location = A->getLocation();
779 Range = A->getRange();
780 } else
781 llvm_unreachable("Not an alias or ifunc?");
782
783 StringRef MangledName = getMangledName(GD);
784 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
785 const llvm::GlobalValue *GV = nullptr;
786 if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV,
787 MangledDeclNames, Range)) {
788 Error = true;
789 continue;
790 }
791
792 if (getContext().getTargetInfo().getTriple().isOSAIX())
793 if (const llvm::GlobalVariable *GVar =
794 dyn_cast<const llvm::GlobalVariable>(GV))
795 checkAliasForTocData(const_cast<llvm::GlobalVariable *>(GVar),
796 getCodeGenOpts(), Diags, Location);
797
798 llvm::Constant *Aliasee =
799 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
800 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
801
802 llvm::GlobalValue *AliaseeGV;
803 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
804 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
805 else
806 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
807
808 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
809 StringRef AliasSection = SA->getName();
810 if (AliasSection != AliaseeGV->getSection())
811 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
812 << AliasSection << IsIFunc << IsIFunc;
813 }
814
815 // We have to handle alias to weak aliases in here. LLVM itself disallows
816 // this since the object semantics would not match the IL one. For
817 // compatibility with gcc we implement it by just pointing the alias
818 // to its aliasee's aliasee. We also warn, since the user is probably
819 // expecting the link to be weak.
820 if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
821 if (GA->isInterposable()) {
822 Diags.Report(Location, diag::warn_alias_to_weak_alias)
823 << GV->getName() << GA->getName() << IsIFunc;
824 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
825 GA->getAliasee(), Alias->getType());
826
827 if (IsIFunc)
828 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
829 else
830 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
831 }
832 }
833 // ifunc resolvers are usually implemented to run before sanitizer
834 // initialization. Disable instrumentation to prevent the ordering issue.
835 if (IsIFunc)
836 cast<llvm::Function>(Aliasee)->addFnAttr(
837 llvm::Attribute::DisableSanitizerInstrumentation);
838 }
839 if (!Error)
840 return;
841
842 for (const GlobalDecl &GD : Aliases) {
843 StringRef MangledName = getMangledName(GD);
844 llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
845 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
846 Alias->eraseFromParent();
847 }
848 }
849
850 void CodeGenModule::clear() {
851 DeferredDeclsToEmit.clear();
852 EmittedDeferredDecls.clear();
853 DeferredAnnotations.clear();
854 if (OpenMPRuntime)
855 OpenMPRuntime->clear();
856 }
857
858 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
859 StringRef MainFile) {
860 if (!hasDiagnostics())
861 return;
862 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
863 if (MainFile.empty())
864 MainFile = "<stdin>";
865 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
866 } else {
867 if (Mismatched > 0)
868 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
869
870 if (Missing > 0)
871 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
872 }
873 }
874
875 static std::optional<llvm::GlobalValue::VisibilityTypes>
876 getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K) {
877 // Map to LLVM visibility.
878 switch (K) {
879 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep:
880 return std::nullopt;
881 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default:
882 return llvm::GlobalValue::DefaultVisibility;
883 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden:
884 return llvm::GlobalValue::HiddenVisibility;
885 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected:
886 return llvm::GlobalValue::ProtectedVisibility;
887 }
888 llvm_unreachable("unknown option value!");
889 }
890
891 static void
892 setLLVMVisibility(llvm::GlobalValue &GV,
893 std::optional<llvm::GlobalValue::VisibilityTypes> V) {
894 if (!V)
895 return;
896
897 // Reset DSO locality before setting the visibility. This removes
898 // any effects that visibility options and annotations may have
899 // had on the DSO locality. Setting the visibility will implicitly set
900 // appropriate globals to DSO Local; however, this will be pessimistic
901 // w.r.t. to the normal compiler IRGen.
902 GV.setDSOLocal(false);
903 GV.setVisibility(*V);
904 }
905
906 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
907 llvm::Module &M) {
908 if (!LO.VisibilityFromDLLStorageClass)
909 return;
910
911 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
912 getLLVMVisibility(LO.getDLLExportVisibility());
913
914 std::optional<llvm::GlobalValue::VisibilityTypes>
915 NoDLLStorageClassVisibility =
916 getLLVMVisibility(LO.getNoDLLStorageClassVisibility());
917
918 std::optional<llvm::GlobalValue::VisibilityTypes>
919 ExternDeclDLLImportVisibility =
920 getLLVMVisibility(LO.getExternDeclDLLImportVisibility());
921
922 std::optional<llvm::GlobalValue::VisibilityTypes>
923 ExternDeclNoDLLStorageClassVisibility =
924 getLLVMVisibility(LO.getExternDeclNoDLLStorageClassVisibility());
925
926 for (llvm::GlobalValue &GV : M.global_values()) {
927 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
928 continue;
929
930 if (GV.isDeclarationForLinker())
931 setLLVMVisibility(GV, GV.getDLLStorageClass() ==
932 llvm::GlobalValue::DLLImportStorageClass
933 ? ExternDeclDLLImportVisibility
934 : ExternDeclNoDLLStorageClassVisibility);
935 else
936 setLLVMVisibility(GV, GV.getDLLStorageClass() ==
937 llvm::GlobalValue::DLLExportStorageClass
938 ? DLLExportVisibility
939 : NoDLLStorageClassVisibility);
940
941 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
942 }
943 }
944
945 static bool isStackProtectorOn(const LangOptions &LangOpts,
946 const llvm::Triple &Triple,
947 clang::LangOptions::StackProtectorMode Mode) {
948 if (Triple.isGPU())
949 return false;
950 return LangOpts.getStackProtector() == Mode;
951 }
952
953 void CodeGenModule::Release() {
954 Module *Primary = getContext().getCurrentNamedModule();
955 if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
956 EmitModuleInitializers(Primary);
957 EmitDeferred();
958 DeferredDecls.insert_range(EmittedDeferredDecls);
959 EmittedDeferredDecls.clear();
960 EmitVTablesOpportunistically();
961 applyGlobalValReplacements();
962 applyReplacements();
963 emitMultiVersionFunctions();
964
965 if (Context.getLangOpts().IncrementalExtensions &&
966 GlobalTopLevelStmtBlockInFlight.first) {
967 const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
968 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
969 GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
970 }
971
972 // Module implementations are initialized the same way as a regular TU that
973 // imports one or more modules.
974 if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
975 EmitCXXModuleInitFunc(Primary);
976 else
977 EmitCXXGlobalInitFunc();
978 EmitCXXGlobalCleanUpFunc();
979 registerGlobalDtorsWithAtExit();
980 EmitCXXThreadLocalInitFunc();
981 if (ObjCRuntime)
982 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
983 AddGlobalCtor(ObjCInitFunction);
984 if (Context.getLangOpts().CUDA && CUDARuntime) {
985 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
986 AddGlobalCtor(CudaCtorFunction);
987 }
988 if (OpenMPRuntime) {
989 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
990 OpenMPRuntime->clear();
991 }
992 if (PGOReader) {
993 getModule().setProfileSummary(
994 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
995 llvm::ProfileSummary::PSK_Instr);
996 if (PGOStats.hasDiagnostics())
997 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
998 }
999 llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
1000 return L.LexOrder < R.LexOrder;
1001 });
1002 EmitCtorList(GlobalCtors, "llvm.global_ctors");
1003 EmitCtorList(GlobalDtors, "llvm.global_dtors");
1004 EmitGlobalAnnotations();
1005 EmitStaticExternCAliases();
1006 checkAliases();
1007 EmitDeferredUnusedCoverageMappings();
1008 CodeGenPGO(*this).setValueProfilingFlag(getModule());
1009 CodeGenPGO(*this).setProfileVersion(getModule());
1010 if (CoverageMapping)
1011 CoverageMapping->emit();
1012 if (CodeGenOpts.SanitizeCfiCrossDso) {
1013 CodeGenFunction(*this).EmitCfiCheckFail();
1014 CodeGenFunction(*this).EmitCfiCheckStub();
1015 }
1016 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1017 finalizeKCFITypes();
1018 emitAtAvailableLinkGuard();
1019 if (Context.getTargetInfo().getTriple().isWasm())
1020 EmitMainVoidAlias();
1021
1022 if (getTriple().isAMDGPU() ||
1023 (getTriple().isSPIRV() && getTriple().getVendor() == llvm::Triple::AMD)) {
1024 // Emit amdhsa_code_object_version module flag, which is code object version
1025 // times 100.
1026 if (getTarget().getTargetOpts().CodeObjectVersion !=
1027 llvm::CodeObjectVersionKind::COV_None) {
1028 getModule().addModuleFlag(llvm::Module::Error,
1029 "amdhsa_code_object_version",
1030 getTarget().getTargetOpts().CodeObjectVersion);
1031 }
1032
1033 // Currently, "-mprintf-kind" option is only supported for HIP
1034 if (LangOpts.HIP) {
1035 auto *MDStr = llvm::MDString::get(
1036 getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal ==
1037 TargetOptions::AMDGPUPrintfKind::Hostcall)
1038 ? "hostcall"
1039 : "buffered");
1040 getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind",
1041 MDStr);
1042 }
1043 }
1044
1045 // Emit a global array containing all external kernels or device variables
1046 // used by host functions and mark it as used for CUDA/HIP. This is necessary
1047 // to get kernels or device variables in archives linked in even if these
1048 // kernels or device variables are only used in host functions.
1049 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1050 SmallVector<llvm::Constant *, 8> UsedArray;
1051 for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1052 GlobalDecl GD;
1053 if (auto *FD = dyn_cast<FunctionDecl>(D))
1054 GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
1055 else
1056 GD = GlobalDecl(D);
1057 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1058 GetAddrOfGlobal(GD), Int8PtrTy));
1059 }
1060
1061 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
1062
1063 auto *GV = new llvm::GlobalVariable(
1064 getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
1065 llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
1066 addCompilerUsedGlobal(GV);
1067 }
1068 if (LangOpts.HIP) {
1069 // Emit a unique ID so that host and device binaries from the same
1070 // compilation unit can be associated.
1071 auto *GV = new llvm::GlobalVariable(
1072 getModule(), Int8Ty, false, llvm::GlobalValue::ExternalLinkage,
1073 llvm::Constant::getNullValue(Int8Ty),
1074 "__hip_cuid_" + getContext().getCUIDHash());
1075 getSanitizerMetadata()->disableSanitizerForGlobal(GV);
1076 addCompilerUsedGlobal(GV);
1077 }
1078 emitLLVMUsed();
1079 if (SanStats)
1080 SanStats->finish();
1081
1082 if (CodeGenOpts.Autolink &&
1083 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1084 EmitModuleLinkOptions();
1085 }
1086
1087 // On ELF we pass the dependent library specifiers directly to the linker
1088 // without manipulating them. This is in contrast to other platforms where
1089 // they are mapped to a specific linker option by the compiler. This
1090 // difference is a result of the greater variety of ELF linkers and the fact
1091 // that ELF linkers tend to handle libraries in a more complicated fashion
1092 // than on other platforms. This forces us to defer handling the dependent
1093 // libs to the linker.
1094 //
1095 // CUDA/HIP device and host libraries are different. Currently there is no
1096 // way to differentiate dependent libraries for host or device. Existing
1097 // usage of #pragma comment(lib, *) is intended for host libraries on
1098 // Windows. Therefore emit llvm.dependent-libraries only for host.
1099 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1100 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
1101 for (auto *MD : ELFDependentLibraries)
1102 NMD->addOperand(MD);
1103 }
1104
1105 if (CodeGenOpts.DwarfVersion) {
1106 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
1107 CodeGenOpts.DwarfVersion);
1108 }
1109
1110 if (CodeGenOpts.Dwarf64)
1111 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
1112
1113 if (Context.getLangOpts().SemanticInterposition)
1114 // Require various optimization to respect semantic interposition.
1115 getModule().setSemanticInterposition(true);
1116
1117 if (CodeGenOpts.EmitCodeView) {
1118 // Indicate that we want CodeView in the metadata.
1119 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
1120 }
1121 if (CodeGenOpts.CodeViewGHash) {
1122 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
1123 }
1124 if (CodeGenOpts.ControlFlowGuard) {
1125 // Function ID tables and checks for Control Flow Guard (cfguard=2).
1126 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
1127 } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1128 // Function ID tables for Control Flow Guard (cfguard=1).
1129 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
1130 }
1131 if (CodeGenOpts.EHContGuard) {
1132 // Function ID tables for EH Continuation Guard.
1133 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
1134 }
1135 if (Context.getLangOpts().Kernel) {
1136 // Note if we are compiling with /kernel.
1137 getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
1138 }
1139 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1140 // We don't support LTO with 2 with different StrictVTablePointers
1141 // FIXME: we could support it by stripping all the information introduced
1142 // by StrictVTablePointers.
1143
1144 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
1145
1146 llvm::Metadata *Ops[2] = {
1147 llvm::MDString::get(VMContext, "StrictVTablePointers"),
1148 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1149 llvm::Type::getInt32Ty(VMContext), 1))};
1150
1151 getModule().addModuleFlag(llvm::Module::Require,
1152 "StrictVTablePointersRequirement",
1153 llvm::MDNode::get(VMContext, Ops));
1154 }
1155 if (getModuleDebugInfo() || getTriple().isOSWindows())
1156 // We support a single version in the linked module. The LLVM
1157 // parser will drop debug info with a different version number
1158 // (and warn about it, too).
1159 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
1160 llvm::DEBUG_METADATA_VERSION);
1161
1162 // We need to record the widths of enums and wchar_t, so that we can generate
1163 // the correct build attributes in the ARM backend. wchar_size is also used by
1164 // TargetLibraryInfo.
1165 uint64_t WCharWidth =
1166 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1167 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
1168
1169 if (getTriple().isOSzOS()) {
1170 getModule().addModuleFlag(llvm::Module::Warning,
1171 "zos_product_major_version",
1172 uint32_t(CLANG_VERSION_MAJOR));
1173 getModule().addModuleFlag(llvm::Module::Warning,
1174 "zos_product_minor_version",
1175 uint32_t(CLANG_VERSION_MINOR));
1176 getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel",
1177 uint32_t(CLANG_VERSION_PATCHLEVEL));
1178 std::string ProductId = getClangVendor() + "clang";
1179 getModule().addModuleFlag(llvm::Module::Error, "zos_product_id",
1180 llvm::MDString::get(VMContext, ProductId));
1181
1182 // Record the language because we need it for the PPA2.
1183 StringRef lang_str = languageToString(
1184 LangStandard::getLangStandardForKind(LangOpts.LangStd).Language);
1185 getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language",
1186 llvm::MDString::get(VMContext, lang_str));
1187
1188 time_t TT = PreprocessorOpts.SourceDateEpoch
1189 ? *PreprocessorOpts.SourceDateEpoch
1190 : std::time(nullptr);
1191 getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time",
1192 static_cast<uint64_t>(TT));
1193
1194 // Multiple modes will be supported here.
1195 getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode",
1196 llvm::MDString::get(VMContext, "ascii"));
1197 }
1198
1199 llvm::Triple T = Context.getTargetInfo().getTriple();
1200 if (T.isARM() || T.isThumb()) {
1201 // The minimum width of an enum in bytes
1202 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1203 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
1204 }
1205
1206 if (T.isRISCV()) {
1207 StringRef ABIStr = Target.getABI();
1208 llvm::LLVMContext &Ctx = TheModule.getContext();
1209 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
1210 llvm::MDString::get(Ctx, ABIStr));
1211
1212 // Add the canonical ISA string as metadata so the backend can set the ELF
1213 // attributes correctly. We use AppendUnique so LTO will keep all of the
1214 // unique ISA strings that were linked together.
1215 const std::vector<std::string> &Features =
1216 getTarget().getTargetOpts().Features;
1217 auto ParseResult =
1218 llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
1219 if (!errorToBool(ParseResult.takeError()))
1220 getModule().addModuleFlag(
1221 llvm::Module::AppendUnique, "riscv-isa",
1222 llvm::MDNode::get(
1223 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1224 }
1225
1226 if (CodeGenOpts.SanitizeCfiCrossDso) {
1227 // Indicate that we want cross-DSO control flow integrity checks.
1228 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
1229 }
1230
1231 if (CodeGenOpts.WholeProgramVTables) {
1232 // Indicate whether VFE was enabled for this module, so that the
1233 // vcall_visibility metadata added under whole program vtables is handled
1234 // appropriately in the optimizer.
1235 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
1236 CodeGenOpts.VirtualFunctionElimination);
1237 }
1238
1239 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1240 getModule().addModuleFlag(llvm::Module::Override,
1241 "CFI Canonical Jump Tables",
1242 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1243 }
1244
1245 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1246 getModule().addModuleFlag(llvm::Module::Override, "cfi-normalize-integers",
1247 1);
1248 }
1249
1250 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1251 getModule().addModuleFlag(
1252 llvm::Module::Append, "Unique Source File Identifier",
1253 llvm::MDTuple::get(
1254 TheModule.getContext(),
1255 llvm::MDString::get(TheModule.getContext(),
1256 CodeGenOpts.UniqueSourceFileIdentifier)));
1257 }
1258
1259 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1260 getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
1261 // KCFI assumes patchable-function-prefix is the same for all indirectly
1262 // called functions. Store the expected offset for code generation.
1263 if (CodeGenOpts.PatchableFunctionEntryOffset)
1264 getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
1265 CodeGenOpts.PatchableFunctionEntryOffset);
1266 if (CodeGenOpts.SanitizeKcfiArity)
1267 getModule().addModuleFlag(llvm::Module::Override, "kcfi-arity", 1);
1268 // Store the hash algorithm choice for use in LLVM passes
1269 getModule().addModuleFlag(
1270 llvm::Module::Override, "kcfi-hash",
1271 llvm::MDString::get(
1272 getLLVMContext(),
1273 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1274 }
1275
1276 if (CodeGenOpts.CFProtectionReturn &&
1277 Target.checkCFProtectionReturnSupported(getDiags())) {
1278 // Indicate that we want to instrument return control flow protection.
1279 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
1280 1);
1281 }
1282
1283 if (CodeGenOpts.CFProtectionBranch &&
1284 Target.checkCFProtectionBranchSupported(getDiags())) {
1285 // Indicate that we want to instrument branch control flow protection.
1286 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
1287 1);
1288
1289 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1290 if (Target.checkCFBranchLabelSchemeSupported(Scheme, getDiags())) {
1291 if (Scheme == CFBranchLabelSchemeKind::Default)
1292 Scheme = Target.getDefaultCFBranchLabelScheme();
1293 getModule().addModuleFlag(
1294 llvm::Module::Error, "cf-branch-label-scheme",
1295 llvm::MDString::get(getLLVMContext(),
1296 getCFBranchLabelSchemeFlagVal(Scheme)));
1297 }
1298 }
1299
1300 if (CodeGenOpts.FunctionReturnThunks)
1301 getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
1302
1303 if (CodeGenOpts.IndirectBranchCSPrefix)
1304 getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
1305
1306 // Add module metadata for return address signing (ignoring
1307 // non-leaf/all) and stack tagging. These are actually turned on by function
1308 // attributes, but we use module metadata to emit build attributes. This is
1309 // needed for LTO, where the function attributes are inside bitcode
1310 // serialised into a global variable by the time build attributes are
1311 // emitted, so we can't access them. LTO objects could be compiled with
1312 // different flags therefore module flags are set to "Min" behavior to achieve
1313 // the same end result of the normal build where e.g BTI is off if any object
1314 // doesn't support it.
1315 if (Context.getTargetInfo().hasFeature("ptrauth") &&
1316 LangOpts.getSignReturnAddressScope() !=
1317 LangOptions::SignReturnAddressScopeKind::None)
1318 getModule().addModuleFlag(llvm::Module::Override,
1319 "sign-return-address-buildattr", 1);
1320 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1321 getModule().addModuleFlag(llvm::Module::Override,
1322 "tag-stack-memory-buildattr", 1);
1323
1324 if (T.isARM() || T.isThumb() || T.isAArch64()) {
1325 // Previously 1 is used and meant for the backed to derive the function
1326 // attribute form it. 2 now means function attributes already set for all
1327 // functions in this module, so no need to propagate those from the module
1328 // flag. Value is only used in case of LTO module merge because the backend
1329 // will see all required function attribute set already. Value is used
1330 // before modules got merged. Any posive value means the feature is active
1331 // and required binary markings need to be emit accordingly.
1332 if (LangOpts.BranchTargetEnforcement)
1333 getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
1334 2);
1335 if (LangOpts.BranchProtectionPAuthLR)
1336 getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr",
1337 2);
1338 if (LangOpts.GuardedControlStack)
1339 getModule().addModuleFlag(llvm::Module::Min, "guarded-control-stack", 2);
1340 if (LangOpts.hasSignReturnAddress())
1341 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 2);
1342 if (LangOpts.isSignReturnAddressScopeAll())
1343 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
1344 2);
1345 if (!LangOpts.isSignReturnAddressWithAKey())
1346 getModule().addModuleFlag(llvm::Module::Min,
1347 "sign-return-address-with-bkey", 2);
1348
1349 if (LangOpts.PointerAuthELFGOT)
1350 getModule().addModuleFlag(llvm::Module::Min, "ptrauth-elf-got", 1);
1351
1352 if (getTriple().isOSLinux()) {
1353 if (LangOpts.PointerAuthCalls)
1354 getModule().addModuleFlag(llvm::Module::Min, "ptrauth-sign-personality",
1355 1);
1356 assert(getTriple().isOSBinFormatELF());
1357 using namespace llvm::ELF;
1358 uint64_t PAuthABIVersion =
1359 (LangOpts.PointerAuthIntrinsics
1360 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1361 (LangOpts.PointerAuthCalls
1362 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1363 (LangOpts.PointerAuthReturns
1364 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1365 (LangOpts.PointerAuthAuthTraps
1366 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1367 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1368 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1369 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1370 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1371 (LangOpts.PointerAuthInitFini
1372 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1373 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1374 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1375 (LangOpts.PointerAuthELFGOT
1376 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1377 (LangOpts.PointerAuthIndirectGotos
1378 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1379 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1380 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1381 (LangOpts.PointerAuthFunctionTypeDiscrimination
1382 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1383 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1384 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1385 "Update when new enum items are defined");
1386 if (PAuthABIVersion != 0) {
1387 getModule().addModuleFlag(llvm::Module::Error,
1388 "aarch64-elf-pauthabi-platform",
1389 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1390 getModule().addModuleFlag(llvm::Module::Error,
1391 "aarch64-elf-pauthabi-version",
1392 PAuthABIVersion);
1393 }
1394 }
1395 }
1396
1397 if (CodeGenOpts.StackClashProtector)
1398 getModule().addModuleFlag(
1399 llvm::Module::Override, "probe-stack",
1400 llvm::MDString::get(TheModule.getContext(), "inline-asm"));
1401
1402 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1403 getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size",
1404 CodeGenOpts.StackProbeSize);
1405
1406 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1407 llvm::LLVMContext &Ctx = TheModule.getContext();
1408 getModule().addModuleFlag(
1409 llvm::Module::Error, "MemProfProfileFilename",
1410 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1411 }
1412
1413 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
1414 // Indicate whether __nvvm_reflect should be configured to flush denormal
1415 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
1416 // property.)
1417 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
1418 CodeGenOpts.FP32DenormalMode.Output !=
1419 llvm::DenormalMode::IEEE);
1420 }
1421
1422 if (LangOpts.EHAsynch)
1423 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
1424
1425 // Emit Import Call section.
1426 if (CodeGenOpts.ImportCallOptimization)
1427 getModule().addModuleFlag(llvm::Module::Warning, "import-call-optimization",
1428 1);
1429
1430 // Enable unwind v2 (epilog).
1431 if (CodeGenOpts.getWinX64EHUnwindV2() != llvm::WinX64EHUnwindV2Mode::Disabled)
1432 getModule().addModuleFlag(
1433 llvm::Module::Warning, "winx64-eh-unwindv2",
1434 static_cast<unsigned>(CodeGenOpts.getWinX64EHUnwindV2()));
1435
1436 // Indicate whether this Module was compiled with -fopenmp
1437 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1438 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
1439 if (getLangOpts().OpenMPIsTargetDevice)
1440 getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
1441 LangOpts.OpenMP);
1442
1443 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
1444 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
1445 EmitOpenCLMetadata();
1446 // Emit SPIR version.
1447 if (getTriple().isSPIR()) {
1448 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
1449 // opencl.spir.version named metadata.
1450 // C++ for OpenCL has a distinct mapping for version compatibility with
1451 // OpenCL.
1452 auto Version = LangOpts.getOpenCLCompatibleVersion();
1453 llvm::Metadata *SPIRVerElts[] = {
1454 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1455 Int32Ty, Version / 100)),
1456 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1457 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1458 llvm::NamedMDNode *SPIRVerMD =
1459 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
1460 llvm::LLVMContext &Ctx = TheModule.getContext();
1461 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1462 }
1463 }
1464
1465 // HLSL related end of code gen work items.
1466 if (LangOpts.HLSL)
1467 getHLSLRuntime().finishCodeGen();
1468
1469 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1470 assert(PLevel < 3 && "Invalid PIC Level");
1471 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
1472 if (Context.getLangOpts().PIE)
1473 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
1474 }
1475
1476 if (getCodeGenOpts().CodeModel.size() > 0) {
1477 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
1478 .Case("tiny", llvm::CodeModel::Tiny)
1479 .Case("small", llvm::CodeModel::Small)
1480 .Case("kernel", llvm::CodeModel::Kernel)
1481 .Case("medium", llvm::CodeModel::Medium)
1482 .Case("large", llvm::CodeModel::Large)
1483 .Default(~0u);
1484 if (CM != ~0u) {
1485 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
1486 getModule().setCodeModel(codeModel);
1487
1488 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1489 Context.getTargetInfo().getTriple().getArch() ==
1490 llvm::Triple::x86_64) {
1491 getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold);
1492 }
1493 }
1494 }
1495
1496 if (CodeGenOpts.NoPLT)
1497 getModule().setRtLibUseGOT();
1498 if (getTriple().isOSBinFormatELF() &&
1499 CodeGenOpts.DirectAccessExternalData !=
1500 getModule().getDirectAccessExternalData()) {
1501 getModule().setDirectAccessExternalData(
1502 CodeGenOpts.DirectAccessExternalData);
1503 }
1504 if (CodeGenOpts.UnwindTables)
1505 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1506
1507 switch (CodeGenOpts.getFramePointer()) {
1508 case CodeGenOptions::FramePointerKind::None:
1509 // 0 ("none") is the default.
1510 break;
1511 case CodeGenOptions::FramePointerKind::Reserved:
1512 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1513 break;
1514 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
1515 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
1516 break;
1517 case CodeGenOptions::FramePointerKind::NonLeaf:
1518 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1519 break;
1520 case CodeGenOptions::FramePointerKind::All:
1521 getModule().setFramePointer(llvm::FramePointerKind::All);
1522 break;
1523 }
1524
1525 SimplifyPersonality();
1526
1527 if (getCodeGenOpts().EmitDeclMetadata)
1528 EmitDeclMetadata();
1529
1530 if (getCodeGenOpts().CoverageNotesFile.size() ||
1531 getCodeGenOpts().CoverageDataFile.size())
1532 EmitCoverageFile();
1533
1534 if (CGDebugInfo *DI = getModuleDebugInfo())
1535 DI->finalize();
1536
1537 if (getCodeGenOpts().EmitVersionIdentMetadata)
1538 EmitVersionIdentMetadata();
1539
1540 if (!getCodeGenOpts().RecordCommandLine.empty())
1541 EmitCommandLineMetadata();
1542
1543 if (!getCodeGenOpts().StackProtectorGuard.empty())
1544 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
1545 if (!getCodeGenOpts().StackProtectorGuardReg.empty())
1546 getModule().setStackProtectorGuardReg(
1547 getCodeGenOpts().StackProtectorGuardReg);
1548 if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
1549 getModule().setStackProtectorGuardSymbol(
1550 getCodeGenOpts().StackProtectorGuardSymbol);
1551 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
1552 getModule().setStackProtectorGuardOffset(
1553 getCodeGenOpts().StackProtectorGuardOffset);
1554 if (getCodeGenOpts().StackAlignment)
1555 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
1556 if (getCodeGenOpts().SkipRaxSetup)
1557 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
1558 if (getLangOpts().RegCall4)
1559 getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1);
1560
1561 if (getContext().getTargetInfo().getMaxTLSAlign())
1562 getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
1563 getContext().getTargetInfo().getMaxTLSAlign());
1564
1565 getTargetCodeGenInfo().emitTargetGlobals(*this);
1566
1567 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
1568
1569 EmitBackendOptionsMetadata(getCodeGenOpts());
1570
1571 // If there is device offloading code embed it in the host now.
1572 EmbedObject(&getModule(), CodeGenOpts, *getFileSystem(), getDiags());
1573
1574 // Set visibility from DLL storage class
1575 // We do this at the end of LLVM IR generation; after any operation
1576 // that might affect the DLL storage class or the visibility, and
1577 // before anything that might act on these.
1578 setVisibilityFromDLLStorageClass(LangOpts, getModule());
1579
1580 // Check the tail call symbols are truly undefined.
1581 if (getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1582 for (auto &I : MustTailCallUndefinedGlobals) {
1583 if (!I.first->isDefined())
1584 getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1585 else {
1586 StringRef MangledName = getMangledName(GlobalDecl(I.first));
1587 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1588 if (!Entry || Entry->isWeakForLinker() ||
1589 Entry->isDeclarationForLinker())
1590 getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1591 }
1592 }
1593 }
1594
1595 // Emit `!llvm.errno.tbaa`, a module-level metadata that specifies the TBAA
1596 // for an int access. This allows LLVM to reason about what memory can be
1597 // accessed by certain library calls that only touch errno.
1598 if (TBAA) {
1599 TBAAAccessInfo TBAAInfo = getTBAAAccessInfo(Context.IntTy);
1600 if (llvm::MDNode *IntegerNode = getTBAAAccessTagInfo(TBAAInfo)) {
1601 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(ErrnoTBAAMDName);
1602 ErrnoTBAAMD->addOperand(IntegerNode);
1603 }
1604 }
1605 }
1606
1607 void CodeGenModule::EmitOpenCLMetadata() {
1608 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
1609 // opencl.ocl.version named metadata node.
1610 // C++ for OpenCL has a distinct mapping for versions compatible with OpenCL.
1611 auto CLVersion = LangOpts.getOpenCLCompatibleVersion();
1612
1613 auto EmitVersion = [this](StringRef MDName, int Version) {
1614 llvm::Metadata *OCLVerElts[] = {
1615 llvm::ConstantAsMetadata::get(
1616 llvm::ConstantInt::get(Int32Ty, Version / 100)),
1617 llvm::ConstantAsMetadata::get(
1618 llvm::ConstantInt::get(Int32Ty, (Version % 100) / 10))};
1619 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1620 llvm::LLVMContext &Ctx = TheModule.getContext();
1621 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1622 };
1623
1624 EmitVersion("opencl.ocl.version", CLVersion);
1625 if (LangOpts.OpenCLCPlusPlus) {
1626 // In addition to the OpenCL compatible version, emit the C++ version.
1627 EmitVersion("opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1628 }
1629 }
1630
1631 void CodeGenModule::EmitBackendOptionsMetadata(
1632 const CodeGenOptions &CodeGenOpts) {
1633 if (getTriple().isRISCV()) {
1634 getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
1635 CodeGenOpts.SmallDataLimit);
1636 }
1637
1638 // Set AllocToken configuration for backend pipeline.
1639 if (LangOpts.AllocTokenMode) {
1640 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
1641 getModule().addModuleFlag(llvm::Module::Error, "alloc-token-mode",
1642 llvm::MDString::get(VMContext, S));
1643 }
1644 if (LangOpts.AllocTokenMax)
1645 getModule().addModuleFlag(
1646 llvm::Module::Error, "alloc-token-max",
1647 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1648 *LangOpts.AllocTokenMax));
1649 if (CodeGenOpts.SanitizeAllocTokenFastABI)
1650 getModule().addModuleFlag(llvm::Module::Error, "alloc-token-fast-abi", 1);
1651 if (CodeGenOpts.SanitizeAllocTokenExtended)
1652 getModule().addModuleFlag(llvm::Module::Error, "alloc-token-extended", 1);
1653 }
1654
1655 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
1656 // Make sure that this type is translated.
1657 getTypes().UpdateCompletedType(TD);
1658 }
1659
1660 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
1661 // Make sure that this type is translated.
1662 getTypes().RefreshTypeCacheForClass(RD);
1663 }
1664
1665 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
1666 if (!TBAA)
1667 return nullptr;
1668 return TBAA->getTypeInfo(QTy);
1669 }
1670
1671 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
1672 if (!TBAA)
1673 return TBAAAccessInfo();
1674 if (getLangOpts().CUDAIsDevice) {
1675 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
1676 // access info.
1677 if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
1678 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
1679 nullptr)
1680 return TBAAAccessInfo();
1681 } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
1682 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
1683 nullptr)
1684 return TBAAAccessInfo();
1685 }
1686 }
1687 return TBAA->getAccessInfo(AccessType);
1688 }
1689
1690 TBAAAccessInfo
1691 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
1692 if (!TBAA)
1693 return TBAAAccessInfo();
1694 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1695 }
1696
1697 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
1698 if (!TBAA)
1699 return nullptr;
1700 return TBAA->getTBAAStructInfo(QTy);
1701 }
1702
1703 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
1704 if (!TBAA)
1705 return nullptr;
1706 return TBAA->getBaseTypeInfo(QTy);
1707 }
1708
1709 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
1710 if (!TBAA)
1711 return nullptr;
1712 return TBAA->getAccessTagInfo(Info);
1713 }
1714
1715 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
1716 TBAAAccessInfo TargetInfo) {
1717 if (!TBAA)
1718 return TBAAAccessInfo();
1719 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
1720 }
1721
1722 TBAAAccessInfo
1723 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
1724 TBAAAccessInfo InfoB) {
1725 if (!TBAA)
1726 return TBAAAccessInfo();
1727 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1728 }
1729
1730 TBAAAccessInfo
1731 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
1732 TBAAAccessInfo SrcInfo) {
1733 if (!TBAA)
1734 return TBAAAccessInfo();
1735 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1736 }
1737
1738 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
1739 TBAAAccessInfo TBAAInfo) {
1740 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
1741 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1742 }
1743
1744 void CodeGenModule::DecorateInstructionWithInvariantGroup(
1745 llvm::Instruction *I, const CXXRecordDecl *RD) {
1746 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1747 llvm::MDNode::get(getLLVMContext(), {}));
1748 }
1749
1750 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
1751 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1752 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
1753 }
1754
1755 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1756 /// specified stmt yet.
1757 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
1758 std::string Msg = Type;
1759 getDiags().Report(Context.getFullLoc(S->getBeginLoc()),
1760 diag::err_codegen_unsupported)
1761 << Msg << S->getSourceRange();
1762 }
1763
1764 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1765 /// specified decl yet.
1766 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
1767 std::string Msg = Type;
1768 getDiags().Report(Context.getFullLoc(D->getLocation()),
1769 diag::err_codegen_unsupported)
1770 << Msg;
1771 }
1772
1773 void CodeGenModule::runWithSufficientStackSpace(SourceLocation Loc,
1774 llvm::function_ref<void()> Fn) {
1775 StackHandler.runWithSufficientStackSpace(Loc, Fn);
1776 }
1777
1778 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
1779 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
1780 }
1781
1782 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1783 const NamedDecl *D) const {
1784 // Internal definitions always have default visibility.
1785 if (GV->hasLocalLinkage()) {
1786 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1787 return;
1788 }
1789 if (!D)
1790 return;
1791
1792 // Set visibility for definitions, and for declarations if requested globally
1793 // or set explicitly.
1794 LinkageInfo LV = D->getLinkageAndVisibility();
1795
1796 // OpenMP declare target variables must be visible to the host so they can
1797 // be registered. We require protected visibility unless the variable has
1798 // the DT_nohost modifier and does not need to be registered.
1799 if (Context.getLangOpts().OpenMP &&
1800 Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) &&
1801 D->hasAttr<OMPDeclareTargetDeclAttr>() &&
1802 D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1803 OMPDeclareTargetDeclAttr::DT_NoHost &&
1804 LV.getVisibility() == HiddenVisibility) {
1805 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1806 return;
1807 }
1808
1809 if (Context.getLangOpts().HLSL && !D->isInExportDeclContext()) {
1810 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1811 return;
1812 }
1813
1814 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1815 // Reject incompatible dlllstorage and visibility annotations.
1816 if (!LV.isVisibilityExplicit())
1817 return;
1818 if (GV->hasDLLExportStorageClass()) {
1819 if (LV.getVisibility() == HiddenVisibility)
1820 getDiags().Report(D->getLocation(),
1821 diag::err_hidden_visibility_dllexport);
1822 } else if (LV.getVisibility() != DefaultVisibility) {
1823 getDiags().Report(D->getLocation(),
1824 diag::err_non_default_visibility_dllimport);
1825 }
1826 return;
1827 }
1828
1829 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
1830 !GV->isDeclarationForLinker())
1831 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1832 }
1833
1834 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
1835 llvm::GlobalValue *GV) {
1836 if (GV->hasLocalLinkage())
1837 return true;
1838
1839 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1840 return true;
1841
1842 // DLLImport explicitly marks the GV as external.
1843 if (GV->hasDLLImportStorageClass())
1844 return false;
1845
1846 const llvm::Triple &TT = CGM.getTriple();
1847 const auto &CGOpts = CGM.getCodeGenOpts();
1848 if (TT.isOSCygMing()) {
1849 // In MinGW, variables without DLLImport can still be automatically
1850 // imported from a DLL by the linker; don't mark variables that
1851 // potentially could come from another DLL as DSO local.
1852
1853 // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1854 // (and this actually happens in the public interface of libstdc++), so
1855 // such variables can't be marked as DSO local. (Native TLS variables
1856 // can't be dllimported at all, though.)
1857 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1858 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) &&
1859 CGOpts.AutoImport)
1860 return false;
1861 }
1862
1863 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1864 // remain unresolved in the link, they can be resolved to zero, which is
1865 // outside the current DSO.
1866 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1867 return false;
1868
1869 // Every other GV is local on COFF.
1870 // Make an exception for windows OS in the triple: Some firmware builds use
1871 // *-win32-macho triples. This (accidentally?) produced windows relocations
1872 // without GOT tables in older clang versions; Keep this behaviour.
1873 // FIXME: even thread local variables?
1874 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1875 return true;
1876
1877 // Only handle COFF and ELF for now.
1878 if (!TT.isOSBinFormatELF())
1879 return false;
1880
1881 // If this is not an executable, don't assume anything is local.
1882 llvm::Reloc::Model RM = CGOpts.RelocationModel;
1883 const auto &LOpts = CGM.getLangOpts();
1884 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1885 // On ELF, if -fno-semantic-interposition is specified and the target
1886 // supports local aliases, there will be neither CC1
1887 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1888 // dso_local on the function if using a local alias is preferable (can avoid
1889 // PLT indirection).
1890 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1891 return false;
1892 return !(CGM.getLangOpts().SemanticInterposition ||
1893 CGM.getLangOpts().HalfNoSemanticInterposition);
1894 }
1895
1896 // A definition cannot be preempted from an executable.
1897 if (!GV->isDeclarationForLinker())
1898 return true;
1899
1900 // Most PIC code sequences that assume that a symbol is local cannot produce a
1901 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1902 // depended, it seems worth it to handle it here.
1903 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1904 return false;
1905
1906 // PowerPC64 prefers TOC indirection to avoid copy relocations.
1907 if (TT.isPPC64())
1908 return false;
1909
1910 if (CGOpts.DirectAccessExternalData) {
1911 // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1912 // for non-thread-local variables. If the symbol is not defined in the
1913 // executable, a copy relocation will be needed at link time. dso_local is
1914 // excluded for thread-local variables because they generally don't support
1915 // copy relocations.
1916 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1917 if (!Var->isThreadLocal())
1918 return true;
1919
1920 // -fno-pic sets dso_local on a function declaration to allow direct
1921 // accesses when taking its address (similar to a data symbol). If the
1922 // function is not defined in the executable, a canonical PLT entry will be
1923 // needed at link time. -fno-direct-access-external-data can avoid the
1924 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1925 // it could just cause trouble without providing perceptible benefits.
1926 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1927 return true;
1928 }
1929
1930 // If we can use copy relocations we can assume it is local.
1931
1932 // Otherwise don't assume it is local.
1933 return false;
1934 }
1935
1936 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1937 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1938 }
1939
1940 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1941 GlobalDecl GD) const {
1942 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1943 // C++ destructors have a few C++ ABI specific special cases.
1944 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1945 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
1946 return;
1947 }
1948 setDLLImportDLLExport(GV, D);
1949 }
1950
1951 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1952 const NamedDecl *D) const {
1953 if (D && D->isExternallyVisible()) {
1954 if (D->hasAttr<DLLImportAttr>())
1955 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1956 else if ((D->hasAttr<DLLExportAttr>() ||
1957 shouldMapVisibilityToDLLExport(D)) &&
1958 !GV->isDeclarationForLinker())
1959 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1960 }
1961 }
1962
1963 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1964 GlobalDecl GD) const {
1965 setDLLImportDLLExport(GV, GD);
1966 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1967 }
1968
1969 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1970 const NamedDecl *D) const {
1971 setDLLImportDLLExport(GV, D);
1972 setGVPropertiesAux(GV, D);
1973 }
1974
1975 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1976 const NamedDecl *D) const {
1977 setGlobalVisibility(GV, D);
1978 setDSOLocal(GV);
1979 GV->setPartition(CodeGenOpts.SymbolPartition);
1980 }
1981
1982 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1983 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1984 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1985 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1986 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1987 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1988 }
1989
1990 llvm::GlobalVariable::ThreadLocalMode
1991 CodeGenModule::GetDefaultLLVMTLSModel() const {
1992 switch (CodeGenOpts.getDefaultTLSModel()) {
1993 case CodeGenOptions::GeneralDynamicTLSModel:
1994 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1995 case CodeGenOptions::LocalDynamicTLSModel:
1996 return llvm::GlobalVariable::LocalDynamicTLSModel;
1997 case CodeGenOptions::InitialExecTLSModel:
1998 return llvm::GlobalVariable::InitialExecTLSModel;
1999 case CodeGenOptions::LocalExecTLSModel:
2000 return llvm::GlobalVariable::LocalExecTLSModel;
2001 }
2002 llvm_unreachable("Invalid TLS model!");
2003 }
2004
2005 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
2006 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
2007
2008 llvm::GlobalValue::ThreadLocalMode TLM;
2009 TLM = GetDefaultLLVMTLSModel();
2010
2011 // Override the TLS model if it is explicitly specified.
2012 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
2013 TLM = GetLLVMTLSModel(Attr->getModel());
2014 }
2015
2016 GV->setThreadLocalMode(TLM);
2017 }
2018
2019 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
2020 StringRef Name) {
2021 const TargetInfo &Target = CGM.getTarget();
2022 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
2023 }
2024
2025 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
2026 const CPUSpecificAttr *Attr,
2027 unsigned CPUIndex,
2028 raw_ostream &Out) {
2029 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
2030 // supported.
2031 if (Attr)
2032 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
2033 else if (CGM.getTarget().supportsIFunc())
2034 Out << ".resolver";
2035 }
2036
2037 // Returns true if GD is a function decl with internal linkage and
2038 // needs a unique suffix after the mangled name.
2039 static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
2040 CodeGenModule &CGM) {
2041 const Decl *D = GD.getDecl();
2042 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
2043 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
2044 }
2045
2046 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
2047 const NamedDecl *ND,
2048 bool OmitMultiVersionMangling = false) {
2049 SmallString<256> Buffer;
2050 llvm::raw_svector_ostream Out(Buffer);
2051 MangleContext &MC = CGM.getCXXABI().getMangleContext();
2052 if (!CGM.getModuleNameHash().empty())
2053 MC.needsUniqueInternalLinkageNames();
2054 bool ShouldMangle = MC.shouldMangleDeclName(ND);
2055 if (ShouldMangle)
2056 MC.mangleName(GD.getWithDecl(ND), Out);
2057 else {
2058 IdentifierInfo *II = ND->getIdentifier();
2059 assert(II && "Attempt to mangle unnamed decl.");
2060 const auto *FD = dyn_cast<FunctionDecl>(ND);
2061
2062 if (FD &&
2063 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
2064 if (CGM.getLangOpts().RegCall4)
2065 Out << "__regcall4__" << II->getName();
2066 else
2067 Out << "__regcall3__" << II->getName();
2068 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2069 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
2070 Out << "__device_stub__" << II->getName();
2071 } else if (FD &&
2072 DeviceKernelAttr::isOpenCLSpelling(
2073 FD->getAttr<DeviceKernelAttr>()) &&
2074 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
2075 Out << "__clang_ocl_kern_imp_" << II->getName();
2076 } else {
2077 Out << II->getName();
2078 }
2079 }
2080
2081 // Check if the module name hash should be appended for internal linkage
2082 // symbols. This should come before multi-version target suffixes are
2083 // appended. This is to keep the name and module hash suffix of the
2084 // internal linkage function together. The unique suffix should only be
2085 // added when name mangling is done to make sure that the final name can
2086 // be properly demangled. For example, for C functions without prototypes,
2087 // name mangling is not done and the unique suffix should not be appeneded
2088 // then.
2089 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
2090 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
2091 "Hash computed when not explicitly requested");
2092 Out << CGM.getModuleNameHash();
2093 }
2094
2095 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2096 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2097 switch (FD->getMultiVersionKind()) {
2098 case MultiVersionKind::CPUDispatch:
2099 case MultiVersionKind::CPUSpecific:
2100 AppendCPUSpecificCPUDispatchMangling(CGM,
2101 FD->getAttr<CPUSpecificAttr>(),
2102 GD.getMultiVersionIndex(), Out);
2103 break;
2104 case MultiVersionKind::Target: {
2105 auto *Attr = FD->getAttr<TargetAttr>();
2106 assert(Attr && "Expected TargetAttr to be present "
2107 "for attribute mangling");
2108 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
2109 Info.appendAttributeMangling(Attr, Out);
2110 break;
2111 }
2112 case MultiVersionKind::TargetVersion: {
2113 auto *Attr = FD->getAttr<TargetVersionAttr>();
2114 assert(Attr && "Expected TargetVersionAttr to be present "
2115 "for attribute mangling");
2116 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
2117 Info.appendAttributeMangling(Attr, Out);
2118 break;
2119 }
2120 case MultiVersionKind::TargetClones: {
2121 auto *Attr = FD->getAttr<TargetClonesAttr>();
2122 assert(Attr && "Expected TargetClonesAttr to be present "
2123 "for attribute mangling");
2124 unsigned Index = GD.getMultiVersionIndex();
2125 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
2126 Info.appendAttributeMangling(Attr, Index, Out);
2127 break;
2128 }
2129 case MultiVersionKind::None:
2130 llvm_unreachable("None multiversion type isn't valid here");
2131 }
2132 }
2133
2134 // Make unique name for device side static file-scope variable for HIP.
2135 if (CGM.getContext().shouldExternalize(ND) &&
2136 CGM.getLangOpts().GPURelocatableDeviceCode &&
2137 CGM.getLangOpts().CUDAIsDevice)
2138 CGM.printPostfixForExternalizedDecl(Out, ND);
2139
2140 return std::string(Out.str());
2141 }
2142
2143 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2144 const FunctionDecl *FD,
2145 StringRef &CurName) {
2146 if (!FD->isMultiVersion())
2147 return;
2148
2149 // Get the name of what this would be without the 'target' attribute. This
2150 // allows us to lookup the version that was emitted when this wasn't a
2151 // multiversion function.
2152 std::string NonTargetName =
2153 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
2154 GlobalDecl OtherGD;
2155 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
2156 assert(OtherGD.getCanonicalDecl()
2157 .getDecl()
2158 ->getAsFunction()
2159 ->isMultiVersion() &&
2160 "Other GD should now be a multiversioned function");
2161 // OtherFD is the version of this function that was mangled BEFORE
2162 // becoming a MultiVersion function. It potentially needs to be updated.
2163 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
2164 .getDecl()
2165 ->getAsFunction()
2166 ->getMostRecentDecl();
2167 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
2168 // This is so that if the initial version was already the 'default'
2169 // version, we don't try to update it.
2170 if (OtherName != NonTargetName) {
2171 // Remove instead of erase, since others may have stored the StringRef
2172 // to this.
2173 const auto ExistingRecord = Manglings.find(NonTargetName);
2174 if (ExistingRecord != std::end(Manglings))
2175 Manglings.remove(&(*ExistingRecord));
2176 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2177 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
2178 Result.first->first();
2179 // If this is the current decl is being created, make sure we update the name.
2180 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
2181 CurName = OtherNameRef;
2182 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
2183 Entry->setName(OtherName);
2184 }
2185 }
2186 }
2187
2188 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
2189 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
2190
2191 // Some ABIs don't have constructor variants. Make sure that base and
2192 // complete constructors get mangled the same.
2193 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
2194 if (!getTarget().getCXXABI().hasConstructorVariants()) {
2195 CXXCtorType OrigCtorType = GD.getCtorType();
2196 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
2197 if (OrigCtorType == Ctor_Base)
2198 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
2199 }
2200 }
2201
2202 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
2203 // static device variable depends on whether the variable is referenced by
2204 // a host or device host function. Therefore the mangled name cannot be
2205 // cached.
2206 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
2207 auto FoundName = MangledDeclNames.find(CanonicalGD);
2208 if (FoundName != MangledDeclNames.end())
2209 return FoundName->second;
2210 }
2211
2212 // Keep the first result in the case of a mangling collision.
2213 const auto *ND = cast<NamedDecl>(GD.getDecl());
2214 std::string MangledName = getMangledNameImpl(*this, GD, ND);
2215
2216 // Ensure either we have different ABIs between host and device compilations,
2217 // says host compilation following MSVC ABI but device compilation follows
2218 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
2219 // mangling should be the same after name stubbing. The later checking is
2220 // very important as the device kernel name being mangled in host-compilation
2221 // is used to resolve the device binaries to be executed. Inconsistent naming
2222 // result in undefined behavior. Even though we cannot check that naming
2223 // directly between host- and device-compilations, the host- and
2224 // device-mangling in host compilation could help catching certain ones.
2225 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2226 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
2227 (getContext().getAuxTargetInfo() &&
2228 (getContext().getAuxTargetInfo()->getCXXABI() !=
2229 getContext().getTargetInfo().getCXXABI())) ||
2230 getCUDARuntime().getDeviceSideName(ND) ==
2231 getMangledNameImpl(
2232 *this,
2233 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
2234 ND));
2235
2236 // This invariant should hold true in the future.
2237 // Prior work:
2238 // https://discourse.llvm.org/t/rfc-clang-diagnostic-for-demangling-failures/82835/8
2239 // https://github.com/llvm/llvm-project/issues/111345
2240 // assert(!((StringRef(MangledName).starts_with("_Z") ||
2241 // StringRef(MangledName).starts_with("?")) &&
2242 // !GD.getDecl()->hasAttr<AsmLabelAttr>() &&
2243 // llvm::demangle(MangledName) == MangledName) &&
2244 // "LLVM demangler must demangle clang-generated names");
2245
2246 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2247 return MangledDeclNames[CanonicalGD] = Result.first->first();
2248 }
2249
2250 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
2251 const BlockDecl *BD) {
2252 MangleContext &MangleCtx = getCXXABI().getMangleContext();
2253 const Decl *D = GD.getDecl();
2254
2255 SmallString<256> Buffer;
2256 llvm::raw_svector_ostream Out(Buffer);
2257 if (!D)
2258 MangleCtx.mangleGlobalBlock(BD,
2259 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2260 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2261 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
2262 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2263 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
2264 else
2265 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
2266
2267 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2268 return Result.first->first();
2269 }
2270
2271 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
2272 auto it = MangledDeclNames.begin();
2273 while (it != MangledDeclNames.end()) {
2274 if (it->second == Name)
2275 return it->first;
2276 it++;
2277 }
2278 return GlobalDecl();
2279 }
2280
2281 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
2282 return getModule().getNamedValue(Name);
2283 }
2284
2285 /// AddGlobalCtor - Add a function to the list that will be called before
2286 /// main() runs.
2287 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
2288 unsigned LexOrder,
2289 llvm::Constant *AssociatedData) {
2290 // FIXME: Type coercion of void()* types.
2291 GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
2292 }
2293
2294 /// AddGlobalDtor - Add a function to the list that will be called
2295 /// when the module is unloaded.
2296 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
2297 bool IsDtorAttrFunc) {
2298 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2299 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
2300 DtorsUsingAtExit[Priority].push_back(Dtor);
2301 return;
2302 }
2303
2304 // FIXME: Type coercion of void()* types.
2305 GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
2306 }
2307
2308 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
2309 if (Fns.empty()) return;
2310
2311 const PointerAuthSchema &InitFiniAuthSchema =
2312 getCodeGenOpts().PointerAuth.InitFiniPointers;
2313
2314 // Ctor function type is ptr.
2315 llvm::PointerType *PtrTy = llvm::PointerType::get(
2316 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2317
2318 // Get the type of a ctor entry, { i32, ptr, ptr }.
2319 llvm::StructType *CtorStructTy = llvm::StructType::get(Int32Ty, PtrTy, PtrTy);
2320
2321 // Construct the constructor and destructor arrays.
2322 ConstantInitBuilder Builder(*this);
2323 auto Ctors = Builder.beginArray(CtorStructTy);
2324 for (const auto &I : Fns) {
2325 auto Ctor = Ctors.beginStruct(CtorStructTy);
2326 Ctor.addInt(Int32Ty, I.Priority);
2327 if (InitFiniAuthSchema) {
2328 llvm::Constant *StorageAddress =
2329 (InitFiniAuthSchema.isAddressDiscriminated()
2330 ? llvm::ConstantExpr::getIntToPtr(
2331 llvm::ConstantInt::get(
2332 IntPtrTy,
2333 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2334 PtrTy)
2335 : nullptr);
2336 llvm::Constant *SignedCtorPtr = getConstantSignedPointer(
2337 I.Initializer, InitFiniAuthSchema.getKey(), StorageAddress,
2338 llvm::ConstantInt::get(
2339 SizeTy, InitFiniAuthSchema.getConstantDiscrimination()));
2340 Ctor.add(SignedCtorPtr);
2341 } else {
2342 Ctor.add(I.Initializer);
2343 }
2344 if (I.AssociatedData)
2345 Ctor.add(I.AssociatedData);
2346 else
2347 Ctor.addNullPointer(PtrTy);
2348 Ctor.finishAndAddTo(Ctors);
2349 }
2350
2351 auto List = Ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
2352 /*constant*/ false,
2353 llvm::GlobalValue::AppendingLinkage);
2354
2355 // The LTO linker doesn't seem to like it when we set an alignment
2356 // on appending variables. Take it off as a workaround.
2357 List->setAlignment(std::nullopt);
2358
2359 Fns.clear();
2360 }
2361
2362 llvm::GlobalValue::LinkageTypes
2363 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
2364 const auto *D = cast<FunctionDecl>(GD.getDecl());
2365
2366 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
2367
2368 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2369 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
2370
2371 return getLLVMLinkageForDeclarator(D, Linkage);
2372 }
2373
2374 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
2375 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2376 if (!MDS) return nullptr;
2377
2378 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
2379 }
2380
2381 static QualType GeneralizeTransparentUnion(QualType Ty) {
2382 const RecordType *UT = Ty->getAsUnionType();
2383 if (!UT)
2384 return Ty;
2385 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2386 if (!UD->hasAttr<TransparentUnionAttr>())
2387 return Ty;
2388 if (!UD->fields().empty())
2389 return UD->fields().begin()->getType();
2390 return Ty;
2391 }
2392
2393 // If `GeneralizePointers` is true, generalizes types to a void pointer with the
2394 // qualifiers of the originally pointed-to type, e.g. 'const char *' and 'char *
2395 // const *' generalize to 'const void *' while 'char *' and 'const char **'
2396 // generalize to 'void *'.
2397 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty,
2398 bool GeneralizePointers) {
2399 Ty = GeneralizeTransparentUnion(Ty);
2400
2401 if (!GeneralizePointers || !Ty->isPointerType())
2402 return Ty;
2403
2404 return Ctx.getPointerType(
2405 QualType(Ctx.VoidTy)
2406 .withCVRQualifiers(Ty->getPointeeType().getCVRQualifiers()));
2407 }
2408
2409 // Apply type generalization to a FunctionType's return and argument types
2410 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty,
2411 bool GeneralizePointers) {
2412 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
2413 SmallVector<QualType, 8> GeneralizedParams;
2414 for (auto &Param : FnType->param_types())
2415 GeneralizedParams.push_back(
2416 GeneralizeType(Ctx, Param, GeneralizePointers));
2417
2418 return Ctx.getFunctionType(
2419 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2420 GeneralizedParams, FnType->getExtProtoInfo());
2421 }
2422
2423 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
2424 return Ctx.getFunctionNoProtoType(
2425 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2426
2427 llvm_unreachable("Encountered unknown FunctionType");
2428 }
2429
2430 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T, StringRef Salt) {
2431 T = GeneralizeFunctionType(
2432 getContext(), T, getCodeGenOpts().SanitizeCfiICallGeneralizePointers);
2433 if (auto *FnType = T->getAs<FunctionProtoType>())
2434 T = getContext().getFunctionType(
2435 FnType->getReturnType(), FnType->getParamTypes(),
2436 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
2437
2438 std::string OutName;
2439 llvm::raw_string_ostream Out(OutName);
2440 getCXXABI().getMangleContext().mangleCanonicalTypeName(
2441 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
2442
2443 if (!Salt.empty())
2444 Out << "." << Salt;
2445
2446 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
2447 Out << ".normalized";
2448 if (getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
2449 Out << ".generalized";
2450
2451 return llvm::ConstantInt::get(
2452 Int32Ty, llvm::getKCFITypeID(OutName, getCodeGenOpts().SanitizeKcfiHash));
2453 }
2454
2455 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
2456 const CGFunctionInfo &Info,
2457 llvm::Function *F, bool IsThunk) {
2458 unsigned CallingConv;
2459 llvm::AttributeList PAL;
2460 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2461 /*AttrOnCallSite=*/false, IsThunk);
2462 if (CallingConv == llvm::CallingConv::X86_VectorCall &&
2463 getTarget().getTriple().isWindowsArm64EC()) {
2464 SourceLocation Loc;
2465 if (const Decl *D = GD.getDecl())
2466 Loc = D->getLocation();
2467
2468 Error(Loc, "__vectorcall calling convention is not currently supported");
2469 }
2470 F->setAttributes(PAL);
2471 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
2472 }
2473
2474 static void removeImageAccessQualifier(std::string& TyName) {
2475 std::string ReadOnlyQual("__read_only");
2476 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2477 if (ReadOnlyPos != std::string::npos)
2478 // "+ 1" for the space after access qualifier.
2479 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2480 else {
2481 std::string WriteOnlyQual("__write_only");
2482 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2483 if (WriteOnlyPos != std::string::npos)
2484 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2485 else {
2486 std::string ReadWriteQual("__read_write");
2487 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2488 if (ReadWritePos != std::string::npos)
2489 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2490 }
2491 }
2492 }
2493
2494 // Returns the address space id that should be produced to the
2495 // kernel_arg_addr_space metadata. This is always fixed to the ids
2496 // as specified in the SPIR 2.0 specification in order to differentiate
2497 // for example in clGetKernelArgInfo() implementation between the address
2498 // spaces with targets without unique mapping to the OpenCL address spaces
2499 // (basically all single AS CPUs).
2500 static unsigned ArgInfoAddressSpace(LangAS AS) {
2501 switch (AS) {
2502 case LangAS::opencl_global:
2503 return 1;
2504 case LangAS::opencl_constant:
2505 return 2;
2506 case LangAS::opencl_local:
2507 return 3;
2508 case LangAS::opencl_generic:
2509 return 4; // Not in SPIR 2.0 specs.
2510 case LangAS::opencl_global_device:
2511 return 5;
2512 case LangAS::opencl_global_host:
2513 return 6;
2514 default:
2515 return 0; // Assume private.
2516 }
2517 }
2518
2519 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
2520 const FunctionDecl *FD,
2521 CodeGenFunction *CGF) {
2522 assert(((FD && CGF) || (!FD && !CGF)) &&
2523 "Incorrect use - FD and CGF should either be both null or not!");
2524 // Create MDNodes that represent the kernel arg metadata.
2525 // Each MDNode is a list in the form of "key", N number of values which is
2526 // the same number of values as their are kernel arguments.
2527
2528 const PrintingPolicy &Policy = Context.getPrintingPolicy();
2529
2530 // MDNode for the kernel argument address space qualifiers.
2531 SmallVector<llvm::Metadata *, 8> addressQuals;
2532
2533 // MDNode for the kernel argument access qualifiers (images only).
2534 SmallVector<llvm::Metadata *, 8> accessQuals;
2535
2536 // MDNode for the kernel argument type names.
2537 SmallVector<llvm::Metadata *, 8> argTypeNames;
2538
2539 // MDNode for the kernel argument base type names.
2540 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
2541
2542 // MDNode for the kernel argument type qualifiers.
2543 SmallVector<llvm::Metadata *, 8> argTypeQuals;
2544
2545 // MDNode for the kernel argument names.
2546 SmallVector<llvm::Metadata *, 8> argNames;
2547
2548 if (FD && CGF)
2549 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
2550 const ParmVarDecl *parm = FD->getParamDecl(i);
2551 // Get argument name.
2552 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
2553
2554 if (!getLangOpts().OpenCL)
2555 continue;
2556 QualType ty = parm->getType();
2557 std::string typeQuals;
2558
2559 // Get image and pipe access qualifier:
2560 if (ty->isImageType() || ty->isPipeType()) {
2561 const Decl *PDecl = parm;
2562 if (const auto *TD = ty->getAs<TypedefType>())
2563 PDecl = TD->getDecl();
2564 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2565 if (A && A->isWriteOnly())
2566 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2567 else if (A && A->isReadWrite())
2568 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2569 else
2570 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2571 } else
2572 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2573
2574 auto getTypeSpelling = [&](QualType Ty) {
2575 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2576
2577 if (Ty.isCanonical()) {
2578 StringRef typeNameRef = typeName;
2579 // Turn "unsigned type" to "utype"
2580 if (typeNameRef.consume_front("unsigned "))
2581 return std::string("u") + typeNameRef.str();
2582 if (typeNameRef.consume_front("signed "))
2583 return typeNameRef.str();
2584 }
2585
2586 return typeName;
2587 };
2588
2589 if (ty->isPointerType()) {
2590 QualType pointeeTy = ty->getPointeeType();
2591
2592 // Get address qualifier.
2593 addressQuals.push_back(
2594 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
2595 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
2596
2597 // Get argument type name.
2598 std::string typeName = getTypeSpelling(pointeeTy) + "*";
2599 std::string baseTypeName =
2600 getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2601 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2602 argBaseTypeNames.push_back(
2603 llvm::MDString::get(VMContext, baseTypeName));
2604
2605 // Get argument type qualifiers:
2606 if (ty.isRestrictQualified())
2607 typeQuals = "restrict";
2608 if (pointeeTy.isConstQualified() ||
2609 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
2610 typeQuals += typeQuals.empty() ? "const" : " const";
2611 if (pointeeTy.isVolatileQualified())
2612 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
2613 } else {
2614 uint32_t AddrSpc = 0;
2615 bool isPipe = ty->isPipeType();
2616 if (ty->isImageType() || isPipe)
2617 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
2618
2619 addressQuals.push_back(
2620 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
2621
2622 // Get argument type name.
2623 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2624 std::string typeName = getTypeSpelling(ty);
2625 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
2626
2627 // Remove access qualifiers on images
2628 // (as they are inseparable from type in clang implementation,
2629 // but OpenCL spec provides a special query to get access qualifier
2630 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
2631 if (ty->isImageType()) {
2632 removeImageAccessQualifier(typeName);
2633 removeImageAccessQualifier(baseTypeName);
2634 }
2635
2636 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2637 argBaseTypeNames.push_back(
2638 llvm::MDString::get(VMContext, baseTypeName));
2639
2640 if (isPipe)
2641 typeQuals = "pipe";
2642 }
2643 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2644 }
2645
2646 if (getLangOpts().OpenCL) {
2647 Fn->setMetadata("kernel_arg_addr_space",
2648 llvm::MDNode::get(VMContext, addressQuals));
2649 Fn->setMetadata("kernel_arg_access_qual",
2650 llvm::MDNode::get(VMContext, accessQuals));
2651 Fn->setMetadata("kernel_arg_type",
2652 llvm::MDNode::get(VMContext, argTypeNames));
2653 Fn->setMetadata("kernel_arg_base_type",
2654 llvm::MDNode::get(VMContext, argBaseTypeNames));
2655 Fn->setMetadata("kernel_arg_type_qual",
2656 llvm::MDNode::get(VMContext, argTypeQuals));
2657 }
2658 if (getCodeGenOpts().EmitOpenCLArgMetadata ||
2659 getCodeGenOpts().HIPSaveKernelArgName)
2660 Fn->setMetadata("kernel_arg_name",
2661 llvm::MDNode::get(VMContext, argNames));
2662 }
2663
2664 /// Determines whether the language options require us to model
2665 /// unwind exceptions. We treat -fexceptions as mandating this
2666 /// except under the fragile ObjC ABI with only ObjC exceptions
2667 /// enabled. This means, for example, that C with -fexceptions
2668 /// enables this.
2669 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
2670 // If exceptions are completely disabled, obviously this is false.
2671 if (!LangOpts.Exceptions) return false;
2672
2673 // If C++ exceptions are enabled, this is true.
2674 if (LangOpts.CXXExceptions) return true;
2675
2676 // If ObjC exceptions are enabled, this depends on the ABI.
2677 if (LangOpts.ObjCExceptions) {
2678 return LangOpts.ObjCRuntime.hasUnwindExceptions();
2679 }
2680
2681 return true;
2682 }
2683
2684 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
2685 const CXXMethodDecl *MD) {
2686 // Check that the type metadata can ever actually be used by a call.
2687 if (!CGM.getCodeGenOpts().LTOUnit ||
2688 !CGM.HasHiddenLTOVisibility(MD->getParent()))
2689 return false;
2690
2691 // Only functions whose address can be taken with a member function pointer
2692 // need this sort of type metadata.
2693 return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() &&
2694 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2695 }
2696
2697 SmallVector<const CXXRecordDecl *, 0>
2698 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
2699 llvm::SetVector<const CXXRecordDecl *> MostBases;
2700
2701 std::function<void (const CXXRecordDecl *)> CollectMostBases;
2702 CollectMostBases = [&](const CXXRecordDecl *RD) {
2703 if (RD->getNumBases() == 0)
2704 MostBases.insert(RD);
2705 for (const CXXBaseSpecifier &B : RD->bases())
2706 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2707 };
2708 CollectMostBases(RD);
2709 return MostBases.takeVector();
2710 }
2711
2712 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
2713 llvm::Function *F) {
2714 llvm::AttrBuilder B(F->getContext());
2715
2716 if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2717 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2718
2719 if (CodeGenOpts.StackClashProtector)
2720 B.addAttribute("probe-stack", "inline-asm");
2721
2722 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2723 B.addAttribute("stack-probe-size",
2724 std::to_string(CodeGenOpts.StackProbeSize));
2725
2726 if (!hasUnwindExceptions(LangOpts))
2727 B.addAttribute(llvm::Attribute::NoUnwind);
2728
2729 if (D && D->hasAttr<NoStackProtectorAttr>())
2730 ; // Do nothing.
2731 else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2732 isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2733 B.addAttribute(llvm::Attribute::StackProtectStrong);
2734 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2735 B.addAttribute(llvm::Attribute::StackProtect);
2736 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong))
2737 B.addAttribute(llvm::Attribute::StackProtectStrong);
2738 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq))
2739 B.addAttribute(llvm::Attribute::StackProtectReq);
2740
2741 if (!D) {
2742 // Non-entry HLSL functions must always be inlined.
2743 if (getLangOpts().HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2744 B.addAttribute(llvm::Attribute::AlwaysInline);
2745 // If we don't have a declaration to control inlining, the function isn't
2746 // explicitly marked as alwaysinline for semantic reasons, and inlining is
2747 // disabled, mark the function as noinline.
2748 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2749 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2750 B.addAttribute(llvm::Attribute::NoInline);
2751
2752 F->addFnAttrs(B);
2753 return;
2754 }
2755
2756 // Handle SME attributes that apply to function definitions,
2757 // rather than to function prototypes.
2758 if (D->hasAttr<ArmLocallyStreamingAttr>())
2759 B.addAttribute("aarch64_pstate_sm_body");
2760
2761 if (auto *Attr = D->getAttr<ArmNewAttr>()) {
2762 if (Attr->isNewZA())
2763 B.addAttribute("aarch64_new_za");
2764 if (Attr->isNewZT0())
2765 B.addAttribute("aarch64_new_zt0");
2766 }
2767
2768 // Track whether we need to add the optnone LLVM attribute,
2769 // starting with the default for this optimization level.
2770 bool ShouldAddOptNone =
2771 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2772 // We can't add optnone in the following cases, it won't pass the verifier.
2773 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2774 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2775
2776 // Non-entry HLSL functions must always be inlined.
2777 if (getLangOpts().HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2778 !D->hasAttr<NoInlineAttr>()) {
2779 B.addAttribute(llvm::Attribute::AlwaysInline);
2780 } else if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2781 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2782 // Add optnone, but do so only if the function isn't always_inline.
2783 B.addAttribute(llvm::Attribute::OptimizeNone);
2784
2785 // OptimizeNone implies noinline; we should not be inlining such functions.
2786 B.addAttribute(llvm::Attribute::NoInline);
2787
2788 // We still need to handle naked functions even though optnone subsumes
2789 // much of their semantics.
2790 if (D->hasAttr<NakedAttr>())
2791 B.addAttribute(llvm::Attribute::Naked);
2792
2793 // OptimizeNone wins over OptimizeForSize and MinSize.
2794 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2795 F->removeFnAttr(llvm::Attribute::MinSize);
2796 } else if (D->hasAttr<NakedAttr>()) {
2797 // Naked implies noinline: we should not be inlining such functions.
2798 B.addAttribute(llvm::Attribute::Naked);
2799 B.addAttribute(llvm::Attribute::NoInline);
2800 } else if (D->hasAttr<NoDuplicateAttr>()) {
2801 B.addAttribute(llvm::Attribute::NoDuplicate);
2802 } else if (D->hasAttr<NoInlineAttr>() &&
2803 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2804 // Add noinline if the function isn't always_inline.
2805 B.addAttribute(llvm::Attribute::NoInline);
2806 } else if (D->hasAttr<AlwaysInlineAttr>() &&
2807 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2808 // (noinline wins over always_inline, and we can't specify both in IR)
2809 B.addAttribute(llvm::Attribute::AlwaysInline);
2810 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2811 // If we're not inlining, then force everything that isn't always_inline to
2812 // carry an explicit noinline attribute.
2813 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2814 B.addAttribute(llvm::Attribute::NoInline);
2815 } else {
2816 // Otherwise, propagate the inline hint attribute and potentially use its
2817 // absence to mark things as noinline.
2818 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2819 // Search function and template pattern redeclarations for inline.
2820 auto CheckForInline = [](const FunctionDecl *FD) {
2821 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2822 return Redecl->isInlineSpecified();
2823 };
2824 if (any_of(FD->redecls(), CheckRedeclForInline))
2825 return true;
2826 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2827 if (!Pattern)
2828 return false;
2829 return any_of(Pattern->redecls(), CheckRedeclForInline);
2830 };
2831 if (CheckForInline(FD)) {
2832 B.addAttribute(llvm::Attribute::InlineHint);
2833 } else if (CodeGenOpts.getInlining() ==
2834 CodeGenOptions::OnlyHintInlining &&
2835 !FD->isInlined() &&
2836 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2837 B.addAttribute(llvm::Attribute::NoInline);
2838 }
2839 }
2840 }
2841
2842 // Add other optimization related attributes if we are optimizing this
2843 // function.
2844 if (!D->hasAttr<OptimizeNoneAttr>()) {
2845 if (D->hasAttr<ColdAttr>()) {
2846 if (!ShouldAddOptNone)
2847 B.addAttribute(llvm::Attribute::OptimizeForSize);
2848 B.addAttribute(llvm::Attribute::Cold);
2849 }
2850 if (D->hasAttr<HotAttr>())
2851 B.addAttribute(llvm::Attribute::Hot);
2852 if (D->hasAttr<MinSizeAttr>())
2853 B.addAttribute(llvm::Attribute::MinSize);
2854 }
2855
2856 F->addFnAttrs(B);
2857
2858 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2859 if (alignment)
2860 F->setAlignment(llvm::Align(alignment));
2861
2862 if (!D->hasAttr<AlignedAttr>())
2863 if (LangOpts.FunctionAlignment)
2864 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2865
2866 // Some C++ ABIs require 2-byte alignment for member functions, in order to
2867 // reserve a bit for differentiating between virtual and non-virtual member
2868 // functions. If the current target's C++ ABI requires this and this is a
2869 // member function, set its alignment accordingly.
2870 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2871 if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2)
2872 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2873 }
2874
2875 // In the cross-dso CFI mode with canonical jump tables, we want !type
2876 // attributes on definitions only.
2877 if (CodeGenOpts.SanitizeCfiCrossDso &&
2878 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2879 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2880 // Skip available_externally functions. They won't be codegen'ed in the
2881 // current module anyway.
2882 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2883 createFunctionTypeMetadataForIcall(FD, F);
2884 }
2885 }
2886
2887 if (CodeGenOpts.CallGraphSection) {
2888 if (auto *FD = dyn_cast<FunctionDecl>(D))
2889 createIndirectFunctionTypeMD(FD, F);
2890 }
2891
2892 // Emit type metadata on member functions for member function pointer checks.
2893 // These are only ever necessary on definitions; we're guaranteed that the
2894 // definition will be present in the LTO unit as a result of LTO visibility.
2895 auto *MD = dyn_cast<CXXMethodDecl>(D);
2896 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2897 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2898 llvm::Metadata *Id =
2899 CreateMetadataIdentifierForType(Context.getMemberPointerType(
2900 MD->getType(), /*Qualifier=*/std::nullopt, Base));
2901 F->addTypeMetadata(0, Id);
2902 }
2903 }
2904 }
2905
2906 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2907 const Decl *D = GD.getDecl();
2908 if (isa_and_nonnull<NamedDecl>(D))
2909 setGVProperties(GV, GD);
2910 else
2911 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2912
2913 if (D && D->hasAttr<UsedAttr>())
2914 addUsedOrCompilerUsedGlobal(GV);
2915
2916 if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
2917 VD &&
2918 ((CodeGenOpts.KeepPersistentStorageVariables &&
2919 (VD->getStorageDuration() == SD_Static ||
2920 VD->getStorageDuration() == SD_Thread)) ||
2921 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
2922 VD->getType().isConstQualified())))
2923 addUsedOrCompilerUsedGlobal(GV);
2924 }
2925
2926 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2927 llvm::AttrBuilder &Attrs,
2928 bool SetTargetFeatures) {
2929 // Add target-cpu and target-features attributes to functions. If
2930 // we have a decl for the function and it has a target attribute then
2931 // parse that and add it to the feature set.
2932 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2933 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2934 std::vector<std::string> Features;
2935 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2936 FD = FD ? FD->getMostRecentDecl() : FD;
2937 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2938 const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2939 assert((!TD || !TV) && "both target_version and target specified");
2940 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2941 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2942 bool AddedAttr = false;
2943 if (TD || TV || SD || TC) {
2944 llvm::StringMap<bool> FeatureMap;
2945 getContext().getFunctionFeatureMap(FeatureMap, GD);
2946
2947 // Produce the canonical string for this set of features.
2948 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2949 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2950
2951 // Now add the target-cpu and target-features to the function.
2952 // While we populated the feature map above, we still need to
2953 // get and parse the target attribute so we can get the cpu for
2954 // the function.
2955 if (TD) {
2956 ParsedTargetAttr ParsedAttr =
2957 Target.parseTargetAttr(TD->getFeaturesStr());
2958 if (!ParsedAttr.CPU.empty() &&
2959 getTarget().isValidCPUName(ParsedAttr.CPU)) {
2960 TargetCPU = ParsedAttr.CPU;
2961 TuneCPU = ""; // Clear the tune CPU.
2962 }
2963 if (!ParsedAttr.Tune.empty() &&
2964 getTarget().isValidCPUName(ParsedAttr.Tune))
2965 TuneCPU = ParsedAttr.Tune;
2966 }
2967
2968 if (SD) {
2969 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2970 // favor this processor.
2971 TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
2972 }
2973 } else {
2974 // Otherwise just add the existing target cpu and target features to the
2975 // function.
2976 Features = getTarget().getTargetOpts().Features;
2977 }
2978
2979 if (!TargetCPU.empty()) {
2980 Attrs.addAttribute("target-cpu", TargetCPU);
2981 AddedAttr = true;
2982 }
2983 if (!TuneCPU.empty()) {
2984 Attrs.addAttribute("tune-cpu", TuneCPU);
2985 AddedAttr = true;
2986 }
2987 if (!Features.empty() && SetTargetFeatures) {
2988 llvm::erase_if(Features, [&](const std::string& F) {
2989 return getTarget().isReadOnlyFeature(F.substr(1));
2990 });
2991 llvm::sort(Features);
2992 Attrs.addAttribute("target-features", llvm::join(Features, ","));
2993 AddedAttr = true;
2994 }
2995 // Add metadata for AArch64 Function Multi Versioning.
2996 if (getTarget().getTriple().isAArch64()) {
2997 llvm::SmallVector<StringRef, 8> Feats;
2998 bool IsDefault = false;
2999 if (TV) {
3000 IsDefault = TV->isDefaultVersion();
3001 TV->getFeatures(Feats);
3002 } else if (TC) {
3003 IsDefault = TC->isDefaultVersion(GD.getMultiVersionIndex());
3004 TC->getFeatures(Feats, GD.getMultiVersionIndex());
3005 }
3006 if (IsDefault) {
3007 Attrs.addAttribute("fmv-features");
3008 AddedAttr = true;
3009 } else if (!Feats.empty()) {
3010 // Sort features and remove duplicates.
3011 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3012 std::string FMVFeatures;
3013 for (StringRef F : OrderedFeats)
3014 FMVFeatures.append("," + F.str());
3015 Attrs.addAttribute("fmv-features", FMVFeatures.substr(1));
3016 AddedAttr = true;
3017 }
3018 }
3019 return AddedAttr;
3020 }
3021
3022 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3023 llvm::GlobalObject *GO) {
3024 const Decl *D = GD.getDecl();
3025 SetCommonAttributes(GD, GO);
3026
3027 if (D) {
3028 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3029 if (D->hasAttr<RetainAttr>())
3030 addUsedGlobal(GV);
3031 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
3032 GV->addAttribute("bss-section", SA->getName());
3033 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
3034 GV->addAttribute("data-section", SA->getName());
3035 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
3036 GV->addAttribute("rodata-section", SA->getName());
3037 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
3038 GV->addAttribute("relro-section", SA->getName());
3039 }
3040
3041 if (auto *F = dyn_cast<llvm::Function>(GO)) {
3042 if (D->hasAttr<RetainAttr>())
3043 addUsedGlobal(F);
3044 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
3045 if (!D->getAttr<SectionAttr>())
3046 F->setSection(SA->getName());
3047
3048 llvm::AttrBuilder Attrs(F->getContext());
3049 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3050 // We know that GetCPUAndFeaturesAttributes will always have the
3051 // newest set, since it has the newest possible FunctionDecl, so the
3052 // new ones should replace the old.
3053 llvm::AttributeMask RemoveAttrs;
3054 RemoveAttrs.addAttribute("target-cpu");
3055 RemoveAttrs.addAttribute("target-features");
3056 RemoveAttrs.addAttribute("fmv-features");
3057 RemoveAttrs.addAttribute("tune-cpu");
3058 F->removeFnAttrs(RemoveAttrs);
3059 F->addFnAttrs(Attrs);
3060 }
3061 }
3062
3063 if (const auto *CSA = D->getAttr<CodeSegAttr>())
3064 GO->setSection(CSA->getName());
3065 else if (const auto *SA = D->getAttr<SectionAttr>())
3066 GO->setSection(SA->getName());
3067 }
3068
3069 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
3070 }
3071
3072 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
3073 llvm::Function *F,
3074 const CGFunctionInfo &FI) {
3075 const Decl *D = GD.getDecl();
3076 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
3077 SetLLVMFunctionAttributesForDefinition(D, F);
3078
3079 F->setLinkage(llvm::Function::InternalLinkage);
3080
3081 setNonAliasAttributes(GD, F);
3082 }
3083
3084 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
3085 // Set linkage and visibility in case we never see a definition.
3086 LinkageInfo LV = ND->getLinkageAndVisibility();
3087 // Don't set internal linkage on declarations.
3088 // "extern_weak" is overloaded in LLVM; we probably should have
3089 // separate linkage types for this.
3090 if (isExternallyVisible(LV.getLinkage()) &&
3091 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
3092 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3093 }
3094
3095 static bool hasExistingGeneralizedTypeMD(llvm::Function *F) {
3096 llvm::MDNode *MD = F->getMetadata(llvm::LLVMContext::MD_type);
3097 return MD && MD->hasGeneralizedMDString();
3098 }
3099
3100 void CodeGenModule::createIndirectFunctionTypeMD(const FunctionDecl *FD,
3101 llvm::Function *F) {
3102 // Return if generalized type metadata is already attached.
3103 if (hasExistingGeneralizedTypeMD(F))
3104 return;
3105
3106 // All functions which are not internal linkage could be indirect targets.
3107 // Address taken functions with internal linkage could be indirect targets.
3108 if (!F->hasLocalLinkage() ||
3109 F->getFunction().hasAddressTaken(nullptr, /*IgnoreCallbackUses=*/true,
3110 /*IgnoreAssumeLikeCalls=*/true,
3111 /*IgnoreLLVMUsed=*/false))
3112 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
3113 }
3114
3115 void CodeGenModule::createFunctionTypeMetadataForIcall(const FunctionDecl *FD,
3116 llvm::Function *F) {
3117 // Only if we are checking indirect calls.
3118 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3119 return;
3120
3121 // Non-static class methods are handled via vtable or member function pointer
3122 // checks elsewhere.
3123 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
3124 return;
3125
3126 QualType FnType = GeneralizeFunctionType(getContext(), FD->getType(),
3127 /*GeneralizePointers=*/false);
3128 llvm::Metadata *MD = CreateMetadataIdentifierForType(FnType);
3129 F->addTypeMetadata(0, MD);
3130 // Add the generalized identifier if not added already.
3131 if (!hasExistingGeneralizedTypeMD(F)) {
3132 QualType GenPtrFnType = GeneralizeFunctionType(getContext(), FD->getType(),
3133 /*GeneralizePointers=*/true);
3134 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(GenPtrFnType));
3135 }
3136
3137 // Emit a hash-based bit set entry for cross-DSO calls.
3138 if (CodeGenOpts.SanitizeCfiCrossDso)
3139 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
3140 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3141 }
3142
3143 void CodeGenModule::createCalleeTypeMetadataForIcall(const QualType &QT,
3144 llvm::CallBase *CB) {
3145 // Only if needed for call graph section and only for indirect calls.
3146 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall())
3147 return;
3148
3149 llvm::Metadata *TypeIdMD = CreateMetadataIdentifierGeneralized(QT);
3150 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
3151 getLLVMContext(), {llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
3152 llvm::Type::getInt64Ty(getLLVMContext()), 0)),
3153 TypeIdMD});
3154 llvm::MDTuple *MDN = llvm::MDNode::get(getLLVMContext(), {TypeTuple});
3155 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3156 }
3157
3158 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
3159 llvm::LLVMContext &Ctx = F->getContext();
3160 llvm::MDBuilder MDB(Ctx);
3161 llvm::StringRef Salt;
3162
3163 if (const auto *FP = FD->getType()->getAs<FunctionProtoType>())
3164 if (const auto &Info = FP->getExtraAttributeInfo())
3165 Salt = Info.CFISalt;
3166
3167 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3168 llvm::MDNode::get(Ctx, MDB.createConstant(CreateKCFITypeId(
3169 FD->getType(), Salt))));
3170 }
3171
3172 static bool allowKCFIIdentifier(StringRef Name) {
3173 // KCFI type identifier constants are only necessary for external assembly
3174 // functions, which means it's safe to skip unusual names. Subset of
3175 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
3176 return llvm::all_of(Name, [](const char &C) {
3177 return llvm::isAlnum(C) || C == '_' || C == '.';
3178 });
3179 }
3180
3181 void CodeGenModule::finalizeKCFITypes() {
3182 llvm::Module &M = getModule();
3183 for (auto &F : M.functions()) {
3184 // Remove KCFI type metadata from non-address-taken local functions.
3185 bool AddressTaken = F.hasAddressTaken();
3186 if (!AddressTaken && F.hasLocalLinkage())
3187 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3188
3189 // Generate a constant with the expected KCFI type identifier for all
3190 // address-taken function declarations to support annotating indirectly
3191 // called assembly functions.
3192 if (!AddressTaken || !F.isDeclaration())
3193 continue;
3194
3195 const llvm::ConstantInt *Type;
3196 if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3197 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3198 else
3199 continue;
3200
3201 StringRef Name = F.getName();
3202 if (!allowKCFIIdentifier(Name))
3203 continue;
3204
3205 std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
3206 Name + ", " + Twine(Type->getZExtValue()) + " /* " +
3207 Twine(Type->getSExtValue()) + " */\n")
3208 .str();
3209 M.appendModuleInlineAsm(Asm);
3210 }
3211 }
3212
3213 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
3214 bool IsIncompleteFunction,
3215 bool IsThunk) {
3216
3217 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3218 // If this is an intrinsic function, the attributes will have been set
3219 // when the function was created.
3220 return;
3221 }
3222
3223 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3224
3225 if (!IsIncompleteFunction)
3226 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
3227 IsThunk);
3228
3229 // Add the Returned attribute for "this", except for iOS 5 and earlier
3230 // where substantial code, including the libstdc++ dylib, was compiled with
3231 // GCC and does not actually return "this".
3232 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
3233 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
3234 assert(!F->arg_empty() &&
3235 F->arg_begin()->getType()
3236 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3237 "unexpected this return");
3238 F->addParamAttr(0, llvm::Attribute::Returned);
3239 }
3240
3241 // Only a few attributes are set on declarations; these may later be
3242 // overridden by a definition.
3243
3244 setLinkageForGV(F, FD);
3245 setGVProperties(F, FD);
3246
3247 // Setup target-specific attributes.
3248 if (!IsIncompleteFunction && F->isDeclaration())
3249 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
3250
3251 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
3252 F->setSection(CSA->getName());
3253 else if (const auto *SA = FD->getAttr<SectionAttr>())
3254 F->setSection(SA->getName());
3255
3256 if (const auto *EA = FD->getAttr<ErrorAttr>()) {
3257 if (EA->isError())
3258 F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
3259 else if (EA->isWarning())
3260 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
3261 }
3262
3263 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
3264 if (FD->isInlineBuiltinDeclaration()) {
3265 const FunctionDecl *FDBody;
3266 bool HasBody = FD->hasBody(FDBody);
3267 (void)HasBody;
3268 assert(HasBody && "Inline builtin declarations should always have an "
3269 "available body!");
3270 if (shouldEmitFunction(FDBody))
3271 F->addFnAttr(llvm::Attribute::NoBuiltin);
3272 }
3273
3274 if (FD->isReplaceableGlobalAllocationFunction()) {
3275 // A replaceable global allocation function does not act like a builtin by
3276 // default, only if it is invoked by a new-expression or delete-expression.
3277 F->addFnAttr(llvm::Attribute::NoBuiltin);
3278 }
3279
3280 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
3281 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3282 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3283 if (MD->isVirtual())
3284 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3285
3286 // Don't emit entries for function declarations in the cross-DSO mode. This
3287 // is handled with better precision by the receiving DSO. But if jump tables
3288 // are non-canonical then we need type metadata in order to produce the local
3289 // jump table.
3290 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3291 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3292 createFunctionTypeMetadataForIcall(FD, F);
3293
3294 if (CodeGenOpts.CallGraphSection)
3295 createIndirectFunctionTypeMD(FD, F);
3296
3297 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3298 setKCFIType(FD, F);
3299
3300 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
3301 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
3302
3303 if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
3304 F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3305
3306 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
3307 // Annotate the callback behavior as metadata:
3308 // - The callback callee (as argument number).
3309 // - The callback payloads (as argument numbers).
3310 llvm::LLVMContext &Ctx = F->getContext();
3311 llvm::MDBuilder MDB(Ctx);
3312
3313 // The payload indices are all but the first one in the encoding. The first
3314 // identifies the callback callee.
3315 int CalleeIdx = *CB->encoding_begin();
3316 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3317 F->addMetadata(llvm::LLVMContext::MD_callback,
3318 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3319 CalleeIdx, PayloadIndices,
3320 /* VarArgsArePassed */ false)}));
3321 }
3322 }
3323
3324 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
3325 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3326 "Only globals with definition can force usage.");
3327 LLVMUsed.emplace_back(GV);
3328 }
3329
3330 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
3331 assert(!GV->isDeclaration() &&
3332 "Only globals with definition can force usage.");
3333 LLVMCompilerUsed.emplace_back(GV);
3334 }
3335
3336 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
3337 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3338 "Only globals with definition can force usage.");
3339 if (getTriple().isOSBinFormatELF())
3340 LLVMCompilerUsed.emplace_back(GV);
3341 else
3342 LLVMUsed.emplace_back(GV);
3343 }
3344
3345 static void emitUsed(CodeGenModule &CGM, StringRef Name,
3346 std::vector<llvm::WeakTrackingVH> &List) {
3347 // Don't create llvm.used if there is no need.
3348 if (List.empty())
3349 return;
3350
3351 // Convert List to what ConstantArray needs.
3352 SmallVector<llvm::Constant*, 8> UsedArray;
3353 UsedArray.resize(List.size());
3354 for (unsigned i = 0, e = List.size(); i != e; ++i) {
3355 UsedArray[i] =
3356 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3357 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
3358 }
3359
3360 if (UsedArray.empty())
3361 return;
3362 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
3363
3364 auto *GV = new llvm::GlobalVariable(
3365 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
3366 llvm::ConstantArray::get(ATy, UsedArray), Name);
3367
3368 GV->setSection("llvm.metadata");
3369 }
3370
3371 void CodeGenModule::emitLLVMUsed() {
3372 emitUsed(*this, "llvm.used", LLVMUsed);
3373 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
3374 }
3375
3376 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
3377 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
3378 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
3379 }
3380
3381 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
3382 llvm::SmallString<32> Opt;
3383 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
3384 if (Opt.empty())
3385 return;
3386 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
3387 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
3388 }
3389
3390 void CodeGenModule::AddDependentLib(StringRef Lib) {
3391 auto &C = getLLVMContext();
3392 if (getTarget().getTriple().isOSBinFormatELF()) {
3393 ELFDependentLibraries.push_back(
3394 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
3395 return;
3396 }
3397
3398 llvm::SmallString<24> Opt;
3399 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
3400 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
3401 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
3402 }
3403
3404 /// Add link options implied by the given module, including modules
3405 /// it depends on, using a postorder walk.
3406 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
3407 SmallVectorImpl<llvm::MDNode *> &Metadata,
3408 llvm::SmallPtrSet<Module *, 16> &Visited) {
3409 // Import this module's parent.
3410 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
3411 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
3412 }
3413
3414 // Import this module's dependencies.
3415 for (Module *Import : llvm::reverse(Mod->Imports)) {
3416 if (Visited.insert(Import).second)
3417 addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
3418 }
3419
3420 // Add linker options to link against the libraries/frameworks
3421 // described by this module.
3422 llvm::LLVMContext &Context = CGM.getLLVMContext();
3423 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
3424
3425 // For modules that use export_as for linking, use that module
3426 // name instead.
3427 if (Mod->UseExportAsModuleLinkName)
3428 return;
3429
3430 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
3431 // Link against a framework. Frameworks are currently Darwin only, so we
3432 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
3433 if (LL.IsFramework) {
3434 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3435 llvm::MDString::get(Context, LL.Library)};
3436
3437 Metadata.push_back(llvm::MDNode::get(Context, Args));
3438 continue;
3439 }
3440
3441 // Link against a library.
3442 if (IsELF) {
3443 llvm::Metadata *Args[2] = {
3444 llvm::MDString::get(Context, "lib"),
3445 llvm::MDString::get(Context, LL.Library),
3446 };
3447 Metadata.push_back(llvm::MDNode::get(Context, Args));
3448 } else {
3449 llvm::SmallString<24> Opt;
3450 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
3451 auto *OptString = llvm::MDString::get(Context, Opt);
3452 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3453 }
3454 }
3455 }
3456
3457 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
3458 assert(Primary->isNamedModuleUnit() &&
3459 "We should only emit module initializers for named modules.");
3460
3461 // Emit the initializers in the order that sub-modules appear in the
3462 // source, first Global Module Fragments, if present.
3463 if (auto GMF = Primary->getGlobalModuleFragment()) {
3464 for (Decl *D : getContext().getModuleInitializers(GMF)) {
3465 if (isa<ImportDecl>(D))
3466 continue;
3467 assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
3468 EmitTopLevelDecl(D);
3469 }
3470 }
3471 // Second any associated with the module, itself.
3472 for (Decl *D : getContext().getModuleInitializers(Primary)) {
3473 // Skip import decls, the inits for those are called explicitly.
3474 if (isa<ImportDecl>(D))
3475 continue;
3476 EmitTopLevelDecl(D);
3477 }
3478 // Third any associated with the Privat eMOdule Fragment, if present.
3479 if (auto PMF = Primary->getPrivateModuleFragment()) {
3480 for (Decl *D : getContext().getModuleInitializers(PMF)) {
3481 // Skip import decls, the inits for those are called explicitly.
3482 if (isa<ImportDecl>(D))
3483 continue;
3484 assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
3485 EmitTopLevelDecl(D);
3486 }
3487 }
3488 }
3489
3490 void CodeGenModule::EmitModuleLinkOptions() {
3491 // Collect the set of all of the modules we want to visit to emit link
3492 // options, which is essentially the imported modules and all of their
3493 // non-explicit child modules.
3494 llvm::SetVector<clang::Module *> LinkModules;
3495 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3496 SmallVector<clang::Module *, 16> Stack;
3497
3498 // Seed the stack with imported modules.
3499 for (Module *M : ImportedModules) {
3500 // Do not add any link flags when an implementation TU of a module imports
3501 // a header of that same module.
3502 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
3503 !getLangOpts().isCompilingModule())
3504 continue;
3505 if (Visited.insert(M).second)
3506 Stack.push_back(M);
3507 }
3508
3509 // Find all of the modules to import, making a little effort to prune
3510 // non-leaf modules.
3511 while (!Stack.empty()) {
3512 clang::Module *Mod = Stack.pop_back_val();
3513
3514 bool AnyChildren = false;
3515
3516 // Visit the submodules of this module.
3517 for (const auto &SM : Mod->submodules()) {
3518 // Skip explicit children; they need to be explicitly imported to be
3519 // linked against.
3520 if (SM->IsExplicit)
3521 continue;
3522
3523 if (Visited.insert(SM).second) {
3524 Stack.push_back(SM);
3525 AnyChildren = true;
3526 }
3527 }
3528
3529 // We didn't find any children, so add this module to the list of
3530 // modules to link against.
3531 if (!AnyChildren) {
3532 LinkModules.insert(Mod);
3533 }
3534 }
3535
3536 // Add link options for all of the imported modules in reverse topological
3537 // order. We don't do anything to try to order import link flags with respect
3538 // to linker options inserted by things like #pragma comment().
3539 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3540 Visited.clear();
3541 for (Module *M : LinkModules)
3542 if (Visited.insert(M).second)
3543 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
3544 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3545 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3546
3547 // Add the linker options metadata flag.
3548 if (!LinkerOptionsMetadata.empty()) {
3549 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
3550 for (auto *MD : LinkerOptionsMetadata)
3551 NMD->addOperand(MD);
3552 }
3553 }
3554
3555 void CodeGenModule::EmitDeferred() {
3556 // Emit deferred declare target declarations.
3557 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
3558 getOpenMPRuntime().emitDeferredTargetDecls();
3559
3560 // Emit code for any potentially referenced deferred decls. Since a
3561 // previously unused static decl may become used during the generation of code
3562 // for a static function, iterate until no changes are made.
3563
3564 if (!DeferredVTables.empty()) {
3565 EmitDeferredVTables();
3566
3567 // Emitting a vtable doesn't directly cause more vtables to
3568 // become deferred, although it can cause functions to be
3569 // emitted that then need those vtables.
3570 assert(DeferredVTables.empty());
3571 }
3572
3573 // Emit CUDA/HIP static device variables referenced by host code only.
3574 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3575 // needed for further handling.
3576 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
3577 llvm::append_range(DeferredDeclsToEmit,
3578 getContext().CUDADeviceVarODRUsedByHost);
3579
3580 // Stop if we're out of both deferred vtables and deferred declarations.
3581 if (DeferredDeclsToEmit.empty())
3582 return;
3583
3584 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
3585 // work, it will not interfere with this.
3586 std::vector<GlobalDecl> CurDeclsToEmit;
3587 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3588
3589 for (GlobalDecl &D : CurDeclsToEmit) {
3590 // Functions declared with the sycl_kernel_entry_point attribute are
3591 // emitted normally during host compilation. During device compilation,
3592 // a SYCL kernel caller offload entry point function is generated and
3593 // emitted in place of each of these functions.
3594 if (const auto *FD = D.getDecl()->getAsFunction()) {
3595 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
3596 FD->isDefined()) {
3597 // Functions with an invalid sycl_kernel_entry_point attribute are
3598 // ignored during device compilation.
3599 if (!FD->getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3600 // Generate and emit the SYCL kernel caller function.
3601 EmitSYCLKernelCaller(FD, getContext());
3602 // Recurse to emit any symbols directly or indirectly referenced
3603 // by the SYCL kernel caller function.
3604 EmitDeferred();
3605 }
3606 // Do not emit the sycl_kernel_entry_point attributed function.
3607 continue;
3608 }
3609 }
3610
3611 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
3612 // to get GlobalValue with exactly the type we need, not something that
3613 // might had been created for another decl with the same mangled name but
3614 // different type.
3615 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3616 GetAddrOfGlobal(D, ForDefinition));
3617
3618 // In case of different address spaces, we may still get a cast, even with
3619 // IsForDefinition equal to true. Query mangled names table to get
3620 // GlobalValue.
3621 if (!GV)
3622 GV = GetGlobalValue(getMangledName(D));
3623
3624 // Make sure GetGlobalValue returned non-null.
3625 assert(GV);
3626
3627 // Check to see if we've already emitted this. This is necessary
3628 // for a couple of reasons: first, decls can end up in the
3629 // deferred-decls queue multiple times, and second, decls can end
3630 // up with definitions in unusual ways (e.g. by an extern inline
3631 // function acquiring a strong function redefinition). Just
3632 // ignore these cases.
3633 if (!GV->isDeclaration())
3634 continue;
3635
3636 // If this is OpenMP, check if it is legal to emit this global normally.
3637 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3638 continue;
3639
3640 // Otherwise, emit the definition and move on to the next one.
3641 EmitGlobalDefinition(D, GV);
3642
3643 // If we found out that we need to emit more decls, do that recursively.
3644 // This has the advantage that the decls are emitted in a DFS and related
3645 // ones are close together, which is convenient for testing.
3646 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3647 EmitDeferred();
3648 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3649 }
3650 }
3651 }
3652
3653 void CodeGenModule::EmitVTablesOpportunistically() {
3654 // Try to emit external vtables as available_externally if they have emitted
3655 // all inlined virtual functions. It runs after EmitDeferred() and therefore
3656 // is not allowed to create new references to things that need to be emitted
3657 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
3658
3659 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3660 && "Only emit opportunistic vtables with optimizations");
3661
3662 for (const CXXRecordDecl *RD : OpportunisticVTables) {
3663 assert(getVTables().isVTableExternal(RD) &&
3664 "This queue should only contain external vtables");
3665 if (getCXXABI().canSpeculativelyEmitVTable(RD))
3666 VTables.GenerateClassData(RD);
3667 }
3668 OpportunisticVTables.clear();
3669 }
3670
3671 void CodeGenModule::EmitGlobalAnnotations() {
3672 for (const auto& [MangledName, VD] : DeferredAnnotations) {
3673 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3674 if (GV)
3675 AddGlobalAnnotations(VD, GV);
3676 }
3677 DeferredAnnotations.clear();
3678
3679 if (Annotations.empty())
3680 return;
3681
3682 // Create a new global variable for the ConstantStruct in the Module.
3683 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3684 Annotations[0]->getType(), Annotations.size()), Annotations);
3685 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
3686 llvm::GlobalValue::AppendingLinkage,
3687 Array, "llvm.global.annotations");
3688 gv->setSection(AnnotationSection);
3689 }
3690
3691 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
3692 llvm::Constant *&AStr = AnnotationStrings[Str];
3693 if (AStr)
3694 return AStr;
3695
3696 // Not found yet, create a new global.
3697 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3698 auto *gv = new llvm::GlobalVariable(
3699 getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3700 ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3701 ConstGlobalsPtrTy->getAddressSpace());
3702 gv->setSection(AnnotationSection);
3703 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3704 AStr = gv;
3705 return gv;
3706 }
3707
3708 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
3709 SourceManager &SM = getContext().getSourceManager();
3710 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3711 if (PLoc.isValid())
3712 return EmitAnnotationString(PLoc.getFilename());
3713 return EmitAnnotationString(SM.getBufferName(Loc));
3714 }
3715
3716 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
3717 SourceManager &SM = getContext().getSourceManager();
3718 PresumedLoc PLoc = SM.getPresumedLoc(L);
3719 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
3720 SM.getExpansionLineNumber(L);
3721 return llvm::ConstantInt::get(Int32Ty, LineNo);
3722 }
3723
3724 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3725 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3726 if (Exprs.empty())
3727 return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3728
3729 llvm::FoldingSetNodeID ID;
3730 for (Expr *E : Exprs) {
3731 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3732 }
3733 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3734 if (Lookup)
3735 return Lookup;
3736
3737 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
3738 LLVMArgs.reserve(Exprs.size());
3739 ConstantEmitter ConstEmiter(*this);
3740 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3741 const auto *CE = cast<clang::ConstantExpr>(E);
3742 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3743 CE->getType());
3744 });
3745 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3746 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3747 llvm::GlobalValue::PrivateLinkage, Struct,
3748 ".args");
3749 GV->setSection(AnnotationSection);
3750 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3751
3752 Lookup = GV;
3753 return GV;
3754 }
3755
3756 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
3757 const AnnotateAttr *AA,
3758 SourceLocation L) {
3759 // Get the globals for file name, annotation, and the line number.
3760 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
3761 *UnitGV = EmitAnnotationUnit(L),
3762 *LineNoCst = EmitAnnotationLineNo(L),
3763 *Args = EmitAnnotationArgs(AA);
3764
3765 llvm::Constant *GVInGlobalsAS = GV;
3766 if (GV->getAddressSpace() !=
3767 getDataLayout().getDefaultGlobalsAddressSpace()) {
3768 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3769 GV,
3770 llvm::PointerType::get(
3771 GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace()));
3772 }
3773
3774 // Create the ConstantStruct for the global annotation.
3775 llvm::Constant *Fields[] = {
3776 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3777 };
3778 return llvm::ConstantStruct::getAnon(Fields);
3779 }
3780
3781 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
3782 llvm::GlobalValue *GV) {
3783 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
3784 // Get the struct elements for these annotations.
3785 for (const auto *I : D->specific_attrs<AnnotateAttr>())
3786 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
3787 }
3788
3789 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
3790 SourceLocation Loc) const {
3791 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3792 // NoSanitize by function name.
3793 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3794 return true;
3795 // NoSanitize by location. Check "mainfile" prefix.
3796 auto &SM = Context.getSourceManager();
3797 FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
3798 if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3799 return true;
3800
3801 // Check "src" prefix.
3802 if (Loc.isValid())
3803 return NoSanitizeL.containsLocation(Kind, Loc);
3804 // If location is unknown, this may be a compiler-generated function. Assume
3805 // it's located in the main file.
3806 return NoSanitizeL.containsFile(Kind, MainFile.getName());
3807 }
3808
3809 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
3810 llvm::GlobalVariable *GV,
3811 SourceLocation Loc, QualType Ty,
3812 StringRef Category) const {
3813 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3814 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3815 return true;
3816 auto &SM = Context.getSourceManager();
3817 if (NoSanitizeL.containsMainFile(
3818 Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
3819 Category))
3820 return true;
3821 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3822 return true;
3823
3824 // Check global type.
3825 if (!Ty.isNull()) {
3826 // Drill down the array types: if global variable of a fixed type is
3827 // not sanitized, we also don't instrument arrays of them.
3828 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
3829 Ty = AT->getElementType();
3830 Ty = Ty.getCanonicalType().getUnqualifiedType();
3831 // Only record types (classes, structs etc.) are ignored.
3832 if (Ty->isRecordType()) {
3833 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
3834 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3835 return true;
3836 }
3837 }
3838 return false;
3839 }
3840
3841 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
3842 StringRef Category) const {
3843 const auto &XRayFilter = getContext().getXRayFilter();
3844 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3845 auto Attr = ImbueAttr::NONE;
3846 if (Loc.isValid())
3847 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3848 if (Attr == ImbueAttr::NONE)
3849 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3850 switch (Attr) {
3851 case ImbueAttr::NONE:
3852 return false;
3853 case ImbueAttr::ALWAYS:
3854 Fn->addFnAttr("function-instrument", "xray-always");
3855 break;
3856 case ImbueAttr::ALWAYS_ARG1:
3857 Fn->addFnAttr("function-instrument", "xray-always");
3858 Fn->addFnAttr("xray-log-args", "1");
3859 break;
3860 case ImbueAttr::NEVER:
3861 Fn->addFnAttr("function-instrument", "xray-never");
3862 break;
3863 }
3864 return true;
3865 }
3866
3867 ProfileList::ExclusionType
3868 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3869 SourceLocation Loc) const {
3870 const auto &ProfileList = getContext().getProfileList();
3871 // If the profile list is empty, then instrument everything.
3872 if (ProfileList.isEmpty())
3873 return ProfileList::Allow;
3874 llvm::driver::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3875 // First, check the function name.
3876 if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3877 return *V;
3878 // Next, check the source location.
3879 if (Loc.isValid())
3880 if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3881 return *V;
3882 // If location is unknown, this may be a compiler-generated function. Assume
3883 // it's located in the main file.
3884 auto &SM = Context.getSourceManager();
3885 if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
3886 if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3887 return *V;
3888 return ProfileList.getDefault(Kind);
3889 }
3890
3891 ProfileList::ExclusionType
3892 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3893 SourceLocation Loc) const {
3894 auto V = isFunctionBlockedByProfileList(Fn, Loc);
3895 if (V != ProfileList::Allow)
3896 return V;
3897
3898 auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3899 if (NumGroups > 1) {
3900 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3901 if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3902 return ProfileList::Skip;
3903 }
3904 return ProfileList::Allow;
3905 }
3906
3907 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3908 // Never defer when EmitAllDecls is specified.
3909 if (LangOpts.EmitAllDecls)
3910 return true;
3911
3912 const auto *VD = dyn_cast<VarDecl>(Global);
3913 if (VD &&
3914 ((CodeGenOpts.KeepPersistentStorageVariables &&
3915 (VD->getStorageDuration() == SD_Static ||
3916 VD->getStorageDuration() == SD_Thread)) ||
3917 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
3918 VD->getType().isConstQualified())))
3919 return true;
3920
3921 return getContext().DeclMustBeEmitted(Global);
3922 }
3923
3924 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3925 // In OpenMP 5.0 variables and function may be marked as
3926 // device_type(host/nohost) and we should not emit them eagerly unless we sure
3927 // that they must be emitted on the host/device. To be sure we need to have
3928 // seen a declare target with an explicit mentioning of the function, we know
3929 // we have if the level of the declare target attribute is -1. Note that we
3930 // check somewhere else if we should emit this at all.
3931 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3932 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3933 OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3934 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3935 return false;
3936 }
3937
3938 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3939 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
3940 // Implicit template instantiations may change linkage if they are later
3941 // explicitly instantiated, so they should not be emitted eagerly.
3942 return false;
3943 // Defer until all versions have been semantically checked.
3944 if (FD->hasAttr<TargetVersionAttr>() && !FD->isMultiVersion())
3945 return false;
3946 // Defer emission of SYCL kernel entry point functions during device
3947 // compilation.
3948 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelEntryPointAttr>())
3949 return false;
3950 }
3951 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3952 if (Context.getInlineVariableDefinitionKind(VD) ==
3953 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
3954 // A definition of an inline constexpr static data member may change
3955 // linkage later if it's redeclared outside the class.
3956 return false;
3957 if (CXX20ModuleInits && VD->getOwningModule() &&
3958 !VD->getOwningModule()->isModuleMapModule()) {
3959 // For CXX20, module-owned initializers need to be deferred, since it is
3960 // not known at this point if they will be run for the current module or
3961 // as part of the initializer for an imported one.
3962 return false;
3963 }
3964 }
3965 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3966 // codegen for global variables, because they may be marked as threadprivate.
3967 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3968 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3969 !Global->getType().isConstantStorage(getContext(), false, false) &&
3970 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3971 return false;
3972
3973 return true;
3974 }
3975
3976 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
3977 StringRef Name = getMangledName(GD);
3978
3979 // The UUID descriptor should be pointer aligned.
3980 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
3981
3982 // Look for an existing global.
3983 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3984 return ConstantAddress(GV, GV->getValueType(), Alignment);
3985
3986 ConstantEmitter Emitter(*this);
3987 llvm::Constant *Init;
3988
3989 APValue &V = GD->getAsAPValue();
3990 if (!V.isAbsent()) {
3991 // If possible, emit the APValue version of the initializer. In particular,
3992 // this gets the type of the constant right.
3993 Init = Emitter.emitForInitializer(
3994 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3995 } else {
3996 // As a fallback, directly construct the constant.
3997 // FIXME: This may get padding wrong under esoteric struct layout rules.
3998 // MSVC appears to create a complete type 'struct __s_GUID' that it
3999 // presumably uses to represent these constants.
4000 MSGuidDecl::Parts Parts = GD->getParts();
4001 llvm::Constant *Fields[4] = {
4002 llvm::ConstantInt::get(Int32Ty, Parts.Part1),
4003 llvm::ConstantInt::get(Int16Ty, Parts.Part2),
4004 llvm::ConstantInt::get(Int16Ty, Parts.Part3),
4005 llvm::ConstantDataArray::getRaw(
4006 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
4007 Int8Ty)};
4008 Init = llvm::ConstantStruct::getAnon(Fields);
4009 }
4010
4011 auto *GV = new llvm::GlobalVariable(
4012 getModule(), Init->getType(),
4013 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
4014 if (supportsCOMDAT())
4015 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4016 setDSOLocal(GV);
4017
4018 if (!V.isAbsent()) {
4019 Emitter.finalize(GV);
4020 return ConstantAddress(GV, GV->getValueType(), Alignment);
4021 }
4022
4023 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
4024 return ConstantAddress(GV, Ty, Alignment);
4025 }
4026
4027 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
4028 const UnnamedGlobalConstantDecl *GCD) {
4029 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
4030
4031 llvm::GlobalVariable **Entry = nullptr;
4032 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4033 if (*Entry)
4034 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
4035
4036 ConstantEmitter Emitter(*this);
4037 llvm::Constant *Init;
4038
4039 const APValue &V = GCD->getValue();
4040
4041 assert(!V.isAbsent());
4042 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
4043 GCD->getType());
4044
4045 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
4046 /*isConstant=*/true,
4047 llvm::GlobalValue::PrivateLinkage, Init,
4048 ".constant");
4049 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4050 GV->setAlignment(Alignment.getAsAlign());
4051
4052 Emitter.finalize(GV);
4053
4054 *Entry = GV;
4055 return ConstantAddress(GV, GV->getValueType(), Alignment);
4056 }
4057
4058 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
4059 const TemplateParamObjectDecl *TPO) {
4060 StringRef Name = getMangledName(TPO);
4061 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
4062
4063 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
4064 return ConstantAddress(GV, GV->getValueType(), Alignment);
4065
4066 ConstantEmitter Emitter(*this);
4067 llvm::Constant *Init = Emitter.emitForInitializer(
4068 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
4069
4070 if (!Init) {
4071 ErrorUnsupported(TPO, "template parameter object");
4072 return ConstantAddress::invalid();
4073 }
4074
4075 llvm::GlobalValue::LinkageTypes Linkage =
4076 isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
4077 ? llvm::GlobalValue::LinkOnceODRLinkage
4078 : llvm::GlobalValue::InternalLinkage;
4079 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
4080 /*isConstant=*/true, Linkage, Init, Name);
4081 setGVProperties(GV, TPO);
4082 if (supportsCOMDAT() && Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
4083 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4084 Emitter.finalize(GV);
4085
4086 return ConstantAddress(GV, GV->getValueType(), Alignment);
4087 }
4088
4089 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
4090 const AliasAttr *AA = VD->getAttr<AliasAttr>();
4091 assert(AA && "No alias?");
4092
4093 CharUnits Alignment = getContext().getDeclAlign(VD);
4094 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
4095
4096 // See if there is already something with the target's name in the module.
4097 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
4098 if (Entry)
4099 return ConstantAddress(Entry, DeclTy, Alignment);
4100
4101 llvm::Constant *Aliasee;
4102 if (isa<llvm::FunctionType>(DeclTy))
4103 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4104 GlobalDecl(cast<FunctionDecl>(VD)),
4105 /*ForVTable=*/false);
4106 else
4107 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
4108 nullptr);
4109
4110 auto *F = cast<llvm::GlobalValue>(Aliasee);
4111 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4112 WeakRefReferences.insert(F);
4113
4114 return ConstantAddress(Aliasee, DeclTy, Alignment);
4115 }
4116
4117 template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
4118 if (!D)
4119 return false;
4120 if (auto *A = D->getAttr<AttrT>())
4121 return A->isImplicit();
4122 return D->isImplicit();
4123 }
4124
4125 static bool shouldSkipAliasEmission(const CodeGenModule &CGM,
4126 const ValueDecl *Global) {
4127 const LangOptions &LangOpts = CGM.getLangOpts();
4128 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4129 return false;
4130
4131 const auto *AA = Global->getAttr<AliasAttr>();
4132 GlobalDecl AliaseeGD;
4133
4134 // Check if the aliasee exists, if the aliasee is not found, skip the alias
4135 // emission. This is executed for both the host and device.
4136 if (!CGM.lookupRepresentativeDecl(AA->getAliasee(), AliaseeGD))
4137 return true;
4138
4139 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4140 if (LangOpts.OpenMPIsTargetDevice)
4141 return !AliaseeDecl ||
4142 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4143
4144 // CUDA / HIP
4145 const bool HasDeviceAttr = Global->hasAttr<CUDADeviceAttr>();
4146 const bool AliaseeHasDeviceAttr =
4147 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4148
4149 if (LangOpts.CUDAIsDevice)
4150 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4151
4152 // CUDA / HIP Host
4153 // we know that the aliasee exists from above, so we know to emit
4154 return false;
4155 }
4156
4157 bool CodeGenModule::shouldEmitCUDAGlobalVar(const VarDecl *Global) const {
4158 assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
4159 // We need to emit host-side 'shadows' for all global
4160 // device-side variables because the CUDA runtime needs their
4161 // size and host-side address in order to provide access to
4162 // their device-side incarnations.
4163 return !LangOpts.CUDAIsDevice || Global->hasAttr<CUDADeviceAttr>() ||
4164 Global->hasAttr<CUDAConstantAttr>() ||
4165 Global->hasAttr<CUDASharedAttr>() ||
4166 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4167 Global->getType()->isCUDADeviceBuiltinTextureType();
4168 }
4169
4170 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
4171 const auto *Global = cast<ValueDecl>(GD.getDecl());
4172
4173 // Weak references don't produce any output by themselves.
4174 if (Global->hasAttr<WeakRefAttr>())
4175 return;
4176
4177 // If this is an alias definition (which otherwise looks like a declaration)
4178 // emit it now.
4179 if (Global->hasAttr<AliasAttr>()) {
4180 if (shouldSkipAliasEmission(*this, Global))
4181 return;
4182 return EmitAliasDefinition(GD);
4183 }
4184
4185 // IFunc like an alias whose value is resolved at runtime by calling resolver.
4186 if (Global->hasAttr<IFuncAttr>())
4187 return emitIFuncDefinition(GD);
4188
4189 // If this is a cpu_dispatch multiversion function, emit the resolver.
4190 if (Global->hasAttr<CPUDispatchAttr>())
4191 return emitCPUDispatchDefinition(GD);
4192
4193 // If this is CUDA, be selective about which declarations we emit.
4194 // Non-constexpr non-lambda implicit host device functions are not emitted
4195 // unless they are used on device side.
4196 if (LangOpts.CUDA) {
4197 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
4198 "Expected Variable or Function");
4199 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
4200 if (!shouldEmitCUDAGlobalVar(VD))
4201 return;
4202 } else if (LangOpts.CUDAIsDevice) {
4203 const auto *FD = dyn_cast<FunctionDecl>(Global);
4204 if ((!Global->hasAttr<CUDADeviceAttr>() ||
4205 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4206 hasImplicitAttr<CUDAHostAttr>(FD) &&
4207 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
4208 !isLambdaCallOperator(FD) &&
4209 !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4210 !Global->hasAttr<CUDAGlobalAttr>() &&
4211 !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) &&
4212 !Global->hasAttr<CUDAHostAttr>()))
4213 return;
4214 // Device-only functions are the only things we skip.
4215 } else if (!Global->hasAttr<CUDAHostAttr>() &&
4216 Global->hasAttr<CUDADeviceAttr>())
4217 return;
4218 }
4219
4220 if (LangOpts.OpenMP) {
4221 // If this is OpenMP, check if it is legal to emit this global normally.
4222 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4223 return;
4224 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
4225 if (MustBeEmitted(Global))
4226 EmitOMPDeclareReduction(DRD);
4227 return;
4228 }
4229 if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
4230 if (MustBeEmitted(Global))
4231 EmitOMPDeclareMapper(DMD);
4232 return;
4233 }
4234 }
4235
4236 // Ignore declarations, they will be emitted on their first use.
4237 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
4238 if (DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()) &&
4239 FD->doesThisDeclarationHaveABody())
4240 addDeferredDeclToEmit(GlobalDecl(FD, KernelReferenceKind::Stub));
4241
4242 // Update deferred annotations with the latest declaration if the function
4243 // function was already used or defined.
4244 if (FD->hasAttr<AnnotateAttr>()) {
4245 StringRef MangledName = getMangledName(GD);
4246 if (GetGlobalValue(MangledName))
4247 DeferredAnnotations[MangledName] = FD;
4248 }
4249
4250 // Forward declarations are emitted lazily on first use.
4251 if (!FD->doesThisDeclarationHaveABody()) {
4252 if (!FD->doesDeclarationForceExternallyVisibleDefinition() &&
4253 (!FD->isMultiVersion() || !getTarget().getTriple().isAArch64()))
4254 return;
4255
4256 StringRef MangledName = getMangledName(GD);
4257
4258 // Compute the function info and LLVM type.
4259 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4260 llvm::Type *Ty = getTypes().GetFunctionType(FI);
4261
4262 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
4263 /*DontDefer=*/false);
4264 return;
4265 }
4266 } else {
4267 const auto *VD = cast<VarDecl>(Global);
4268 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
4269 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
4270 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4271 if (LangOpts.OpenMP) {
4272 // Emit declaration of the must-be-emitted declare target variable.
4273 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4274 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4275
4276 // If this variable has external storage and doesn't require special
4277 // link handling we defer to its canonical definition.
4278 if (VD->hasExternalStorage() &&
4279 Res != OMPDeclareTargetDeclAttr::MT_Link)
4280 return;
4281
4282 bool UnifiedMemoryEnabled =
4283 getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
4284 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4285 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4286 !UnifiedMemoryEnabled) {
4287 (void)GetAddrOfGlobalVar(VD);
4288 } else {
4289 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4290 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4291 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4292 UnifiedMemoryEnabled)) &&
4293 "Link clause or to clause with unified memory expected.");
4294 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
4295 }
4296
4297 return;
4298 }
4299 }
4300 // If this declaration may have caused an inline variable definition to
4301 // change linkage, make sure that it's emitted.
4302 if (Context.getInlineVariableDefinitionKind(VD) ==
4303 ASTContext::InlineVariableDefinitionKind::Strong)
4304 GetAddrOfGlobalVar(VD);
4305 return;
4306 }
4307 }
4308
4309 // Defer code generation to first use when possible, e.g. if this is an inline
4310 // function. If the global must always be emitted, do it eagerly if possible
4311 // to benefit from cache locality.
4312 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
4313 // Emit the definition if it can't be deferred.
4314 EmitGlobalDefinition(GD);
4315 addEmittedDeferredDecl(GD);
4316 return;
4317 }
4318
4319 // If we're deferring emission of a C++ variable with an
4320 // initializer, remember the order in which it appeared in the file.
4321 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
4322 cast<VarDecl>(Global)->hasInit()) {
4323 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
4324 CXXGlobalInits.push_back(nullptr);
4325 }
4326
4327 StringRef MangledName = getMangledName(GD);
4328 if (GetGlobalValue(MangledName) != nullptr) {
4329 // The value has already been used and should therefore be emitted.
4330 addDeferredDeclToEmit(GD);
4331 } else if (MustBeEmitted(Global)) {
4332 // The value must be emitted, but cannot be emitted eagerly.
4333 assert(!MayBeEmittedEagerly(Global));
4334 addDeferredDeclToEmit(GD);
4335 } else {
4336 // Otherwise, remember that we saw a deferred decl with this name. The
4337 // first use of the mangled name will cause it to move into
4338 // DeferredDeclsToEmit.
4339 DeferredDecls[MangledName] = GD;
4340 }
4341 }
4342
4343 // Check if T is a class type with a destructor that's not dllimport.
4344 static bool HasNonDllImportDtor(QualType T) {
4345 if (const auto *RT =
4346 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4347 if (auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4348 RD = RD->getDefinitionOrSelf();
4349 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4350 return true;
4351 }
4352
4353 return false;
4354 }
4355
4356 namespace {
4357 struct FunctionIsDirectlyRecursive
4358 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
4359 const StringRef Name;
4360 const Builtin::Context &BI;
4361 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
4362 : Name(N), BI(C) {}
4363
4364 bool VisitCallExpr(const CallExpr *E) {
4365 const FunctionDecl *FD = E->getDirectCallee();
4366 if (!FD)
4367 return false;
4368 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
4369 if (Attr && Name == Attr->getLabel())
4370 return true;
4371 unsigned BuiltinID = FD->getBuiltinID();
4372 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
4373 return false;
4374 std::string BuiltinNameStr = BI.getName(BuiltinID);
4375 StringRef BuiltinName = BuiltinNameStr;
4376 return BuiltinName.consume_front("__builtin_") && Name == BuiltinName;
4377 }
4378
4379 bool VisitStmt(const Stmt *S) {
4380 for (const Stmt *Child : S->children())
4381 if (Child && this->Visit(Child))
4382 return true;
4383 return false;
4384 }
4385 };
4386
4387 // Make sure we're not referencing non-imported vars or functions.
4388 struct DLLImportFunctionVisitor
4389 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4390 bool SafeToInline = true;
4391
4392 bool shouldVisitImplicitCode() const { return true; }
4393
4394 bool VisitVarDecl(VarDecl *VD) {
4395 if (VD->getTLSKind()) {
4396 // A thread-local variable cannot be imported.
4397 SafeToInline = false;
4398 return SafeToInline;
4399 }
4400
4401 // A variable definition might imply a destructor call.
4402 if (VD->isThisDeclarationADefinition())
4403 SafeToInline = !HasNonDllImportDtor(VD->getType());
4404
4405 return SafeToInline;
4406 }
4407
4408 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4409 if (const auto *D = E->getTemporary()->getDestructor())
4410 SafeToInline = D->hasAttr<DLLImportAttr>();
4411 return SafeToInline;
4412 }
4413
4414 bool VisitDeclRefExpr(DeclRefExpr *E) {
4415 ValueDecl *VD = E->getDecl();
4416 if (isa<FunctionDecl>(VD))
4417 SafeToInline = VD->hasAttr<DLLImportAttr>();
4418 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
4419 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
4420 return SafeToInline;
4421 }
4422
4423 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4424 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
4425 return SafeToInline;
4426 }
4427
4428 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4429 CXXMethodDecl *M = E->getMethodDecl();
4430 if (!M) {
4431 // Call through a pointer to member function. This is safe to inline.
4432 SafeToInline = true;
4433 } else {
4434 SafeToInline = M->hasAttr<DLLImportAttr>();
4435 }
4436 return SafeToInline;
4437 }
4438
4439 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4440 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
4441 return SafeToInline;
4442 }
4443
4444 bool VisitCXXNewExpr(CXXNewExpr *E) {
4445 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
4446 return SafeToInline;
4447 }
4448 };
4449 }
4450
4451 // isTriviallyRecursive - Check if this function calls another
4452 // decl that, because of the asm attribute or the other decl being a builtin,
4453 // ends up pointing to itself.
4454 bool
4455 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
4456 StringRef Name;
4457 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4458 // asm labels are a special kind of mangling we have to support.
4459 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
4460 if (!Attr)
4461 return false;
4462 Name = Attr->getLabel();
4463 } else {
4464 Name = FD->getName();
4465 }
4466
4467 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4468 const Stmt *Body = FD->getBody();
4469 return Body ? Walker.Visit(Body) : false;
4470 }
4471
4472 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4473 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
4474 return true;
4475
4476 const auto *F = cast<FunctionDecl>(GD.getDecl());
4477 // Inline builtins declaration must be emitted. They often are fortified
4478 // functions.
4479 if (F->isInlineBuiltinDeclaration())
4480 return true;
4481
4482 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4483 return false;
4484
4485 // We don't import function bodies from other named module units since that
4486 // behavior may break ABI compatibility of the current unit.
4487 if (const Module *M = F->getOwningModule();
4488 M && M->getTopLevelModule()->isNamedModule() &&
4489 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4490 // There are practices to mark template member function as always-inline
4491 // and mark the template as extern explicit instantiation but not give
4492 // the definition for member function. So we have to emit the function
4493 // from explicitly instantiation with always-inline.
4494 //
4495 // See https://github.com/llvm/llvm-project/issues/86893 for details.
4496 //
4497 // TODO: Maybe it is better to give it a warning if we call a non-inline
4498 // function from other module units which is marked as always-inline.
4499 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4500 return false;
4501 }
4502 }
4503
4504 if (F->hasAttr<NoInlineAttr>())
4505 return false;
4506
4507 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4508 // Check whether it would be safe to inline this dllimport function.
4509 DLLImportFunctionVisitor Visitor;
4510 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
4511 if (!Visitor.SafeToInline)
4512 return false;
4513
4514 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4515 // Implicit destructor invocations aren't captured in the AST, so the
4516 // check above can't see them. Check for them manually here.
4517 for (const Decl *Member : Dtor->getParent()->decls())
4518 if (isa<FieldDecl>(Member))
4519 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
4520 return false;
4521 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4522 if (HasNonDllImportDtor(B.getType()))
4523 return false;
4524 }
4525 }
4526
4527 // PR9614. Avoid cases where the source code is lying to us. An available
4528 // externally function should have an equivalent function somewhere else,
4529 // but a function that calls itself through asm label/`__builtin_` trickery is
4530 // clearly not equivalent to the real implementation.
4531 // This happens in glibc's btowc and in some configure checks.
4532 return !isTriviallyRecursive(F);
4533 }
4534
4535 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4536 return CodeGenOpts.OptimizationLevel > 0;
4537 }
4538
4539 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4540 llvm::GlobalValue *GV) {
4541 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4542
4543 if (FD->isCPUSpecificMultiVersion()) {
4544 auto *Spec = FD->getAttr<CPUSpecificAttr>();
4545 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
4546 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4547 } else if (auto *TC = FD->getAttr<TargetClonesAttr>()) {
4548 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4549 if (TC->isFirstOfVersion(I))
4550 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4551 } else
4552 EmitGlobalFunctionDefinition(GD, GV);
4553
4554 // Ensure that the resolver function is also emitted.
4555 if (FD->isTargetVersionMultiVersion() || FD->isTargetClonesMultiVersion()) {
4556 // On AArch64 defer the resolver emission until the entire TU is processed.
4557 if (getTarget().getTriple().isAArch64())
4558 AddDeferredMultiVersionResolverToEmit(GD);
4559 else
4560 GetOrCreateMultiVersionResolver(GD);
4561 }
4562 }
4563
4564 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4565 const auto *D = cast<ValueDecl>(GD.getDecl());
4566
4567 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
4568 Context.getSourceManager(),
4569 "Generating code for declaration");
4570
4571 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4572 // At -O0, don't generate IR for functions with available_externally
4573 // linkage.
4574 if (!shouldEmitFunction(GD))
4575 return;
4576
4577 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
4578 std::string Name;
4579 llvm::raw_string_ostream OS(Name);
4580 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
4581 /*Qualified=*/true);
4582 return Name;
4583 });
4584
4585 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
4586 // Make sure to emit the definition(s) before we emit the thunks.
4587 // This is necessary for the generation of certain thunks.
4588 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4589 ABI->emitCXXStructor(GD);
4590 else if (FD->isMultiVersion())
4591 EmitMultiVersionFunctionDefinition(GD, GV);
4592 else
4593 EmitGlobalFunctionDefinition(GD, GV);
4594
4595 if (Method->isVirtual())
4596 getVTables().EmitThunks(GD);
4597
4598 return;
4599 }
4600
4601 if (FD->isMultiVersion())
4602 return EmitMultiVersionFunctionDefinition(GD, GV);
4603 return EmitGlobalFunctionDefinition(GD, GV);
4604 }
4605
4606 if (const auto *VD = dyn_cast<VarDecl>(D))
4607 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4608
4609 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
4610 }
4611
4612 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4613 llvm::Function *NewFn);
4614
4615 static llvm::APInt
4616 getFMVPriority(const TargetInfo &TI,
4617 const CodeGenFunction::FMVResolverOption &RO) {
4618 llvm::SmallVector<StringRef, 8> Features{RO.Features};
4619 if (RO.Architecture)
4620 Features.push_back(*RO.Architecture);
4621 return TI.getFMVPriority(Features);
4622 }
4623
4624 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
4625 // TU can forward declare the function without causing problems. Particularly
4626 // in the cases of CPUDispatch, this causes issues. This also makes sure we
4627 // work with internal linkage functions, so that the same function name can be
4628 // used with internal linkage in multiple TUs.
4629 static llvm::GlobalValue::LinkageTypes
4630 getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD) {
4631 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4632 if (FD->getFormalLinkage() == Linkage::Internal)
4633 return llvm::GlobalValue::InternalLinkage;
4634 return llvm::GlobalValue::WeakODRLinkage;
4635 }
4636
4637 void CodeGenModule::emitMultiVersionFunctions() {
4638 std::vector<GlobalDecl> MVFuncsToEmit;
4639 MultiVersionFuncs.swap(MVFuncsToEmit);
4640 for (GlobalDecl GD : MVFuncsToEmit) {
4641 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4642 assert(FD && "Expected a FunctionDecl");
4643
4644 auto createFunction = [&](const FunctionDecl *Decl, unsigned MVIdx = 0) {
4645 GlobalDecl CurGD{Decl->isDefined() ? Decl->getDefinition() : Decl, MVIdx};
4646 StringRef MangledName = getMangledName(CurGD);
4647 llvm::Constant *Func = GetGlobalValue(MangledName);
4648 if (!Func) {
4649 if (Decl->isDefined()) {
4650 EmitGlobalFunctionDefinition(CurGD, nullptr);
4651 Func = GetGlobalValue(MangledName);
4652 } else {
4653 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(CurGD);
4654 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4655 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
4656 /*DontDefer=*/false, ForDefinition);
4657 }
4658 assert(Func && "This should have just been created");
4659 }
4660 return cast<llvm::Function>(Func);
4661 };
4662
4663 // For AArch64, a resolver is only emitted if a function marked with
4664 // target_version("default")) or target_clones("default") is defined
4665 // in this TU. For other architectures it is always emitted.
4666 bool ShouldEmitResolver = !getTarget().getTriple().isAArch64();
4667 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4668 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
4669
4670 getContext().forEachMultiversionedFunctionVersion(
4671 FD, [&](const FunctionDecl *CurFD) {
4672 llvm::SmallVector<StringRef, 8> Feats;
4673 bool IsDefined = CurFD->getDefinition() != nullptr;
4674
4675 if (const auto *TA = CurFD->getAttr<TargetAttr>()) {
4676 assert(getTarget().getTriple().isX86() && "Unsupported target");
4677 TA->getX86AddedFeatures(Feats);
4678 llvm::Function *Func = createFunction(CurFD);
4679 DeclMap.insert({Func, CurFD});
4680 Options.emplace_back(Func, Feats, TA->getX86Architecture());
4681 } else if (const auto *TVA = CurFD->getAttr<TargetVersionAttr>()) {
4682 if (TVA->isDefaultVersion() && IsDefined)
4683 ShouldEmitResolver = true;
4684 llvm::Function *Func = createFunction(CurFD);
4685 DeclMap.insert({Func, CurFD});
4686 char Delim = getTarget().getTriple().isAArch64() ? '+' : ',';
4687 TVA->getFeatures(Feats, Delim);
4688 Options.emplace_back(Func, Feats);
4689 } else if (const auto *TC = CurFD->getAttr<TargetClonesAttr>()) {
4690 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4691 if (!TC->isFirstOfVersion(I))
4692 continue;
4693 if (TC->isDefaultVersion(I) && IsDefined)
4694 ShouldEmitResolver = true;
4695 llvm::Function *Func = createFunction(CurFD, I);
4696 DeclMap.insert({Func, CurFD});
4697 Feats.clear();
4698 if (getTarget().getTriple().isX86()) {
4699 TC->getX86Feature(Feats, I);
4700 Options.emplace_back(Func, Feats, TC->getX86Architecture(I));
4701 } else {
4702 char Delim = getTarget().getTriple().isAArch64() ? '+' : ',';
4703 TC->getFeatures(Feats, I, Delim);
4704 Options.emplace_back(Func, Feats);
4705 }
4706 }
4707 } else
4708 llvm_unreachable("unexpected MultiVersionKind");
4709 });
4710
4711 if (!ShouldEmitResolver)
4712 continue;
4713
4714 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4715 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4716 ResolverConstant = IFunc->getResolver();
4717 if (FD->isTargetClonesMultiVersion() &&
4718 !getTarget().getTriple().isAArch64()) {
4719 std::string MangledName = getMangledNameImpl(
4720 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4721 if (!GetGlobalValue(MangledName + ".ifunc")) {
4722 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4723 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4724 // In prior versions of Clang, the mangling for ifuncs incorrectly
4725 // included an .ifunc suffix. This alias is generated for backward
4726 // compatibility. It is deprecated, and may be removed in the future.
4727 auto *Alias = llvm::GlobalAlias::create(
4728 DeclTy, 0, getMultiversionLinkage(*this, GD),
4729 MangledName + ".ifunc", IFunc, &getModule());
4730 SetCommonAttributes(FD, Alias);
4731 }
4732 }
4733 }
4734 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4735
4736 const TargetInfo &TI = getTarget();
4737 llvm::stable_sort(
4738 Options, [&TI](const CodeGenFunction::FMVResolverOption &LHS,
4739 const CodeGenFunction::FMVResolverOption &RHS) {
4740 return getFMVPriority(TI, LHS).ugt(getFMVPriority(TI, RHS));
4741 });
4742
4743 // Diagnose unreachable function versions.
4744 if (getTarget().getTriple().isAArch64()) {
4745 for (auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
4746 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
4747 if (std::any_of(Options.begin(), I, [RHS](auto RO) {
4748 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
4749 return LHS.isSubsetOf(RHS);
4750 })) {
4751 Diags.Report(DeclMap[I->Function]->getLocation(),
4752 diag::warn_unreachable_version)
4753 << I->Function->getName();
4754 assert(I->Function->user_empty() && "unexpected users");
4755 I->Function->eraseFromParent();
4756 I->Function = nullptr;
4757 }
4758 }
4759 }
4760 CodeGenFunction CGF(*this);
4761 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4762
4763 setMultiVersionResolverAttributes(ResolverFunc, GD);
4764 if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT())
4765 ResolverFunc->setComdat(
4766 getModule().getOrInsertComdat(ResolverFunc->getName()));
4767 }
4768
4769 // Ensure that any additions to the deferred decls list caused by emitting a
4770 // variant are emitted. This can happen when the variant itself is inline and
4771 // calls a function without linkage.
4772 if (!MVFuncsToEmit.empty())
4773 EmitDeferred();
4774
4775 // Ensure that any additions to the multiversion funcs list from either the
4776 // deferred decls or the multiversion functions themselves are emitted.
4777 if (!MultiVersionFuncs.empty())
4778 emitMultiVersionFunctions();
4779 }
4780
4781 static void replaceDeclarationWith(llvm::GlobalValue *Old,
4782 llvm::Constant *New) {
4783 assert(cast<llvm::Function>(Old)->isDeclaration() && "Not a declaration");
4784 New->takeName(Old);
4785 Old->replaceAllUsesWith(New);
4786 Old->eraseFromParent();
4787 }
4788
4789 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4790 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4791 assert(FD && "Not a FunctionDecl?");
4792 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
4793 const auto *DD = FD->getAttr<CPUDispatchAttr>();
4794 assert(DD && "Not a cpu_dispatch Function?");
4795
4796 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4797 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4798
4799 StringRef ResolverName = getMangledName(GD);
4800 UpdateMultiVersionNames(GD, FD, ResolverName);
4801
4802 llvm::Type *ResolverType;
4803 GlobalDecl ResolverGD;
4804 if (getTarget().supportsIFunc()) {
4805 ResolverType = llvm::FunctionType::get(
4806 llvm::PointerType::get(getLLVMContext(),
4807 getTypes().getTargetAddressSpace(FD->getType())),
4808 false);
4809 }
4810 else {
4811 ResolverType = DeclTy;
4812 ResolverGD = GD;
4813 }
4814
4815 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4816 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4817
4818 if (supportsCOMDAT())
4819 ResolverFunc->setComdat(
4820 getModule().getOrInsertComdat(ResolverFunc->getName()));
4821
4822 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4823 const TargetInfo &Target = getTarget();
4824 unsigned Index = 0;
4825 for (const IdentifierInfo *II : DD->cpus()) {
4826 // Get the name of the target function so we can look it up/create it.
4827 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
4828 getCPUSpecificMangling(*this, II->getName());
4829
4830 llvm::Constant *Func = GetGlobalValue(MangledName);
4831
4832 if (!Func) {
4833 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4834 if (ExistingDecl.getDecl() &&
4835 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
4836 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
4837 Func = GetGlobalValue(MangledName);
4838 } else {
4839 if (!ExistingDecl.getDecl())
4840 ExistingDecl = GD.getWithMultiVersionIndex(Index);
4841
4842 Func = GetOrCreateLLVMFunction(
4843 MangledName, DeclTy, ExistingDecl,
4844 /*ForVTable=*/false, /*DontDefer=*/true,
4845 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
4846 }
4847 }
4848
4849 llvm::SmallVector<StringRef, 32> Features;
4850 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4851 llvm::transform(Features, Features.begin(),
4852 [](StringRef Str) { return Str.substr(1); });
4853 llvm::erase_if(Features, [&Target](StringRef Feat) {
4854 return !Target.validateCpuSupports(Feat);
4855 });
4856 Options.emplace_back(cast<llvm::Function>(Func), Features);
4857 ++Index;
4858 }
4859
4860 llvm::stable_sort(Options, [](const CodeGenFunction::FMVResolverOption &LHS,
4861 const CodeGenFunction::FMVResolverOption &RHS) {
4862 return llvm::X86::getCpuSupportsMask(LHS.Features) >
4863 llvm::X86::getCpuSupportsMask(RHS.Features);
4864 });
4865
4866 // If the list contains multiple 'default' versions, such as when it contains
4867 // 'pentium' and 'generic', don't emit the call to the generic one (since we
4868 // always run on at least a 'pentium'). We do this by deleting the 'least
4869 // advanced' (read, lowest mangling letter).
4870 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
4871 (Options.end() - 2)->Features),
4872 [](auto X) { return X == 0; })) {
4873 StringRef LHSName = (Options.end() - 2)->Function->getName();
4874 StringRef RHSName = (Options.end() - 1)->Function->getName();
4875 if (LHSName.compare(RHSName) < 0)
4876 Options.erase(Options.end() - 2);
4877 else
4878 Options.erase(Options.end() - 1);
4879 }
4880
4881 CodeGenFunction CGF(*this);
4882 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4883 setMultiVersionResolverAttributes(ResolverFunc, GD);
4884
4885 if (getTarget().supportsIFunc()) {
4886 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
4887 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4888 unsigned AS = IFunc->getType()->getPointerAddressSpace();
4889
4890 // Fix up function declarations that were created for cpu_specific before
4891 // cpu_dispatch was known
4892 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4893 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS, Linkage, "",
4894 ResolverFunc, &getModule());
4895 replaceDeclarationWith(IFunc, GI);
4896 IFunc = GI;
4897 }
4898
4899 std::string AliasName = getMangledNameImpl(
4900 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4901 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4902 if (!AliasFunc) {
4903 auto *GA = llvm::GlobalAlias::create(DeclTy, AS, Linkage, AliasName,
4904 IFunc, &getModule());
4905 SetCommonAttributes(GD, GA);
4906 }
4907 }
4908 }
4909
4910 /// Adds a declaration to the list of multi version functions if not present.
4911 void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
4912 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4913 assert(FD && "Not a FunctionDecl?");
4914
4915 if (FD->isTargetVersionMultiVersion() || FD->isTargetClonesMultiVersion()) {
4916 std::string MangledName =
4917 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4918 if (!DeferredResolversToEmit.insert(MangledName).second)
4919 return;
4920 }
4921 MultiVersionFuncs.push_back(GD);
4922 }
4923
4924 /// If a dispatcher for the specified mangled name is not in the module, create
4925 /// and return it. The dispatcher is either an llvm Function with the specified
4926 /// type, or a global ifunc.
4927 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
4928 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4929 assert(FD && "Not a FunctionDecl?");
4930
4931 std::string MangledName =
4932 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4933
4934 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
4935 // a separate resolver).
4936 std::string ResolverName = MangledName;
4937 if (getTarget().supportsIFunc()) {
4938 switch (FD->getMultiVersionKind()) {
4939 case MultiVersionKind::None:
4940 llvm_unreachable("unexpected MultiVersionKind::None for resolver");
4941 case MultiVersionKind::Target:
4942 case MultiVersionKind::CPUSpecific:
4943 case MultiVersionKind::CPUDispatch:
4944 ResolverName += ".ifunc";
4945 break;
4946 case MultiVersionKind::TargetClones:
4947 case MultiVersionKind::TargetVersion:
4948 break;
4949 }
4950 } else if (FD->isTargetMultiVersion()) {
4951 ResolverName += ".resolver";
4952 }
4953
4954 bool ShouldReturnIFunc =
4955 getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion();
4956
4957 // If the resolver has already been created, just return it. This lookup may
4958 // yield a function declaration instead of a resolver on AArch64. That is
4959 // because we didn't know whether a resolver will be generated when we first
4960 // encountered a use of the symbol named after this resolver. Therefore,
4961 // targets which support ifuncs should not return here unless we actually
4962 // found an ifunc.
4963 llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName);
4964 if (ResolverGV && (isa<llvm::GlobalIFunc>(ResolverGV) || !ShouldReturnIFunc))
4965 return ResolverGV;
4966
4967 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4968 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4969
4970 // The resolver needs to be created. For target and target_clones, defer
4971 // creation until the end of the TU.
4972 if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion())
4973 AddDeferredMultiVersionResolverToEmit(GD);
4974
4975 // For cpu_specific, don't create an ifunc yet because we don't know if the
4976 // cpu_dispatch will be emitted in this translation unit.
4977 if (ShouldReturnIFunc) {
4978 unsigned AS = getTypes().getTargetAddressSpace(FD->getType());
4979 llvm::Type *ResolverType = llvm::FunctionType::get(
4980 llvm::PointerType::get(getLLVMContext(), AS), false);
4981 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4982 MangledName + ".resolver", ResolverType, GlobalDecl{},
4983 /*ForVTable=*/false);
4984 llvm::GlobalIFunc *GIF =
4985 llvm::GlobalIFunc::create(DeclTy, AS, getMultiversionLinkage(*this, GD),
4986 "", Resolver, &getModule());
4987 GIF->setName(ResolverName);
4988 SetCommonAttributes(FD, GIF);
4989 if (ResolverGV)
4990 replaceDeclarationWith(ResolverGV, GIF);
4991 return GIF;
4992 }
4993
4994 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4995 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
4996 assert(isa<llvm::GlobalValue>(Resolver) && !ResolverGV &&
4997 "Resolver should be created for the first time");
4998 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
4999 return Resolver;
5000 }
5001
5002 void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5003 GlobalDecl GD) {
5004 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.getDecl());
5005 Resolver->setLinkage(getMultiversionLinkage(*this, GD));
5006
5007 // Function body has to be emitted before calling setGlobalVisibility
5008 // for Resolver to be considered as definition.
5009 setGlobalVisibility(Resolver, D);
5010
5011 setDSOLocal(Resolver);
5012
5013 // The resolver must be exempt from sanitizer instrumentation, as it can run
5014 // before the sanitizer is initialized.
5015 // (https://github.com/llvm/llvm-project/issues/163369)
5016 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5017
5018 // Set the default target-specific attributes, such as PAC and BTI ones on
5019 // AArch64. Not passing Decl to prevent setting unrelated attributes,
5020 // as Resolver can be shared by multiple declarations.
5021 // FIXME Some targets may require a non-null D to set some attributes
5022 // (such as "stackrealign" on X86, even when it is requested via
5023 // "-mstackrealign" command line option).
5024 getTargetCodeGenInfo().setTargetAttributes(/*D=*/nullptr, Resolver, *this);
5025 }
5026
5027 bool CodeGenModule::shouldDropDLLAttribute(const Decl *D,
5028 const llvm::GlobalValue *GV) const {
5029 auto SC = GV->getDLLStorageClass();
5030 if (SC == llvm::GlobalValue::DefaultStorageClass)
5031 return false;
5032 const Decl *MRD = D->getMostRecentDecl();
5033 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5034 !MRD->hasAttr<DLLImportAttr>()) ||
5035 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5036 !MRD->hasAttr<DLLExportAttr>())) &&
5037 !shouldMapVisibilityToDLLExport(cast<NamedDecl>(MRD)));
5038 }
5039
5040 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
5041 /// module, create and return an llvm Function with the specified type. If there
5042 /// is something in the module with the specified name, return it potentially
5043 /// bitcasted to the right type.
5044 ///
5045 /// If D is non-null, it specifies a decl that correspond to this. This is used
5046 /// to set the attributes on the function when it is first created.
5047 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5048 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
5049 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
5050 ForDefinition_t IsForDefinition) {
5051 const Decl *D = GD.getDecl();
5052
5053 std::string NameWithoutMultiVersionMangling;
5054 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5055 // For the device mark the function as one that should be emitted.
5056 if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5057 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
5058 !DontDefer && !IsForDefinition) {
5059 if (const FunctionDecl *FDDef = FD->getDefinition()) {
5060 GlobalDecl GDDef;
5061 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5062 GDDef = GlobalDecl(CD, GD.getCtorType());
5063 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5064 GDDef = GlobalDecl(DD, GD.getDtorType());
5065 else
5066 GDDef = GlobalDecl(FDDef);
5067 EmitGlobal(GDDef);
5068 }
5069 }
5070
5071 // Any attempts to use a MultiVersion function should result in retrieving
5072 // the iFunc instead. Name Mangling will handle the rest of the changes.
5073 if (FD->isMultiVersion()) {
5074 UpdateMultiVersionNames(GD, FD, MangledName);
5075 if (!IsForDefinition) {
5076 // On AArch64 we do not immediatelly emit an ifunc resolver when a
5077 // function is used. Instead we defer the emission until we see a
5078 // default definition. In the meantime we just reference the symbol
5079 // without FMV mangling (it may or may not be replaced later).
5080 if (getTarget().getTriple().isAArch64()) {
5081 AddDeferredMultiVersionResolverToEmit(GD);
5082 NameWithoutMultiVersionMangling = getMangledNameImpl(
5083 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
5084 } else
5085 return GetOrCreateMultiVersionResolver(GD);
5086 }
5087 }
5088 }
5089
5090 if (!NameWithoutMultiVersionMangling.empty())
5091 MangledName = NameWithoutMultiVersionMangling;
5092
5093 // Lookup the entry, lazily creating it if necessary.
5094 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5095 if (Entry) {
5096 if (WeakRefReferences.erase(Entry)) {
5097 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5098 if (FD && !FD->hasAttr<WeakAttr>())
5099 Entry->setLinkage(llvm::Function::ExternalLinkage);
5100 }
5101
5102 // Handle dropped DLL attributes.
5103 if (D && shouldDropDLLAttribute(D, Entry)) {
5104 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5105 setDSOLocal(Entry);
5106 }
5107
5108 // If there are two attempts to define the same mangled name, issue an
5109 // error.
5110 if (IsForDefinition && !Entry->isDeclaration()) {
5111 GlobalDecl OtherGD;
5112 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
5113 // to make sure that we issue an error only once.
5114 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
5115 (GD.getCanonicalDecl().getDecl() !=
5116 OtherGD.getCanonicalDecl().getDecl()) &&
5117 DiagnosedConflictingDefinitions.insert(GD).second) {
5118 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
5119 << MangledName;
5120 getDiags().Report(OtherGD.getDecl()->getLocation(),
5121 diag::note_previous_definition);
5122 }
5123 }
5124
5125 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
5126 (Entry->getValueType() == Ty)) {
5127 return Entry;
5128 }
5129
5130 // Make sure the result is of the correct type.
5131 // (If function is requested for a definition, we always need to create a new
5132 // function, not just return a bitcast.)
5133 if (!IsForDefinition)
5134 return Entry;
5135 }
5136
5137 // This function doesn't have a complete type (for example, the return
5138 // type is an incomplete struct). Use a fake type instead, and make
5139 // sure not to try to set attributes.
5140 bool IsIncompleteFunction = false;
5141
5142 llvm::FunctionType *FTy;
5143 if (isa<llvm::FunctionType>(Ty)) {
5144 FTy = cast<llvm::FunctionType>(Ty);
5145 } else {
5146 FTy = llvm::FunctionType::get(VoidTy, false);
5147 IsIncompleteFunction = true;
5148 }
5149
5150 llvm::Function *F =
5151 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5152 Entry ? StringRef() : MangledName, &getModule());
5153
5154 // Store the declaration associated with this function so it is potentially
5155 // updated by further declarations or definitions and emitted at the end.
5156 if (D && D->hasAttr<AnnotateAttr>())
5157 DeferredAnnotations[MangledName] = cast<ValueDecl>(D);
5158
5159 // If we already created a function with the same mangled name (but different
5160 // type) before, take its name and add it to the list of functions to be
5161 // replaced with F at the end of CodeGen.
5162 //
5163 // This happens if there is a prototype for a function (e.g. "int f()") and
5164 // then a definition of a different type (e.g. "int f(int x)").
5165 if (Entry) {
5166 F->takeName(Entry);
5167
5168 // This might be an implementation of a function without a prototype, in
5169 // which case, try to do special replacement of calls which match the new
5170 // prototype. The really key thing here is that we also potentially drop
5171 // arguments from the call site so as to make a direct call, which makes the
5172 // inliner happier and suppresses a number of optimizer warnings (!) about
5173 // dropping arguments.
5174 if (!Entry->use_empty()) {
5175 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
5176 Entry->removeDeadConstantUsers();
5177 }
5178
5179 addGlobalValReplacement(Entry, F);
5180 }
5181
5182 assert(F->getName() == MangledName && "name was uniqued!");
5183 if (D)
5184 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5185 if (ExtraAttrs.hasFnAttrs()) {
5186 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5187 F->addFnAttrs(B);
5188 }
5189
5190 if (!DontDefer) {
5191 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
5192 // each other bottoming out with the base dtor. Therefore we emit non-base
5193 // dtors on usage, even if there is no dtor definition in the TU.
5194 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5195 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
5196 GD.getDtorType()))
5197 addDeferredDeclToEmit(GD);
5198
5199 // This is the first use or definition of a mangled name. If there is a
5200 // deferred decl with this name, remember that we need to emit it at the end
5201 // of the file.
5202 auto DDI = DeferredDecls.find(MangledName);
5203 if (DDI != DeferredDecls.end()) {
5204 // Move the potentially referenced deferred decl to the
5205 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
5206 // don't need it anymore).
5207 addDeferredDeclToEmit(DDI->second);
5208 DeferredDecls.erase(DDI);
5209
5210 // Otherwise, there are cases we have to worry about where we're
5211 // using a declaration for which we must emit a definition but where
5212 // we might not find a top-level definition:
5213 // - member functions defined inline in their classes
5214 // - friend functions defined inline in some class
5215 // - special member functions with implicit definitions
5216 // If we ever change our AST traversal to walk into class methods,
5217 // this will be unnecessary.
5218 //
5219 // We also don't emit a definition for a function if it's going to be an
5220 // entry in a vtable, unless it's already marked as used.
5221 } else if (getLangOpts().CPlusPlus && D) {
5222 // Look for a declaration that's lexically in a record.
5223 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
5224 FD = FD->getPreviousDecl()) {
5225 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
5226 if (FD->doesThisDeclarationHaveABody()) {
5227 addDeferredDeclToEmit(GD.getWithDecl(FD));
5228 break;
5229 }
5230 }
5231 }
5232 }
5233 }
5234
5235 // Make sure the result is of the requested type.
5236 if (!IsIncompleteFunction) {
5237 assert(F->getFunctionType() == Ty);
5238 return F;
5239 }
5240
5241 return F;
5242 }
5243
5244 /// GetAddrOfFunction - Return the address of the given function. If Ty is
5245 /// non-null, then this function will use the specified type if it has to
5246 /// create it (this occurs when we see a definition of the function).
5247 llvm::Constant *
5248 CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
5249 bool DontDefer,
5250 ForDefinition_t IsForDefinition) {
5251 // If there was no specific requested type, just convert it now.
5252 if (!Ty) {
5253 const auto *FD = cast<FunctionDecl>(GD.getDecl());
5254 Ty = getTypes().ConvertType(FD->getType());
5255 if (DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()) &&
5256 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
5257 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5258 Ty = getTypes().GetFunctionType(FI);
5259 }
5260 }
5261
5262 // Devirtualized destructor calls may come through here instead of via
5263 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
5264 // of the complete destructor when necessary.
5265 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
5266 if (getTarget().getCXXABI().isMicrosoft() &&
5267 GD.getDtorType() == Dtor_Complete &&
5268 DD->getParent()->getNumVBases() == 0)
5269 GD = GlobalDecl(DD, Dtor_Base);
5270 }
5271
5272 StringRef MangledName = getMangledName(GD);
5273 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5274 /*IsThunk=*/false, llvm::AttributeList(),
5275 IsForDefinition);
5276 // Returns kernel handle for HIP kernel stub function.
5277 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5278 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
5279 auto *Handle = getCUDARuntime().getKernelHandle(
5280 cast<llvm::Function>(F->stripPointerCasts()), GD);
5281 if (IsForDefinition)
5282 return F;
5283 return Handle;
5284 }
5285 return F;
5286 }
5287
5288 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
5289 llvm::GlobalValue *F =
5290 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
5291
5292 return llvm::NoCFIValue::get(F);
5293 }
5294
5295 static const FunctionDecl *
5296 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
5297 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
5298 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5299
5300 IdentifierInfo &CII = C.Idents.get(Name);
5301 for (const auto *Result : DC->lookup(&CII))
5302 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
5303 return FD;
5304
5305 if (!C.getLangOpts().CPlusPlus)
5306 return nullptr;
5307
5308 // Demangle the premangled name from getTerminateFn()
5309 IdentifierInfo &CXXII =
5310 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
5311 ? C.Idents.get("terminate")
5312 : C.Idents.get(Name);
5313
5314 for (const auto &N : {"__cxxabiv1", "std"}) {
5315 IdentifierInfo &NS = C.Idents.get(N);
5316 for (const auto *Result : DC->lookup(&NS)) {
5317 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
5318 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
5319 for (const auto *Result : LSD->lookup(&NS))
5320 if ((ND = dyn_cast<NamespaceDecl>(Result)))
5321 break;
5322
5323 if (ND)
5324 for (const auto *Result : ND->lookup(&CXXII))
5325 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
5326 return FD;
5327 }
5328 }
5329
5330 return nullptr;
5331 }
5332
5333 static void setWindowsItaniumDLLImport(CodeGenModule &CGM, bool Local,
5334 llvm::Function *F, StringRef Name) {
5335 // In Windows Itanium environments, try to mark runtime functions
5336 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
5337 // will link their standard library statically or dynamically. Marking
5338 // functions imported when they are not imported can cause linker errors
5339 // and warnings.
5340 if (!Local && CGM.getTriple().isWindowsItaniumEnvironment() &&
5341 !CGM.getCodeGenOpts().LTOVisibilityPublicStd) {
5342 const FunctionDecl *FD = GetRuntimeFunctionDecl(CGM.getContext(), Name);
5343 if (!FD || FD->hasAttr<DLLImportAttr>()) {
5344 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5345 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5346 }
5347 }
5348 }
5349
5350 llvm::FunctionCallee CodeGenModule::CreateRuntimeFunction(
5351 QualType ReturnTy, ArrayRef<QualType> ArgTys, StringRef Name,
5352 llvm::AttributeList ExtraAttrs, bool Local, bool AssumeConvergent) {
5353 if (AssumeConvergent) {
5354 ExtraAttrs =
5355 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5356 }
5357
5358 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5359 FunctionProtoType::ExtProtoInfo());
5360 const CGFunctionInfo &Info = getTypes().arrangeFreeFunctionType(
5361 Context.getCanonicalType(FTy).castAs<FunctionProtoType>());
5362 auto *ConvTy = getTypes().GetFunctionType(Info);
5363 llvm::Constant *C = GetOrCreateLLVMFunction(
5364 Name, ConvTy, GlobalDecl(), /*ForVTable=*/false,
5365 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
5366
5367 if (auto *F = dyn_cast<llvm::Function>(C)) {
5368 if (F->empty()) {
5369 SetLLVMFunctionAttributes(GlobalDecl(), Info, F, /*IsThunk*/ false);
5370 // FIXME: Set calling-conv properly in ExtProtoInfo
5371 F->setCallingConv(getRuntimeCC());
5372 setWindowsItaniumDLLImport(*this, Local, F, Name);
5373 setDSOLocal(F);
5374 }
5375 }
5376 return {ConvTy, C};
5377 }
5378
5379 /// CreateRuntimeFunction - Create a new runtime function with the specified
5380 /// type and name.
5381 llvm::FunctionCallee
5382 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
5383 llvm::AttributeList ExtraAttrs, bool Local,
5384 bool AssumeConvergent) {
5385 if (AssumeConvergent) {
5386 ExtraAttrs =
5387 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5388 }
5389
5390 llvm::Constant *C =
5391 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
5392 /*DontDefer=*/false, /*IsThunk=*/false,
5393 ExtraAttrs);
5394
5395 if (auto *F = dyn_cast<llvm::Function>(C)) {
5396 if (F->empty()) {
5397 F->setCallingConv(getRuntimeCC());
5398 setWindowsItaniumDLLImport(*this, Local, F, Name);
5399 setDSOLocal(F);
5400 // FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead
5401 // of trying to approximate the attributes using the LLVM function
5402 // signature. The other overload of CreateRuntimeFunction does this; it
5403 // should be used for new code.
5404 markRegisterParameterAttributes(F);
5405 }
5406 }
5407
5408 return {FTy, C};
5409 }
5410
5411 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
5412 /// create and return an llvm GlobalVariable with the specified type and address
5413 /// space. If there is something in the module with the specified name, return
5414 /// it potentially bitcasted to the right type.
5415 ///
5416 /// If D is non-null, it specifies a decl that correspond to this. This is used
5417 /// to set the attributes on the global when it is first created.
5418 ///
5419 /// If IsForDefinition is true, it is guaranteed that an actual global with
5420 /// type Ty will be returned, not conversion of a variable with the same
5421 /// mangled name but some other type.
5422 llvm::Constant *
5423 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
5424 LangAS AddrSpace, const VarDecl *D,
5425 ForDefinition_t IsForDefinition) {
5426 // Lookup the entry, lazily creating it if necessary.
5427 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5428 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5429 if (Entry) {
5430 if (WeakRefReferences.erase(Entry)) {
5431 if (D && !D->hasAttr<WeakAttr>())
5432 Entry->setLinkage(llvm::Function::ExternalLinkage);
5433 }
5434
5435 // Handle dropped DLL attributes.
5436 if (D && shouldDropDLLAttribute(D, Entry))
5437 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5438
5439 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5440 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
5441
5442 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5443 return Entry;
5444
5445 // If there are two attempts to define the same mangled name, issue an
5446 // error.
5447 if (IsForDefinition && !Entry->isDeclaration()) {
5448 GlobalDecl OtherGD;
5449 const VarDecl *OtherD;
5450
5451 // Check that D is not yet in DiagnosedConflictingDefinitions is required
5452 // to make sure that we issue an error only once.
5453 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
5454 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
5455 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
5456 OtherD->hasInit() &&
5457 DiagnosedConflictingDefinitions.insert(D).second) {
5458 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
5459 << MangledName;
5460 getDiags().Report(OtherGD.getDecl()->getLocation(),
5461 diag::note_previous_definition);
5462 }
5463 }
5464
5465 // Make sure the result is of the correct type.
5466 if (Entry->getType()->getAddressSpace() != TargetAS)
5467 return llvm::ConstantExpr::getAddrSpaceCast(
5468 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5469
5470 // (If global is requested for a definition, we always need to create a new
5471 // global, not just return a bitcast.)
5472 if (!IsForDefinition)
5473 return Entry;
5474 }
5475
5476 auto DAddrSpace = GetGlobalVarAddressSpace(D);
5477
5478 auto *GV = new llvm::GlobalVariable(
5479 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
5480 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
5481 getContext().getTargetAddressSpace(DAddrSpace));
5482
5483 // If we already created a global with the same mangled name (but different
5484 // type) before, take its name and remove it from its parent.
5485 if (Entry) {
5486 GV->takeName(Entry);
5487
5488 if (!Entry->use_empty()) {
5489 Entry->replaceAllUsesWith(GV);
5490 }
5491
5492 Entry->eraseFromParent();
5493 }
5494
5495 // This is the first use or definition of a mangled name. If there is a
5496 // deferred decl with this name, remember that we need to emit it at the end
5497 // of the file.
5498 auto DDI = DeferredDecls.find(MangledName);
5499 if (DDI != DeferredDecls.end()) {
5500 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
5501 // list, and remove it from DeferredDecls (since we don't need it anymore).
5502 addDeferredDeclToEmit(DDI->second);
5503 DeferredDecls.erase(DDI);
5504 }
5505
5506 // Handle things which are present even on external declarations.
5507 if (D) {
5508 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5509 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
5510
5511 // FIXME: This code is overly simple and should be merged with other global
5512 // handling.
5513 GV->setConstant(D->getType().isConstantStorage(getContext(), false, false));
5514
5515 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
5516
5517 setLinkageForGV(GV, D);
5518
5519 if (D->getTLSKind()) {
5520 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
5521 CXXThreadLocals.push_back(D);
5522 setTLSMode(GV, *D);
5523 }
5524
5525 setGVProperties(GV, D);
5526
5527 // If required by the ABI, treat declarations of static data members with
5528 // inline initializers as definitions.
5529 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
5530 EmitGlobalVarDefinition(D);
5531 }
5532
5533 // Emit section information for extern variables.
5534 if (D->hasExternalStorage()) {
5535 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
5536 GV->setSection(SA->getName());
5537 }
5538
5539 // Handle XCore specific ABI requirements.
5540 if (getTriple().getArch() == llvm::Triple::xcore &&
5541 D->getLanguageLinkage() == CLanguageLinkage &&
5542 D->getType().isConstant(Context) &&
5543 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
5544 GV->setSection(".cp.rodata");
5545
5546 // Handle code model attribute
5547 if (const auto *CMA = D->getAttr<CodeModelAttr>())
5548 GV->setCodeModel(CMA->getModel());
5549
5550 // Check if we a have a const declaration with an initializer, we may be
5551 // able to emit it as available_externally to expose it's value to the
5552 // optimizer.
5553 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5554 D->getType().isConstQualified() && !GV->hasInitializer() &&
5555 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
5556 const auto *Record =
5557 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
5558 bool HasMutableFields = Record && Record->hasMutableFields();
5559 if (!HasMutableFields) {
5560 const VarDecl *InitDecl;
5561 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5562 if (InitExpr) {
5563 ConstantEmitter emitter(*this);
5564 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
5565 if (Init) {
5566 auto *InitType = Init->getType();
5567 if (GV->getValueType() != InitType) {
5568 // The type of the initializer does not match the definition.
5569 // This happens when an initializer has a different type from
5570 // the type of the global (because of padding at the end of a
5571 // structure for instance).
5572 GV->setName(StringRef());
5573 // Make a new global with the correct type, this is now guaranteed
5574 // to work.
5575 auto *NewGV = cast<llvm::GlobalVariable>(
5576 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
5577 ->stripPointerCasts());
5578
5579 // Erase the old global, since it is no longer used.
5580 GV->eraseFromParent();
5581 GV = NewGV;
5582 } else {
5583 GV->setInitializer(Init);
5584 GV->setConstant(true);
5585 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5586 }
5587 emitter.finalize(GV);
5588 }
5589 }
5590 }
5591 }
5592 }
5593
5594 if (D &&
5595 D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) {
5596 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
5597 // External HIP managed variables needed to be recorded for transformation
5598 // in both device and host compilations.
5599 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
5600 D->hasExternalStorage())
5601 getCUDARuntime().handleVarRegistration(D, *GV);
5602 }
5603
5604 if (D)
5605 SanitizerMD->reportGlobal(GV, *D);
5606
5607 LangAS ExpectedAS =
5608 D ? D->getType().getAddressSpace()
5609 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
5610 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5611 if (DAddrSpace != ExpectedAS) {
5612 return getTargetCodeGenInfo().performAddrSpaceCast(
5613 *this, GV, DAddrSpace,
5614 llvm::PointerType::get(getLLVMContext(), TargetAS));
5615 }
5616
5617 return GV;
5618 }
5619
5620 llvm::Constant *
5621 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
5622 const Decl *D = GD.getDecl();
5623
5624 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
5625 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
5626 /*DontDefer=*/false, IsForDefinition);
5627
5628 if (isa<CXXMethodDecl>(D)) {
5629 auto FInfo =
5630 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
5631 auto Ty = getTypes().GetFunctionType(*FInfo);
5632 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5633 IsForDefinition);
5634 }
5635
5636 if (isa<FunctionDecl>(D)) {
5637 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5638 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5639 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5640 IsForDefinition);
5641 }
5642
5643 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
5644 }
5645
5646 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
5647 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
5648 llvm::Align Alignment) {
5649 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
5650 llvm::GlobalVariable *OldGV = nullptr;
5651
5652 if (GV) {
5653 // Check if the variable has the right type.
5654 if (GV->getValueType() == Ty)
5655 return GV;
5656
5657 // Because C++ name mangling, the only way we can end up with an already
5658 // existing global with the same name is if it has been declared extern "C".
5659 assert(GV->isDeclaration() && "Declaration has wrong type!");
5660 OldGV = GV;
5661 }
5662
5663 // Create a new variable.
5664 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
5665 Linkage, nullptr, Name);
5666
5667 if (OldGV) {
5668 // Replace occurrences of the old variable if needed.
5669 GV->takeName(OldGV);
5670
5671 if (!OldGV->use_empty()) {
5672 OldGV->replaceAllUsesWith(GV);
5673 }
5674
5675 OldGV->eraseFromParent();
5676 }
5677
5678 if (supportsCOMDAT() && GV->isWeakForLinker() &&
5679 !GV->hasAvailableExternallyLinkage())
5680 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5681
5682 GV->setAlignment(Alignment);
5683
5684 return GV;
5685 }
5686
5687 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
5688 /// given global variable. If Ty is non-null and if the global doesn't exist,
5689 /// then it will be created with the specified type instead of whatever the
5690 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
5691 /// that an actual global with type Ty will be returned, not conversion of a
5692 /// variable with the same mangled name but some other type.
5693 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
5694 llvm::Type *Ty,
5695 ForDefinition_t IsForDefinition) {
5696 assert(D->hasGlobalStorage() && "Not a global variable");
5697 QualType ASTTy = D->getType();
5698 if (!Ty)
5699 Ty = getTypes().ConvertTypeForMem(ASTTy);
5700
5701 StringRef MangledName = getMangledName(D);
5702 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
5703 IsForDefinition);
5704 }
5705
5706 /// CreateRuntimeVariable - Create a new runtime global variable with the
5707 /// specified type and name.
5708 llvm::Constant *
5709 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
5710 StringRef Name) {
5711 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
5712 : LangAS::Default;
5713 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
5714 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5715 return Ret;
5716 }
5717
5718 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
5719 assert(!D->getInit() && "Cannot emit definite definitions here!");
5720
5721 StringRef MangledName = getMangledName(D);
5722 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
5723
5724 // We already have a definition, not declaration, with the same mangled name.
5725 // Emitting of declaration is not required (and actually overwrites emitted
5726 // definition).
5727 if (GV && !GV->isDeclaration())
5728 return;
5729
5730 // If we have not seen a reference to this variable yet, place it into the
5731 // deferred declarations table to be emitted if needed later.
5732 if (!MustBeEmitted(D) && !GV) {
5733 DeferredDecls[MangledName] = D;
5734 return;
5735 }
5736
5737 // The tentative definition is the only definition.
5738 EmitGlobalVarDefinition(D);
5739 }
5740
5741 // Return a GlobalDecl. Use the base variants for destructors and constructors.
5742 static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D) {
5743 if (auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
5744 return GlobalDecl(CD, CXXCtorType::Ctor_Base);
5745 else if (auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
5746 return GlobalDecl(DD, CXXDtorType::Dtor_Base);
5747 return GlobalDecl(D);
5748 }
5749
5750 void CodeGenModule::EmitExternalDeclaration(const DeclaratorDecl *D) {
5751 CGDebugInfo *DI = getModuleDebugInfo();
5752 if (!DI || !getCodeGenOpts().hasReducedDebugInfo())
5753 return;
5754
5755 GlobalDecl GD = getBaseVariantGlobalDecl(D);
5756 if (!GD)
5757 return;
5758
5759 llvm::Constant *Addr = GetAddrOfGlobal(GD)->stripPointerCasts();
5760 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5761 DI->EmitExternalVariable(
5762 cast<llvm::GlobalVariable>(Addr->stripPointerCasts()), VD);
5763 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5764 llvm::Function *Fn = cast<llvm::Function>(Addr);
5765 if (!Fn->getSubprogram())
5766 DI->EmitFunctionDecl(GD, FD->getLocation(), FD->getType(), Fn);
5767 }
5768 }
5769
5770 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
5771 return Context.toCharUnitsFromBits(
5772 getDataLayout().getTypeStoreSizeInBits(Ty));
5773 }
5774
5775 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
5776 if (LangOpts.OpenCL) {
5777 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
5778 assert(AS == LangAS::opencl_global ||
5779 AS == LangAS::opencl_global_device ||
5780 AS == LangAS::opencl_global_host ||
5781 AS == LangAS::opencl_constant ||
5782 AS == LangAS::opencl_local ||
5783 AS >= LangAS::FirstTargetAddressSpace);
5784 return AS;
5785 }
5786
5787 if (LangOpts.SYCLIsDevice &&
5788 (!D || D->getType().getAddressSpace() == LangAS::Default))
5789 return LangAS::sycl_global;
5790
5791 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5792 if (D) {
5793 if (D->hasAttr<CUDAConstantAttr>())
5794 return LangAS::cuda_constant;
5795 if (D->hasAttr<CUDASharedAttr>())
5796 return LangAS::cuda_shared;
5797 if (D->hasAttr<CUDADeviceAttr>())
5798 return LangAS::cuda_device;
5799 if (D->getType().isConstQualified())
5800 return LangAS::cuda_constant;
5801 }
5802 return LangAS::cuda_device;
5803 }
5804
5805 if (LangOpts.OpenMP) {
5806 LangAS AS;
5807 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
5808 return AS;
5809 }
5810 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
5811 }
5812
5813 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
5814 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
5815 if (LangOpts.OpenCL)
5816 return LangAS::opencl_constant;
5817 if (LangOpts.SYCLIsDevice)
5818 return LangAS::sycl_global;
5819 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
5820 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
5821 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
5822 // with OpVariable instructions with Generic storage class which is not
5823 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
5824 // UniformConstant storage class is not viable as pointers to it may not be
5825 // casted to Generic pointers which are used to model HIP's "flat" pointers.
5826 return LangAS::cuda_device;
5827 if (auto AS = getTarget().getConstantAddressSpace())
5828 return *AS;
5829 return LangAS::Default;
5830 }
5831
5832 // In address space agnostic languages, string literals are in default address
5833 // space in AST. However, certain targets (e.g. amdgcn) request them to be
5834 // emitted in constant address space in LLVM IR. To be consistent with other
5835 // parts of AST, string literal global variables in constant address space
5836 // need to be casted to default address space before being put into address
5837 // map and referenced by other part of CodeGen.
5838 // In OpenCL, string literals are in constant address space in AST, therefore
5839 // they should not be casted to default address space.
5840 static llvm::Constant *
5841 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
5842 llvm::GlobalVariable *GV) {
5843 llvm::Constant *Cast = GV;
5844 if (!CGM.getLangOpts().OpenCL) {
5845 auto AS = CGM.GetGlobalConstantAddressSpace();
5846 if (AS != LangAS::Default)
5847 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
5848 CGM, GV, AS,
5849 llvm::PointerType::get(
5850 CGM.getLLVMContext(),
5851 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
5852 }
5853 return Cast;
5854 }
5855
5856 template<typename SomeDecl>
5857 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
5858 llvm::GlobalValue *GV) {
5859 if (!getLangOpts().CPlusPlus)
5860 return;
5861
5862 // Must have 'used' attribute, or else inline assembly can't rely on
5863 // the name existing.
5864 if (!D->template hasAttr<UsedAttr>())
5865 return;
5866
5867 // Must have internal linkage and an ordinary name.
5868 if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal)
5869 return;
5870
5871 // Must be in an extern "C" context. Entities declared directly within
5872 // a record are not extern "C" even if the record is in such a context.
5873 const SomeDecl *First = D->getFirstDecl();
5874 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
5875 return;
5876
5877 // OK, this is an internal linkage entity inside an extern "C" linkage
5878 // specification. Make a note of that so we can give it the "expected"
5879 // mangled name if nothing else is using that name.
5880 std::pair<StaticExternCMap::iterator, bool> R =
5881 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5882
5883 // If we have multiple internal linkage entities with the same name
5884 // in extern "C" regions, none of them gets that name.
5885 if (!R.second)
5886 R.first->second = nullptr;
5887 }
5888
5889 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
5890 if (!CGM.supportsCOMDAT())
5891 return false;
5892
5893 if (D.hasAttr<SelectAnyAttr>())
5894 return true;
5895
5896 GVALinkage Linkage;
5897 if (auto *VD = dyn_cast<VarDecl>(&D))
5898 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
5899 else
5900 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
5901
5902 switch (Linkage) {
5903 case GVA_Internal:
5904 case GVA_AvailableExternally:
5905 case GVA_StrongExternal:
5906 return false;
5907 case GVA_DiscardableODR:
5908 case GVA_StrongODR:
5909 return true;
5910 }
5911 llvm_unreachable("No such linkage");
5912 }
5913
5914 bool CodeGenModule::supportsCOMDAT() const {
5915 return getTriple().supportsCOMDAT();
5916 }
5917
5918 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
5919 llvm::GlobalObject &GO) {
5920 if (!shouldBeInCOMDAT(*this, D))
5921 return;
5922 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5923 }
5924
5925 const ABIInfo &CodeGenModule::getABIInfo() {
5926 return getTargetCodeGenInfo().getABIInfo();
5927 }
5928
5929 /// Pass IsTentative as true if you want to create a tentative definition.
5930 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
5931 bool IsTentative) {
5932 // OpenCL global variables of sampler type are translated to function calls,
5933 // therefore no need to be translated.
5934 QualType ASTTy = D->getType();
5935 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
5936 return;
5937
5938 // HLSL default buffer constants will be emitted during HLSLBufferDecl codegen
5939 if (getLangOpts().HLSL &&
5940 D->getType().getAddressSpace() == LangAS::hlsl_constant)
5941 return;
5942
5943 // If this is OpenMP device, check if it is legal to emit this global
5944 // normally.
5945 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5946 OpenMPRuntime->emitTargetGlobalVariable(D))
5947 return;
5948
5949 llvm::TrackingVH<llvm::Constant> Init;
5950 bool NeedsGlobalCtor = false;
5951 // Whether the definition of the variable is available externally.
5952 // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5953 // since this is the job for its original source.
5954 bool IsDefinitionAvailableExternally =
5955 getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
5956 bool NeedsGlobalDtor =
5957 !IsDefinitionAvailableExternally &&
5958 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
5959
5960 // It is helpless to emit the definition for an available_externally variable
5961 // which can't be marked as const.
5962 // We don't need to check if it needs global ctor or dtor. See the above
5963 // comment for ideas.
5964 if (IsDefinitionAvailableExternally &&
5965 (!D->hasConstantInitialization() ||
5966 // TODO: Update this when we have interface to check constexpr
5967 // destructor.
5968 D->needsDestruction(getContext()) ||
5969 !D->getType().isConstantStorage(getContext(), true, true)))
5970 return;
5971
5972 const VarDecl *InitDecl;
5973 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5974
5975 std::optional<ConstantEmitter> emitter;
5976
5977 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
5978 // as part of their declaration." Sema has already checked for
5979 // error cases, so we just need to set Init to UndefValue.
5980 bool IsCUDASharedVar =
5981 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
5982 // Shadows of initialized device-side global variables are also left
5983 // undefined.
5984 // Managed Variables should be initialized on both host side and device side.
5985 bool IsCUDAShadowVar =
5986 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5987 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
5988 D->hasAttr<CUDASharedAttr>());
5989 bool IsCUDADeviceShadowVar =
5990 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5991 (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5992 D->getType()->isCUDADeviceBuiltinTextureType());
5993 if (getLangOpts().CUDA &&
5994 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
5995 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5996 } else if (getLangOpts().HLSL &&
5997 (D->getType()->isHLSLResourceRecord() ||
5998 D->getType()->isHLSLResourceRecordArray())) {
5999 Init = llvm::PoisonValue::get(getTypes().ConvertType(ASTTy));
6000 NeedsGlobalCtor = D->getType()->isHLSLResourceRecord() ||
6001 D->getStorageClass() == SC_Static;
6002 } else if (D->hasAttr<LoaderUninitializedAttr>()) {
6003 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
6004 } else if (!InitExpr) {
6005 // This is a tentative definition; tentative definitions are
6006 // implicitly initialized with { 0 }.
6007 //
6008 // Note that tentative definitions are only emitted at the end of
6009 // a translation unit, so they should never have incomplete
6010 // type. In addition, EmitTentativeDefinition makes sure that we
6011 // never attempt to emit a tentative definition if a real one
6012 // exists. A use may still exists, however, so we still may need
6013 // to do a RAUW.
6014 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
6015 Init = EmitNullConstant(D->getType());
6016 } else {
6017 initializedGlobalDecl = GlobalDecl(D);
6018 emitter.emplace(*this);
6019 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
6020 if (!Initializer) {
6021 QualType T = InitExpr->getType();
6022 if (D->getType()->isReferenceType())
6023 T = D->getType();
6024
6025 if (getLangOpts().CPlusPlus) {
6026 Init = EmitNullConstant(T);
6027 if (!IsDefinitionAvailableExternally)
6028 NeedsGlobalCtor = true;
6029 if (InitDecl->hasFlexibleArrayInit(getContext())) {
6030 ErrorUnsupported(D, "flexible array initializer");
6031 // We cannot create ctor for flexible array initializer
6032 NeedsGlobalCtor = false;
6033 }
6034 } else {
6035 ErrorUnsupported(D, "static initializer");
6036 Init = llvm::PoisonValue::get(getTypes().ConvertType(T));
6037 }
6038 } else {
6039 Init = Initializer;
6040 // We don't need an initializer, so remove the entry for the delayed
6041 // initializer position (just in case this entry was delayed) if we
6042 // also don't need to register a destructor.
6043 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
6044 DelayedCXXInitPosition.erase(D);
6045
6046 #ifndef NDEBUG
6047 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
6048 InitDecl->getFlexibleArrayInitChars(getContext());
6049 CharUnits CstSize = CharUnits::fromQuantity(
6050 getDataLayout().getTypeAllocSize(Init->getType()));
6051 assert(VarSize == CstSize && "Emitted constant has unexpected size");
6052 #endif
6053 }
6054 }
6055
6056 llvm::Type* InitType = Init->getType();
6057 llvm::Constant *Entry =
6058 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
6059
6060 // Strip off pointer casts if we got them.
6061 Entry = Entry->stripPointerCasts();
6062
6063 // Entry is now either a Function or GlobalVariable.
6064 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6065
6066 // We have a definition after a declaration with the wrong type.
6067 // We must make a new GlobalVariable* and update everything that used OldGV
6068 // (a declaration or tentative definition) with the new GlobalVariable*
6069 // (which will be a definition).
6070 //
6071 // This happens if there is a prototype for a global (e.g.
6072 // "extern int x[];") and then a definition of a different type (e.g.
6073 // "int x[10];"). This also happens when an initializer has a different type
6074 // from the type of the global (this happens with unions).
6075 if (!GV || GV->getValueType() != InitType ||
6076 GV->getType()->getAddressSpace() !=
6077 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
6078
6079 // Move the old entry aside so that we'll create a new one.
6080 Entry->setName(StringRef());
6081
6082 // Make a new global with the correct type, this is now guaranteed to work.
6083 GV = cast<llvm::GlobalVariable>(
6084 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
6085 ->stripPointerCasts());
6086
6087 // Replace all uses of the old global with the new global
6088 llvm::Constant *NewPtrForOldDecl =
6089 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6090 Entry->getType());
6091 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6092
6093 // Erase the old global, since it is no longer used.
6094 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
6095 }
6096
6097 MaybeHandleStaticInExternC(D, GV);
6098
6099 if (D->hasAttr<AnnotateAttr>())
6100 AddGlobalAnnotations(D, GV);
6101
6102 // Set the llvm linkage type as appropriate.
6103 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D);
6104
6105 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
6106 // the device. [...]"
6107 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
6108 // __device__, declares a variable that: [...]
6109 // Is accessible from all the threads within the grid and from the host
6110 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
6111 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
6112 if (LangOpts.CUDA) {
6113 if (LangOpts.CUDAIsDevice) {
6114 if (Linkage != llvm::GlobalValue::InternalLinkage &&
6115 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
6116 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
6117 D->getType()->isCUDADeviceBuiltinTextureType()))
6118 GV->setExternallyInitialized(true);
6119 } else {
6120 getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
6121 }
6122 getCUDARuntime().handleVarRegistration(D, *GV);
6123 }
6124
6125 if (LangOpts.HLSL &&
6126 hlsl::isInitializedByPipeline(GetGlobalVarAddressSpace(D))) {
6127 // HLSL Input variables are considered to be set by the driver/pipeline, but
6128 // only visible to a single thread/wave. Push constants are also externally
6129 // initialized, but constant, hence cross-wave visibility is not relevant.
6130 GV->setExternallyInitialized(true);
6131 } else {
6132 GV->setInitializer(Init);
6133 }
6134
6135 if (LangOpts.HLSL)
6136 getHLSLRuntime().handleGlobalVarDefinition(D, GV);
6137
6138 if (emitter)
6139 emitter->finalize(GV);
6140
6141 // If it is safe to mark the global 'constant', do so now.
6142 GV->setConstant((D->hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6143 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6144 D->getType().isConstantStorage(getContext(), true, true)));
6145
6146 // If it is in a read-only section, mark it 'constant'.
6147 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
6148 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6149 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
6150 GV->setConstant(true);
6151 }
6152
6153 CharUnits AlignVal = getContext().getDeclAlign(D);
6154 // Check for alignment specifed in an 'omp allocate' directive.
6155 if (std::optional<CharUnits> AlignValFromAllocate =
6156 getOMPAllocateAlignment(D))
6157 AlignVal = *AlignValFromAllocate;
6158 GV->setAlignment(AlignVal.getAsAlign());
6159
6160 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
6161 // function is only defined alongside the variable, not also alongside
6162 // callers. Normally, all accesses to a thread_local go through the
6163 // thread-wrapper in order to ensure initialization has occurred, underlying
6164 // variable will never be used other than the thread-wrapper, so it can be
6165 // converted to internal linkage.
6166 //
6167 // However, if the variable has the 'constinit' attribute, it _can_ be
6168 // referenced directly, without calling the thread-wrapper, so the linkage
6169 // must not be changed.
6170 //
6171 // Additionally, if the variable isn't plain external linkage, e.g. if it's
6172 // weak or linkonce, the de-duplication semantics are important to preserve,
6173 // so we don't change the linkage.
6174 if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
6175 Linkage == llvm::GlobalValue::ExternalLinkage &&
6176 Context.getTargetInfo().getTriple().isOSDarwin() &&
6177 !D->hasAttr<ConstInitAttr>())
6178 Linkage = llvm::GlobalValue::InternalLinkage;
6179
6180 // HLSL variables in the input or push-constant address space maps are like
6181 // memory-mapped variables. Even if they are 'static', they are externally
6182 // initialized and read/write by the hardware/driver/pipeline.
6183 if (LangOpts.HLSL &&
6184 hlsl::isInitializedByPipeline(GetGlobalVarAddressSpace(D)))
6185 Linkage = llvm::GlobalValue::ExternalLinkage;
6186
6187 GV->setLinkage(Linkage);
6188 if (D->hasAttr<DLLImportAttr>())
6189 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6190 else if (D->hasAttr<DLLExportAttr>())
6191 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6192 else
6193 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6194
6195 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
6196 // common vars aren't constant even if declared const.
6197 GV->setConstant(false);
6198 // Tentative definition of global variables may be initialized with
6199 // non-zero null pointers. In this case they should have weak linkage
6200 // since common linkage must have zero initializer and must not have
6201 // explicit section therefore cannot have non-zero initial value.
6202 if (!GV->getInitializer()->isNullValue())
6203 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6204 }
6205
6206 setNonAliasAttributes(D, GV);
6207
6208 if (D->getTLSKind() && !GV->isThreadLocal()) {
6209 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
6210 CXXThreadLocals.push_back(D);
6211 setTLSMode(GV, *D);
6212 }
6213
6214 maybeSetTrivialComdat(*D, *GV);
6215
6216 // Emit the initializer function if necessary.
6217 if (NeedsGlobalCtor || NeedsGlobalDtor)
6218 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6219
6220 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6221
6222 // Emit global variable debug information.
6223 if (CGDebugInfo *DI = getModuleDebugInfo())
6224 if (getCodeGenOpts().hasReducedDebugInfo())
6225 DI->EmitGlobalVariable(GV, D);
6226 }
6227
6228 static bool isVarDeclStrongDefinition(const ASTContext &Context,
6229 CodeGenModule &CGM, const VarDecl *D,
6230 bool NoCommon) {
6231 // Don't give variables common linkage if -fno-common was specified unless it
6232 // was overridden by a NoCommon attribute.
6233 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
6234 return true;
6235
6236 // C11 6.9.2/2:
6237 // A declaration of an identifier for an object that has file scope without
6238 // an initializer, and without a storage-class specifier or with the
6239 // storage-class specifier static, constitutes a tentative definition.
6240 if (D->getInit() || D->hasExternalStorage())
6241 return true;
6242
6243 // A variable cannot be both common and exist in a section.
6244 if (D->hasAttr<SectionAttr>())
6245 return true;
6246
6247 // A variable cannot be both common and exist in a section.
6248 // We don't try to determine which is the right section in the front-end.
6249 // If no specialized section name is applicable, it will resort to default.
6250 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
6251 D->hasAttr<PragmaClangDataSectionAttr>() ||
6252 D->hasAttr<PragmaClangRelroSectionAttr>() ||
6253 D->hasAttr<PragmaClangRodataSectionAttr>())
6254 return true;
6255
6256 // Thread local vars aren't considered common linkage.
6257 if (D->getTLSKind())
6258 return true;
6259
6260 // Tentative definitions marked with WeakImportAttr are true definitions.
6261 if (D->hasAttr<WeakImportAttr>())
6262 return true;
6263
6264 // A variable cannot be both common and exist in a comdat.
6265 if (shouldBeInCOMDAT(CGM, *D))
6266 return true;
6267
6268 // Declarations with a required alignment do not have common linkage in MSVC
6269 // mode.
6270 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6271 if (D->hasAttr<AlignedAttr>())
6272 return true;
6273 QualType VarType = D->getType();
6274 if (Context.isAlignmentRequired(VarType))
6275 return true;
6276
6277 if (const auto *RD = VarType->getAsRecordDecl()) {
6278 for (const FieldDecl *FD : RD->fields()) {
6279 if (FD->isBitField())
6280 continue;
6281 if (FD->hasAttr<AlignedAttr>())
6282 return true;
6283 if (Context.isAlignmentRequired(FD->getType()))
6284 return true;
6285 }
6286 }
6287 }
6288
6289 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
6290 // common symbols, so symbols with greater alignment requirements cannot be
6291 // common.
6292 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
6293 // alignments for common symbols via the aligncomm directive, so this
6294 // restriction only applies to MSVC environments.
6295 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6296 Context.getTypeAlignIfKnown(D->getType()) >
6297 Context.toBits(CharUnits::fromQuantity(32)))
6298 return true;
6299
6300 return false;
6301 }
6302
6303 llvm::GlobalValue::LinkageTypes
6304 CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D,
6305 GVALinkage Linkage) {
6306 if (Linkage == GVA_Internal)
6307 return llvm::Function::InternalLinkage;
6308
6309 if (D->hasAttr<WeakAttr>())
6310 return llvm::GlobalVariable::WeakAnyLinkage;
6311
6312 if (const auto *FD = D->getAsFunction())
6313 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
6314 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6315
6316 // We are guaranteed to have a strong definition somewhere else,
6317 // so we can use available_externally linkage.
6318 if (Linkage == GVA_AvailableExternally)
6319 return llvm::GlobalValue::AvailableExternallyLinkage;
6320
6321 // Note that Apple's kernel linker doesn't support symbol
6322 // coalescing, so we need to avoid linkonce and weak linkages there.
6323 // Normally, this means we just map to internal, but for explicit
6324 // instantiations we'll map to external.
6325
6326 // In C++, the compiler has to emit a definition in every translation unit
6327 // that references the function. We should use linkonce_odr because
6328 // a) if all references in this translation unit are optimized away, we
6329 // don't need to codegen it. b) if the function persists, it needs to be
6330 // merged with other definitions. c) C++ has the ODR, so we know the
6331 // definition is dependable.
6332 if (Linkage == GVA_DiscardableODR)
6333 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6334 : llvm::Function::InternalLinkage;
6335
6336 // An explicit instantiation of a template has weak linkage, since
6337 // explicit instantiations can occur in multiple translation units
6338 // and must all be equivalent. However, we are not allowed to
6339 // throw away these explicit instantiations.
6340 //
6341 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
6342 // so say that CUDA templates are either external (for kernels) or internal.
6343 // This lets llvm perform aggressive inter-procedural optimizations. For
6344 // -fgpu-rdc case, device function calls across multiple TU's are allowed,
6345 // therefore we need to follow the normal linkage paradigm.
6346 if (Linkage == GVA_StrongODR) {
6347 if (getLangOpts().AppleKext)
6348 return llvm::Function::ExternalLinkage;
6349 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
6350 !getLangOpts().GPURelocatableDeviceCode)
6351 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6352 : llvm::Function::InternalLinkage;
6353 return llvm::Function::WeakODRLinkage;
6354 }
6355
6356 // C++ doesn't have tentative definitions and thus cannot have common
6357 // linkage.
6358 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
6359 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
6360 CodeGenOpts.NoCommon))
6361 return llvm::GlobalVariable::CommonLinkage;
6362
6363 // selectany symbols are externally visible, so use weak instead of
6364 // linkonce. MSVC optimizes away references to const selectany globals, so
6365 // all definitions should be the same and ODR linkage should be used.
6366 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
6367 if (D->hasAttr<SelectAnyAttr>())
6368 return llvm::GlobalVariable::WeakODRLinkage;
6369
6370 // Otherwise, we have strong external linkage.
6371 assert(Linkage == GVA_StrongExternal);
6372 return llvm::GlobalVariable::ExternalLinkage;
6373 }
6374
6375 llvm::GlobalValue::LinkageTypes
6376 CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) {
6377 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
6378 return getLLVMLinkageForDeclarator(VD, Linkage);
6379 }
6380
6381 /// Replace the uses of a function that was declared with a non-proto type.
6382 /// We want to silently drop extra arguments from call sites
6383 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
6384 llvm::Function *newFn) {
6385 // Fast path.
6386 if (old->use_empty())
6387 return;
6388
6389 llvm::Type *newRetTy = newFn->getReturnType();
6390 SmallVector<llvm::Value *, 4> newArgs;
6391
6392 SmallVector<llvm::CallBase *> callSitesToBeRemovedFromParent;
6393
6394 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6395 ui != ue; ui++) {
6396 llvm::User *user = ui->getUser();
6397
6398 // Recognize and replace uses of bitcasts. Most calls to
6399 // unprototyped functions will use bitcasts.
6400 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6401 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6402 replaceUsesOfNonProtoConstant(bitcast, newFn);
6403 continue;
6404 }
6405
6406 // Recognize calls to the function.
6407 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6408 if (!callSite)
6409 continue;
6410 if (!callSite->isCallee(&*ui))
6411 continue;
6412
6413 // If the return types don't match exactly, then we can't
6414 // transform this call unless it's dead.
6415 if (callSite->getType() != newRetTy && !callSite->use_empty())
6416 continue;
6417
6418 // Get the call site's attribute list.
6419 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
6420 llvm::AttributeList oldAttrs = callSite->getAttributes();
6421
6422 // If the function was passed too few arguments, don't transform.
6423 unsigned newNumArgs = newFn->arg_size();
6424 if (callSite->arg_size() < newNumArgs)
6425 continue;
6426
6427 // If extra arguments were passed, we silently drop them.
6428 // If any of the types mismatch, we don't transform.
6429 unsigned argNo = 0;
6430 bool dontTransform = false;
6431 for (llvm::Argument &A : newFn->args()) {
6432 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6433 dontTransform = true;
6434 break;
6435 }
6436
6437 // Add any parameter attributes.
6438 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6439 argNo++;
6440 }
6441 if (dontTransform)
6442 continue;
6443
6444 // Okay, we can transform this. Create the new call instruction and copy
6445 // over the required information.
6446 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6447
6448 // Copy over any operand bundles.
6449 SmallVector<llvm::OperandBundleDef, 1> newBundles;
6450 callSite->getOperandBundlesAsDefs(newBundles);
6451
6452 llvm::CallBase *newCall;
6453 if (isa<llvm::CallInst>(callSite)) {
6454 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
6455 callSite->getIterator());
6456 } else {
6457 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
6458 newCall = llvm::InvokeInst::Create(
6459 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6460 newArgs, newBundles, "", callSite->getIterator());
6461 }
6462 newArgs.clear(); // for the next iteration
6463
6464 if (!newCall->getType()->isVoidTy())
6465 newCall->takeName(callSite);
6466 newCall->setAttributes(
6467 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6468 oldAttrs.getRetAttrs(), newArgAttrs));
6469 newCall->setCallingConv(callSite->getCallingConv());
6470
6471 // Finally, remove the old call, replacing any uses with the new one.
6472 if (!callSite->use_empty())
6473 callSite->replaceAllUsesWith(newCall);
6474
6475 // Copy debug location attached to CI.
6476 if (callSite->getDebugLoc())
6477 newCall->setDebugLoc(callSite->getDebugLoc());
6478
6479 callSitesToBeRemovedFromParent.push_back(callSite);
6480 }
6481
6482 for (auto *callSite : callSitesToBeRemovedFromParent) {
6483 callSite->eraseFromParent();
6484 }
6485 }
6486
6487 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
6488 /// implement a function with no prototype, e.g. "int foo() {}". If there are
6489 /// existing call uses of the old function in the module, this adjusts them to
6490 /// call the new function directly.
6491 ///
6492 /// This is not just a cleanup: the always_inline pass requires direct calls to
6493 /// functions to be able to inline them. If there is a bitcast in the way, it
6494 /// won't inline them. Instcombine normally deletes these calls, but it isn't
6495 /// run at -O0.
6496 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
6497 llvm::Function *NewFn) {
6498 // If we're redefining a global as a function, don't transform it.
6499 if (!isa<llvm::Function>(Old)) return;
6500
6501 replaceUsesOfNonProtoConstant(Old, NewFn);
6502 }
6503
6504 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
6505 auto DK = VD->isThisDeclarationADefinition();
6506 if ((DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) ||
6507 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6508 return;
6509
6510 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
6511 // If we have a definition, this might be a deferred decl. If the
6512 // instantiation is explicit, make sure we emit it at the end.
6513 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
6514 GetAddrOfGlobalVar(VD);
6515
6516 EmitTopLevelDecl(VD);
6517 }
6518
6519 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
6520 llvm::GlobalValue *GV) {
6521 const auto *D = cast<FunctionDecl>(GD.getDecl());
6522
6523 // Compute the function info and LLVM type.
6524 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
6525 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
6526
6527 // Get or create the prototype for the function.
6528 if (!GV || (GV->getValueType() != Ty))
6529 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
6530 /*DontDefer=*/true,
6531 ForDefinition));
6532
6533 // Already emitted.
6534 if (!GV->isDeclaration())
6535 return;
6536
6537 // We need to set linkage and visibility on the function before
6538 // generating code for it because various parts of IR generation
6539 // want to propagate this information down (e.g. to local static
6540 // declarations).
6541 auto *Fn = cast<llvm::Function>(GV);
6542 setFunctionLinkage(GD, Fn);
6543
6544 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
6545 setGVProperties(Fn, GD);
6546
6547 MaybeHandleStaticInExternC(D, Fn);
6548
6549 maybeSetTrivialComdat(*D, *Fn);
6550
6551 CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
6552
6553 setNonAliasAttributes(GD, Fn);
6554
6555 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6556 (CodeGenOpts.OptimizationLevel == 0) &&
6557 !D->hasAttr<MinSizeAttr>();
6558
6559 if (DeviceKernelAttr::isOpenCLSpelling(D->getAttr<DeviceKernelAttr>())) {
6560 if (GD.getKernelReferenceKind() == KernelReferenceKind::Stub &&
6561 !D->hasAttr<NoInlineAttr>() &&
6562 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6563 !D->hasAttr<OptimizeNoneAttr>() &&
6564 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6565 !ShouldAddOptNone) {
6566 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6567 }
6568 }
6569
6570 SetLLVMFunctionAttributesForDefinition(D, Fn);
6571
6572 auto GetPriority = [this](const auto *Attr) -> int {
6573 Expr *E = Attr->getPriority();
6574 if (E) {
6575 return E->EvaluateKnownConstInt(this->getContext()).getExtValue();
6576 }
6577 return Attr->DefaultPriority;
6578 };
6579
6580 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
6581 AddGlobalCtor(Fn, GetPriority(CA));
6582 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
6583 AddGlobalDtor(Fn, GetPriority(DA), true);
6584 if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>())
6585 getOpenMPRuntime().emitDeclareTargetFunction(D, GV);
6586 }
6587
6588 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
6589 const auto *D = cast<ValueDecl>(GD.getDecl());
6590 const AliasAttr *AA = D->getAttr<AliasAttr>();
6591 assert(AA && "Not an alias?");
6592
6593 StringRef MangledName = getMangledName(GD);
6594
6595 if (AA->getAliasee() == MangledName) {
6596 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6597 return;
6598 }
6599
6600 // If there is a definition in the module, then it wins over the alias.
6601 // This is dubious, but allow it to be safe. Just ignore the alias.
6602 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
6603 if (Entry && !Entry->isDeclaration())
6604 return;
6605
6606 Aliases.push_back(GD);
6607
6608 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
6609
6610 // Create a reference to the named value. This ensures that it is emitted
6611 // if a deferred decl.
6612 llvm::Constant *Aliasee;
6613 llvm::GlobalValue::LinkageTypes LT;
6614 if (isa<llvm::FunctionType>(DeclTy)) {
6615 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6616 /*ForVTable=*/false);
6617 LT = getFunctionLinkage(GD);
6618 } else {
6619 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
6620 /*D=*/nullptr);
6621 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
6622 LT = getLLVMLinkageVarDefinition(VD);
6623 else
6624 LT = getFunctionLinkage(GD);
6625 }
6626
6627 // Create the new alias itself, but don't set a name yet.
6628 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6629 auto *GA =
6630 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
6631
6632 if (Entry) {
6633 if (GA->getAliasee() == Entry) {
6634 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6635 return;
6636 }
6637
6638 assert(Entry->isDeclaration());
6639
6640 // If there is a declaration in the module, then we had an extern followed
6641 // by the alias, as in:
6642 // extern int test6();
6643 // ...
6644 // int test6() __attribute__((alias("test7")));
6645 //
6646 // Remove it and replace uses of it with the alias.
6647 GA->takeName(Entry);
6648
6649 Entry->replaceAllUsesWith(GA);
6650 Entry->eraseFromParent();
6651 } else {
6652 GA->setName(MangledName);
6653 }
6654
6655 // Set attributes which are particular to an alias; this is a
6656 // specialization of the attributes which may be set on a global
6657 // variable/function.
6658 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
6659 D->isWeakImported()) {
6660 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6661 }
6662
6663 if (const auto *VD = dyn_cast<VarDecl>(D))
6664 if (VD->getTLSKind())
6665 setTLSMode(GA, *VD);
6666
6667 SetCommonAttributes(GD, GA);
6668
6669 // Emit global alias debug information.
6670 if (isa<VarDecl>(D))
6671 if (CGDebugInfo *DI = getModuleDebugInfo())
6672 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
6673 }
6674
6675 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
6676 const auto *D = cast<ValueDecl>(GD.getDecl());
6677 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
6678 assert(IFA && "Not an ifunc?");
6679
6680 StringRef MangledName = getMangledName(GD);
6681
6682 if (IFA->getResolver() == MangledName) {
6683 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6684 return;
6685 }
6686
6687 // Report an error if some definition overrides ifunc.
6688 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
6689 if (Entry && !Entry->isDeclaration()) {
6690 GlobalDecl OtherGD;
6691 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
6692 DiagnosedConflictingDefinitions.insert(GD).second) {
6693 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
6694 << MangledName;
6695 Diags.Report(OtherGD.getDecl()->getLocation(),
6696 diag::note_previous_definition);
6697 }
6698 return;
6699 }
6700
6701 Aliases.push_back(GD);
6702
6703 // The resolver might not be visited yet. Specify a dummy non-function type to
6704 // indicate IsIncompleteFunction. Either the type is ignored (if the resolver
6705 // was emitted) or the whole function will be replaced (if the resolver has
6706 // not been emitted).
6707 llvm::Constant *Resolver =
6708 GetOrCreateLLVMFunction(IFA->getResolver(), VoidTy, {},
6709 /*ForVTable=*/false);
6710 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
6711 unsigned AS = getTypes().getTargetAddressSpace(D->getType());
6712 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6713 DeclTy, AS, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
6714 if (Entry) {
6715 if (GIF->getResolver() == Entry) {
6716 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6717 return;
6718 }
6719 assert(Entry->isDeclaration());
6720
6721 // If there is a declaration in the module, then we had an extern followed
6722 // by the ifunc, as in:
6723 // extern int test();
6724 // ...
6725 // int test() __attribute__((ifunc("resolver")));
6726 //
6727 // Remove it and replace uses of it with the ifunc.
6728 GIF->takeName(Entry);
6729
6730 Entry->replaceAllUsesWith(GIF);
6731 Entry->eraseFromParent();
6732 } else
6733 GIF->setName(MangledName);
6734 SetCommonAttributes(GD, GIF);
6735 }
6736
6737 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
6738 ArrayRef<llvm::Type*> Tys) {
6739 return llvm::Intrinsic::getOrInsertDeclaration(&getModule(),
6740 (llvm::Intrinsic::ID)IID, Tys);
6741 }
6742
6743 static llvm::StringMapEntry<llvm::GlobalVariable *> &
6744 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
6745 const StringLiteral *Literal, bool TargetIsLSB,
6746 bool &IsUTF16, unsigned &StringLength) {
6747 StringRef String = Literal->getString();
6748 unsigned NumBytes = String.size();
6749
6750 // Check for simple case.
6751 if (!Literal->containsNonAsciiOrNull()) {
6752 StringLength = NumBytes;
6753 return *Map.insert(std::make_pair(String, nullptr)).first;
6754 }
6755
6756 // Otherwise, convert the UTF8 literals into a string of shorts.
6757 IsUTF16 = true;
6758
6759 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
6760 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6761 llvm::UTF16 *ToPtr = &ToBuf[0];
6762
6763 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6764 ToPtr + NumBytes, llvm::strictConversion);
6765
6766 // ConvertUTF8toUTF16 returns the length in ToPtr.
6767 StringLength = ToPtr - &ToBuf[0];
6768
6769 // Add an explicit null.
6770 *ToPtr = 0;
6771 return *Map.insert(std::make_pair(
6772 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
6773 (StringLength + 1) * 2),
6774 nullptr)).first;
6775 }
6776
6777 ConstantAddress
6778 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
6779 unsigned StringLength = 0;
6780 bool isUTF16 = false;
6781 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6782 GetConstantCFStringEntry(CFConstantStringMap, Literal,
6783 getDataLayout().isLittleEndian(), isUTF16,
6784 StringLength);
6785
6786 if (auto *C = Entry.second)
6787 return ConstantAddress(
6788 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
6789
6790 const ASTContext &Context = getContext();
6791 const llvm::Triple &Triple = getTriple();
6792
6793 const auto CFRuntime = getLangOpts().CFRuntime;
6794 const bool IsSwiftABI =
6795 static_cast<unsigned>(CFRuntime) >=
6796 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
6797 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
6798
6799 // If we don't already have it, get __CFConstantStringClassReference.
6800 if (!CFConstantStringClassRef) {
6801 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
6802 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
6803 Ty = llvm::ArrayType::get(Ty, 0);
6804
6805 switch (CFRuntime) {
6806 default: break;
6807 case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
6808 case LangOptions::CoreFoundationABI::Swift5_0:
6809 CFConstantStringClassName =
6810 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
6811 : "$s10Foundation19_NSCFConstantStringCN";
6812 Ty = IntPtrTy;
6813 break;
6814 case LangOptions::CoreFoundationABI::Swift4_2:
6815 CFConstantStringClassName =
6816 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
6817 : "$S10Foundation19_NSCFConstantStringCN";
6818 Ty = IntPtrTy;
6819 break;
6820 case LangOptions::CoreFoundationABI::Swift4_1:
6821 CFConstantStringClassName =
6822 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
6823 : "__T010Foundation19_NSCFConstantStringCN";
6824 Ty = IntPtrTy;
6825 break;
6826 }
6827
6828 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
6829
6830 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6831 llvm::GlobalValue *GV = nullptr;
6832
6833 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
6834 IdentifierInfo &II = Context.Idents.get(GV->getName());
6835 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
6836 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
6837
6838 const VarDecl *VD = nullptr;
6839 for (const auto *Result : DC->lookup(&II))
6840 if ((VD = dyn_cast<VarDecl>(Result)))
6841 break;
6842
6843 if (Triple.isOSBinFormatELF()) {
6844 if (!VD)
6845 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6846 } else {
6847 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6848 if (!VD || !VD->hasAttr<DLLExportAttr>())
6849 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6850 else
6851 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6852 }
6853
6854 setDSOLocal(GV);
6855 }
6856 }
6857
6858 // Decay array -> ptr
6859 CFConstantStringClassRef =
6860 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) : C;
6861 }
6862
6863 QualType CFTy = Context.getCFConstantStringType();
6864
6865 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
6866
6867 ConstantInitBuilder Builder(*this);
6868 auto Fields = Builder.beginStruct(STy);
6869
6870 // Class pointer.
6871 Fields.addSignedPointer(cast<llvm::Constant>(CFConstantStringClassRef),
6872 getCodeGenOpts().PointerAuth.ObjCIsaPointers,
6873 GlobalDecl(), QualType());
6874
6875 // Flags.
6876 if (IsSwiftABI) {
6877 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6878 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6879 } else {
6880 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6881 }
6882
6883 // String pointer.
6884 llvm::Constant *C = nullptr;
6885 if (isUTF16) {
6886 auto Arr = llvm::ArrayRef(
6887 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
6888 Entry.first().size() / 2);
6889 C = llvm::ConstantDataArray::get(VMContext, Arr);
6890 } else {
6891 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6892 }
6893
6894 // Note: -fwritable-strings doesn't make the backing store strings of
6895 // CFStrings writable.
6896 auto *GV =
6897 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
6898 llvm::GlobalValue::PrivateLinkage, C, ".str");
6899 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6900 // Don't enforce the target's minimum global alignment, since the only use
6901 // of the string is via this class initializer.
6902 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
6903 : Context.getTypeAlignInChars(Context.CharTy);
6904 GV->setAlignment(Align.getAsAlign());
6905
6906 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
6907 // Without it LLVM can merge the string with a non unnamed_addr one during
6908 // LTO. Doing that changes the section it ends in, which surprises ld64.
6909 if (Triple.isOSBinFormatMachO())
6910 GV->setSection(isUTF16 ? "__TEXT,__ustring"
6911 : "__TEXT,__cstring,cstring_literals");
6912 // Make sure the literal ends up in .rodata to allow for safe ICF and for
6913 // the static linker to adjust permissions to read-only later on.
6914 else if (Triple.isOSBinFormatELF())
6915 GV->setSection(".rodata");
6916
6917 // String.
6918 Fields.add(GV);
6919
6920 // String length.
6921 llvm::IntegerType *LengthTy =
6922 llvm::IntegerType::get(getModule().getContext(),
6923 Context.getTargetInfo().getLongWidth());
6924 if (IsSwiftABI) {
6925 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6926 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6927 LengthTy = Int32Ty;
6928 else
6929 LengthTy = IntPtrTy;
6930 }
6931 Fields.addInt(LengthTy, StringLength);
6932
6933 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6934 // properly aligned on 32-bit platforms.
6935 CharUnits Alignment =
6936 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
6937
6938 // The struct.
6939 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
6940 /*isConstant=*/false,
6941 llvm::GlobalVariable::PrivateLinkage);
6942 GV->addAttribute("objc_arc_inert");
6943 switch (Triple.getObjectFormat()) {
6944 case llvm::Triple::UnknownObjectFormat:
6945 llvm_unreachable("unknown file format");
6946 case llvm::Triple::DXContainer:
6947 case llvm::Triple::GOFF:
6948 case llvm::Triple::SPIRV:
6949 case llvm::Triple::XCOFF:
6950 llvm_unreachable("unimplemented");
6951 case llvm::Triple::COFF:
6952 case llvm::Triple::ELF:
6953 case llvm::Triple::Wasm:
6954 GV->setSection("cfstring");
6955 break;
6956 case llvm::Triple::MachO:
6957 GV->setSection("__DATA,__cfstring");
6958 break;
6959 }
6960 Entry.second = GV;
6961
6962 return ConstantAddress(GV, GV->getValueType(), Alignment);
6963 }
6964
6965 bool CodeGenModule::getExpressionLocationsEnabled() const {
6966 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6967 }
6968
6969 QualType CodeGenModule::getObjCFastEnumerationStateType() {
6970 if (ObjCFastEnumerationStateType.isNull()) {
6971 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
6972 D->startDefinition();
6973
6974 QualType FieldTypes[] = {
6975 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
6976 Context.getPointerType(Context.UnsignedLongTy),
6977 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
6978 nullptr, ArraySizeModifier::Normal, 0)};
6979
6980 for (size_t i = 0; i < 4; ++i) {
6981 FieldDecl *Field = FieldDecl::Create(Context,
6982 D,
6983 SourceLocation(),
6984 SourceLocation(), nullptr,
6985 FieldTypes[i], /*TInfo=*/nullptr,
6986 /*BitWidth=*/nullptr,
6987 /*Mutable=*/false,
6988 ICIS_NoInit);
6989 Field->setAccess(AS_public);
6990 D->addDecl(Field);
6991 }
6992
6993 D->completeDefinition();
6994 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
6995 }
6996
6997 return ObjCFastEnumerationStateType;
6998 }
6999
7000 llvm::Constant *
7001 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
7002 assert(!E->getType()->isPointerType() && "Strings are always arrays");
7003
7004 // Don't emit it as the address of the string, emit the string data itself
7005 // as an inline array.
7006 if (E->getCharByteWidth() == 1) {
7007 SmallString<64> Str(E->getString());
7008
7009 // Resize the string to the right size, which is indicated by its type.
7010 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
7011 assert(CAT && "String literal not of constant array type!");
7012 Str.resize(CAT->getZExtSize());
7013 return llvm::ConstantDataArray::getString(VMContext, Str, false);
7014 }
7015
7016 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
7017 llvm::Type *ElemTy = AType->getElementType();
7018 unsigned NumElements = AType->getNumElements();
7019
7020 // Wide strings have either 2-byte or 4-byte elements.
7021 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7022 SmallVector<uint16_t, 32> Elements;
7023 Elements.reserve(NumElements);
7024
7025 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
7026 Elements.push_back(E->getCodeUnit(i));
7027 Elements.resize(NumElements);
7028 return llvm::ConstantDataArray::get(VMContext, Elements);
7029 }
7030
7031 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7032 SmallVector<uint32_t, 32> Elements;
7033 Elements.reserve(NumElements);
7034
7035 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
7036 Elements.push_back(E->getCodeUnit(i));
7037 Elements.resize(NumElements);
7038 return llvm::ConstantDataArray::get(VMContext, Elements);
7039 }
7040
7041 static llvm::GlobalVariable *
7042 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
7043 CodeGenModule &CGM, StringRef GlobalName,
7044 CharUnits Alignment) {
7045 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
7046 CGM.GetGlobalConstantAddressSpace());
7047
7048 llvm::Module &M = CGM.getModule();
7049 // Create a global variable for this string
7050 auto *GV = new llvm::GlobalVariable(
7051 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
7052 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7053 GV->setAlignment(Alignment.getAsAlign());
7054 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7055 if (GV->isWeakForLinker()) {
7056 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
7057 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7058 }
7059 CGM.setDSOLocal(GV);
7060
7061 return GV;
7062 }
7063
7064 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
7065 /// constant array for the given string literal.
7066 ConstantAddress
7067 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
7068 StringRef Name) {
7069 CharUnits Alignment =
7070 getContext().getAlignOfGlobalVarInChars(S->getType(), /*VD=*/nullptr);
7071
7072 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
7073 llvm::GlobalVariable **Entry = nullptr;
7074 if (!LangOpts.WritableStrings) {
7075 Entry = &ConstantStringMap[C];
7076 if (auto GV = *Entry) {
7077 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
7078 GV->setAlignment(Alignment.getAsAlign());
7079 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
7080 GV->getValueType(), Alignment);
7081 }
7082 }
7083
7084 SmallString<256> MangledNameBuffer;
7085 StringRef GlobalVariableName;
7086 llvm::GlobalValue::LinkageTypes LT;
7087
7088 // Mangle the string literal if that's how the ABI merges duplicate strings.
7089 // Don't do it if they are writable, since we don't want writes in one TU to
7090 // affect strings in another.
7091 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7092 !LangOpts.WritableStrings) {
7093 llvm::raw_svector_ostream Out(MangledNameBuffer);
7094 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
7095 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7096 GlobalVariableName = MangledNameBuffer;
7097 } else {
7098 LT = llvm::GlobalValue::PrivateLinkage;
7099 GlobalVariableName = Name;
7100 }
7101
7102 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
7103
7104 CGDebugInfo *DI = getModuleDebugInfo();
7105 if (DI && getCodeGenOpts().hasReducedDebugInfo())
7106 DI->AddStringLiteralDebugInfo(GV, S);
7107
7108 if (Entry)
7109 *Entry = GV;
7110
7111 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
7112
7113 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
7114 GV->getValueType(), Alignment);
7115 }
7116
7117 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
7118 /// array for the given ObjCEncodeExpr node.
7119 ConstantAddress
7120 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
7121 std::string Str;
7122 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
7123
7124 return GetAddrOfConstantCString(Str);
7125 }
7126
7127 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
7128 /// the literal and a terminating '\0' character.
7129 /// The result has pointer to array type.
7130 ConstantAddress CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
7131 StringRef GlobalName) {
7132 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7133 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(
7134 getContext().CharTy, /*VD=*/nullptr);
7135
7136 llvm::Constant *C =
7137 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
7138
7139 // Don't share any string literals if strings aren't constant.
7140 llvm::GlobalVariable **Entry = nullptr;
7141 if (!LangOpts.WritableStrings) {
7142 Entry = &ConstantStringMap[C];
7143 if (auto GV = *Entry) {
7144 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
7145 GV->setAlignment(Alignment.getAsAlign());
7146 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
7147 GV->getValueType(), Alignment);
7148 }
7149 }
7150
7151 // Create a global variable for this.
7152 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
7153 GlobalName, Alignment);
7154 if (Entry)
7155 *Entry = GV;
7156
7157 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
7158 GV->getValueType(), Alignment);
7159 }
7160
7161 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
7162 const MaterializeTemporaryExpr *E, const Expr *Init) {
7163 assert((E->getStorageDuration() == SD_Static ||
7164 E->getStorageDuration() == SD_Thread) && "not a global temporary");
7165 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
7166
7167 // If we're not materializing a subobject of the temporary, keep the
7168 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
7169 QualType MaterializedType = Init->getType();
7170 if (Init == E->getSubExpr())
7171 MaterializedType = E->getType();
7172
7173 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
7174
7175 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
7176 if (!InsertResult.second) {
7177 // We've seen this before: either we already created it or we're in the
7178 // process of doing so.
7179 if (!InsertResult.first->second) {
7180 // We recursively re-entered this function, probably during emission of
7181 // the initializer. Create a placeholder. We'll clean this up in the
7182 // outer call, at the end of this function.
7183 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
7184 InsertResult.first->second = new llvm::GlobalVariable(
7185 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
7186 nullptr);
7187 }
7188 return ConstantAddress(InsertResult.first->second,
7189 llvm::cast<llvm::GlobalVariable>(
7190 InsertResult.first->second->stripPointerCasts())
7191 ->getValueType(),
7192 Align);
7193 }
7194
7195 // FIXME: If an externally-visible declaration extends multiple temporaries,
7196 // we need to give each temporary the same name in every translation unit (and
7197 // we also need to make the temporaries externally-visible).
7198 SmallString<256> Name;
7199 llvm::raw_svector_ostream Out(Name);
7200 getCXXABI().getMangleContext().mangleReferenceTemporary(
7201 VD, E->getManglingNumber(), Out);
7202
7203 APValue *Value = nullptr;
7204 if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) {
7205 // If the initializer of the extending declaration is a constant
7206 // initializer, we should have a cached constant initializer for this
7207 // temporary. Note that this might have a different value from the value
7208 // computed by evaluating the initializer if the surrounding constant
7209 // expression modifies the temporary.
7210 Value = E->getOrCreateValue(false);
7211 }
7212
7213 // Try evaluating it now, it might have a constant initializer.
7214 Expr::EvalResult EvalResult;
7215 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
7216 !EvalResult.hasSideEffects())
7217 Value = &EvalResult.Val;
7218
7219 LangAS AddrSpace = GetGlobalVarAddressSpace(VD);
7220
7221 std::optional<ConstantEmitter> emitter;
7222 llvm::Constant *InitialValue = nullptr;
7223 bool Constant = false;
7224 llvm::Type *Type;
7225 if (Value) {
7226 // The temporary has a constant initializer, use it.
7227 emitter.emplace(*this);
7228 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
7229 MaterializedType);
7230 Constant =
7231 MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value,
7232 /*ExcludeDtor*/ false);
7233 Type = InitialValue->getType();
7234 } else {
7235 // No initializer, the initialization will be provided when we
7236 // initialize the declaration which performed lifetime extension.
7237 Type = getTypes().ConvertTypeForMem(MaterializedType);
7238 }
7239
7240 // Create a global variable for this lifetime-extended temporary.
7241 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
7242 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
7243 const VarDecl *InitVD;
7244 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7245 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
7246 // Temporaries defined inside a class get linkonce_odr linkage because the
7247 // class can be defined in multiple translation units.
7248 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7249 } else {
7250 // There is no need for this temporary to have external linkage if the
7251 // VarDecl has external linkage.
7252 Linkage = llvm::GlobalVariable::InternalLinkage;
7253 }
7254 }
7255 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
7256 auto *GV = new llvm::GlobalVariable(
7257 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
7258 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7259 if (emitter) emitter->finalize(GV);
7260 // Don't assign dllimport or dllexport to local linkage globals.
7261 if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
7262 setGVProperties(GV, VD);
7263 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7264 // The reference temporary should never be dllexport.
7265 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7266 }
7267 GV->setAlignment(Align.getAsAlign());
7268 if (supportsCOMDAT() && GV->isWeakForLinker())
7269 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7270 if (VD->getTLSKind())
7271 setTLSMode(GV, *VD);
7272 llvm::Constant *CV = GV;
7273 if (AddrSpace != LangAS::Default)
7274 CV = getTargetCodeGenInfo().performAddrSpaceCast(
7275 *this, GV, AddrSpace,
7276 llvm::PointerType::get(
7277 getLLVMContext(),
7278 getContext().getTargetAddressSpace(LangAS::Default)));
7279
7280 // Update the map with the new temporary. If we created a placeholder above,
7281 // replace it with the new global now.
7282 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7283 if (Entry) {
7284 Entry->replaceAllUsesWith(CV);
7285 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7286 }
7287 Entry = CV;
7288
7289 return ConstantAddress(CV, Type, Align);
7290 }
7291
7292 /// EmitObjCPropertyImplementations - Emit information for synthesized
7293 /// properties for an implementation.
7294 void CodeGenModule::EmitObjCPropertyImplementations(const
7295 ObjCImplementationDecl *D) {
7296 for (const auto *PID : D->property_impls()) {
7297 // Dynamic is just for type-checking.
7298 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
7299 ObjCPropertyDecl *PD = PID->getPropertyDecl();
7300
7301 // Determine which methods need to be implemented, some may have
7302 // been overridden. Note that ::isPropertyAccessor is not the method
7303 // we want, that just indicates if the decl came from a
7304 // property. What we want to know is if the method is defined in
7305 // this implementation.
7306 auto *Getter = PID->getGetterMethodDecl();
7307 if (!Getter || Getter->isSynthesizedAccessorStub())
7308 CodeGenFunction(*this).GenerateObjCGetter(
7309 const_cast<ObjCImplementationDecl *>(D), PID);
7310 auto *Setter = PID->getSetterMethodDecl();
7311 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7312 CodeGenFunction(*this).GenerateObjCSetter(
7313 const_cast<ObjCImplementationDecl *>(D), PID);
7314 }
7315 }
7316 }
7317
7318 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
7319 const ObjCInterfaceDecl *iface = impl->getClassInterface();
7320 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
7321 ivar; ivar = ivar->getNextIvar())
7322 if (ivar->getType().isDestructedType())
7323 return true;
7324
7325 return false;
7326 }
7327
7328 static bool AllTrivialInitializers(CodeGenModule &CGM,
7329 ObjCImplementationDecl *D) {
7330 CodeGenFunction CGF(CGM);
7331 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
7332 E = D->init_end(); B != E; ++B) {
7333 CXXCtorInitializer *CtorInitExp = *B;
7334 Expr *Init = CtorInitExp->getInit();
7335 if (!CGF.isTrivialInitializer(Init))
7336 return false;
7337 }
7338 return true;
7339 }
7340
7341 /// EmitObjCIvarInitializations - Emit information for ivar initialization
7342 /// for an implementation.
7343 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7344 // We might need a .cxx_destruct even if we don't have any ivar initializers.
7345 if (needsDestructMethod(D)) {
7346 const IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
7347 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
7348 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
7349 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
7350 getContext().VoidTy, nullptr, D,
7351 /*isInstance=*/true, /*isVariadic=*/false,
7352 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
7353 /*isImplicitlyDeclared=*/true,
7354 /*isDefined=*/false, ObjCImplementationControl::Required);
7355 D->addInstanceMethod(DTORMethod);
7356 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
7357 D->setHasDestructors(true);
7358 }
7359
7360 // If the implementation doesn't have any ivar initializers, we don't need
7361 // a .cxx_construct.
7362 if (D->getNumIvarInitializers() == 0 ||
7363 AllTrivialInitializers(*this, D))
7364 return;
7365
7366 const IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
7367 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
7368 // The constructor returns 'self'.
7369 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
7370 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
7371 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
7372 /*isVariadic=*/false,
7373 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
7374 /*isImplicitlyDeclared=*/true,
7375 /*isDefined=*/false, ObjCImplementationControl::Required);
7376 D->addInstanceMethod(CTORMethod);
7377 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
7378 D->setHasNonZeroConstructors(true);
7379 }
7380
7381 // EmitLinkageSpec - Emit all declarations in a linkage spec.
7382 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
7383 if (LSD->getLanguage() != LinkageSpecLanguageIDs::C &&
7384 LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) {
7385 ErrorUnsupported(LSD, "linkage spec");
7386 return;
7387 }
7388
7389 EmitDeclContext(LSD);
7390 }
7391
7392 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
7393 // Device code should not be at top level.
7394 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7395 return;
7396
7397 std::unique_ptr<CodeGenFunction> &CurCGF =
7398 GlobalTopLevelStmtBlockInFlight.first;
7399
7400 // We emitted a top-level stmt but after it there is initialization.
7401 // Stop squashing the top-level stmts into a single function.
7402 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7403 CurCGF->FinishFunction(D->getEndLoc());
7404 CurCGF = nullptr;
7405 }
7406
7407 if (!CurCGF) {
7408 // void __stmts__N(void)
7409 // FIXME: Ask the ABI name mangler to pick a name.
7410 std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
7411 FunctionArgList Args;
7412 QualType RetTy = getContext().VoidTy;
7413 const CGFunctionInfo &FnInfo =
7414 getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
7415 llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
7416 llvm::Function *Fn = llvm::Function::Create(
7417 FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
7418
7419 CurCGF.reset(new CodeGenFunction(*this));
7420 GlobalTopLevelStmtBlockInFlight.second = D;
7421 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7422 D->getBeginLoc(), D->getBeginLoc());
7423 CXXGlobalInits.push_back(Fn);
7424 }
7425
7426 CurCGF->EmitStmt(D->getStmt());
7427 }
7428
7429 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
7430 for (auto *I : DC->decls()) {
7431 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
7432 // are themselves considered "top-level", so EmitTopLevelDecl on an
7433 // ObjCImplDecl does not recursively visit them. We need to do that in
7434 // case they're nested inside another construct (LinkageSpecDecl /
7435 // ExportDecl) that does stop them from being considered "top-level".
7436 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7437 for (auto *M : OID->methods())
7438 EmitTopLevelDecl(M);
7439 }
7440
7441 EmitTopLevelDecl(I);
7442 }
7443 }
7444
7445 /// EmitTopLevelDecl - Emit code for a single top level declaration.
7446 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
7447 // Ignore dependent declarations.
7448 if (D->isTemplated())
7449 return;
7450
7451 // Consteval function shouldn't be emitted.
7452 if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
7453 return;
7454
7455 switch (D->getKind()) {
7456 case Decl::CXXConversion:
7457 case Decl::CXXMethod:
7458 case Decl::Function:
7459 EmitGlobal(cast<FunctionDecl>(D));
7460 // Always provide some coverage mapping
7461 // even for the functions that aren't emitted.
7462 AddDeferredUnusedCoverageMapping(D);
7463 break;
7464
7465 case Decl::CXXDeductionGuide:
7466 // Function-like, but does not result in code emission.
7467 break;
7468
7469 case Decl::Var:
7470 case Decl::Decomposition:
7471 case Decl::VarTemplateSpecialization:
7472 EmitGlobal(cast<VarDecl>(D));
7473 if (auto *DD = dyn_cast<DecompositionDecl>(D))
7474 for (auto *B : DD->flat_bindings())
7475 if (auto *HD = B->getHoldingVar())
7476 EmitGlobal(HD);
7477
7478 break;
7479
7480 // Indirect fields from global anonymous structs and unions can be
7481 // ignored; only the actual variable requires IR gen support.
7482 case Decl::IndirectField:
7483 break;
7484
7485 // C++ Decls
7486 case Decl::Namespace:
7487 EmitDeclContext(cast<NamespaceDecl>(D));
7488 break;
7489 case Decl::ClassTemplateSpecialization: {
7490 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
7491 if (CGDebugInfo *DI = getModuleDebugInfo())
7492 if (Spec->getSpecializationKind() ==
7493 TSK_ExplicitInstantiationDefinition &&
7494 Spec->hasDefinition())
7495 DI->completeTemplateDefinition(*Spec);
7496 } [[fallthrough]];
7497 case Decl::CXXRecord: {
7498 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
7499 if (CGDebugInfo *DI = getModuleDebugInfo()) {
7500 if (CRD->hasDefinition())
7501 DI->EmitAndRetainType(
7502 getContext().getCanonicalTagType(cast<RecordDecl>(D)));
7503 if (auto *ES = D->getASTContext().getExternalSource())
7504 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
7505 DI->completeUnusedClass(*CRD);
7506 }
7507 // Emit any static data members, they may be definitions.
7508 for (auto *I : CRD->decls())
7509 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I) || isa<EnumDecl>(I))
7510 EmitTopLevelDecl(I);
7511 break;
7512 }
7513 // No code generation needed.
7514 case Decl::UsingShadow:
7515 case Decl::ClassTemplate:
7516 case Decl::VarTemplate:
7517 case Decl::Concept:
7518 case Decl::VarTemplatePartialSpecialization:
7519 case Decl::FunctionTemplate:
7520 case Decl::TypeAliasTemplate:
7521 case Decl::Block:
7522 case Decl::Empty:
7523 case Decl::Binding:
7524 break;
7525 case Decl::Using: // using X; [C++]
7526 if (CGDebugInfo *DI = getModuleDebugInfo())
7527 DI->EmitUsingDecl(cast<UsingDecl>(*D));
7528 break;
7529 case Decl::UsingEnum: // using enum X; [C++]
7530 if (CGDebugInfo *DI = getModuleDebugInfo())
7531 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
7532 break;
7533 case Decl::NamespaceAlias:
7534 if (CGDebugInfo *DI = getModuleDebugInfo())
7535 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
7536 break;
7537 case Decl::UsingDirective: // using namespace X; [C++]
7538 if (CGDebugInfo *DI = getModuleDebugInfo())
7539 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
7540 break;
7541 case Decl::CXXConstructor:
7542 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
7543 break;
7544 case Decl::CXXDestructor:
7545 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
7546 break;
7547
7548 case Decl::StaticAssert:
7549 // Nothing to do.
7550 break;
7551
7552 // Objective-C Decls
7553
7554 // Forward declarations, no (immediate) code generation.
7555 case Decl::ObjCInterface:
7556 case Decl::ObjCCategory:
7557 break;
7558
7559 case Decl::ObjCProtocol: {
7560 auto *Proto = cast<ObjCProtocolDecl>(D);
7561 if (Proto->isThisDeclarationADefinition())
7562 ObjCRuntime->GenerateProtocol(Proto);
7563 break;
7564 }
7565
7566 case Decl::ObjCCategoryImpl:
7567 // Categories have properties but don't support synthesize so we
7568 // can ignore them here.
7569 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
7570 break;
7571
7572 case Decl::ObjCImplementation: {
7573 auto *OMD = cast<ObjCImplementationDecl>(D);
7574 EmitObjCPropertyImplementations(OMD);
7575 EmitObjCIvarInitializations(OMD);
7576 ObjCRuntime->GenerateClass(OMD);
7577 // Emit global variable debug information.
7578 if (CGDebugInfo *DI = getModuleDebugInfo())
7579 if (getCodeGenOpts().hasReducedDebugInfo())
7580 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
7581 OMD->getClassInterface()), OMD->getLocation());
7582 break;
7583 }
7584 case Decl::ObjCMethod: {
7585 auto *OMD = cast<ObjCMethodDecl>(D);
7586 // If this is not a prototype, emit the body.
7587 if (OMD->getBody())
7588 CodeGenFunction(*this).GenerateObjCMethod(OMD);
7589 break;
7590 }
7591 case Decl::ObjCCompatibleAlias:
7592 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
7593 break;
7594
7595 case Decl::PragmaComment: {
7596 const auto *PCD = cast<PragmaCommentDecl>(D);
7597 switch (PCD->getCommentKind()) {
7598 case PCK_Unknown:
7599 llvm_unreachable("unexpected pragma comment kind");
7600 case PCK_Linker:
7601 AppendLinkerOptions(PCD->getArg());
7602 break;
7603 case PCK_Lib:
7604 AddDependentLib(PCD->getArg());
7605 break;
7606 case PCK_Compiler:
7607 case PCK_ExeStr:
7608 case PCK_User:
7609 break; // We ignore all of these.
7610 }
7611 break;
7612 }
7613
7614 case Decl::PragmaDetectMismatch: {
7615 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
7616 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
7617 break;
7618 }
7619
7620 case Decl::LinkageSpec:
7621 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
7622 break;
7623
7624 case Decl::FileScopeAsm: {
7625 // File-scope asm is ignored during device-side CUDA compilation.
7626 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7627 break;
7628 // File-scope asm is ignored during device-side OpenMP compilation.
7629 if (LangOpts.OpenMPIsTargetDevice)
7630 break;
7631 // File-scope asm is ignored during device-side SYCL compilation.
7632 if (LangOpts.SYCLIsDevice)
7633 break;
7634 auto *AD = cast<FileScopeAsmDecl>(D);
7635 getModule().appendModuleInlineAsm(AD->getAsmString());
7636 break;
7637 }
7638
7639 case Decl::TopLevelStmt:
7640 EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
7641 break;
7642
7643 case Decl::Import: {
7644 auto *Import = cast<ImportDecl>(D);
7645
7646 // If we've already imported this module, we're done.
7647 if (!ImportedModules.insert(Import->getImportedModule()))
7648 break;
7649
7650 // Emit debug information for direct imports.
7651 if (!Import->getImportedOwningModule()) {
7652 if (CGDebugInfo *DI = getModuleDebugInfo())
7653 DI->EmitImportDecl(*Import);
7654 }
7655
7656 // For C++ standard modules we are done - we will call the module
7657 // initializer for imported modules, and that will likewise call those for
7658 // any imports it has.
7659 if (CXX20ModuleInits && Import->getImportedModule() &&
7660 Import->getImportedModule()->isNamedModule())
7661 break;
7662
7663 // For clang C++ module map modules the initializers for sub-modules are
7664 // emitted here.
7665
7666 // Find all of the submodules and emit the module initializers.
7667 llvm::SmallPtrSet<clang::Module *, 16> Visited;
7668 SmallVector<clang::Module *, 16> Stack;
7669 Visited.insert(Import->getImportedModule());
7670 Stack.push_back(Import->getImportedModule());
7671
7672 while (!Stack.empty()) {
7673 clang::Module *Mod = Stack.pop_back_val();
7674 if (!EmittedModuleInitializers.insert(Mod).second)
7675 continue;
7676
7677 for (auto *D : Context.getModuleInitializers(Mod))
7678 EmitTopLevelDecl(D);
7679
7680 // Visit the submodules of this module.
7681 for (auto *Submodule : Mod->submodules()) {
7682 // Skip explicit children; they need to be explicitly imported to emit
7683 // the initializers.
7684 if (Submodule->IsExplicit)
7685 continue;
7686
7687 if (Visited.insert(Submodule).second)
7688 Stack.push_back(Submodule);
7689 }
7690 }
7691 break;
7692 }
7693
7694 case Decl::Export:
7695 EmitDeclContext(cast<ExportDecl>(D));
7696 break;
7697
7698 case Decl::OMPThreadPrivate:
7699 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
7700 break;
7701
7702 case Decl::OMPAllocate:
7703 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
7704 break;
7705
7706 case Decl::OMPDeclareReduction:
7707 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
7708 break;
7709
7710 case Decl::OMPDeclareMapper:
7711 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
7712 break;
7713
7714 case Decl::OMPRequires:
7715 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
7716 break;
7717
7718 case Decl::Typedef:
7719 case Decl::TypeAlias: // using foo = bar; [C++11]
7720 if (CGDebugInfo *DI = getModuleDebugInfo())
7721 DI->EmitAndRetainType(getContext().getTypedefType(
7722 ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
7723 cast<TypedefNameDecl>(D)));
7724 break;
7725
7726 case Decl::Record:
7727 if (CGDebugInfo *DI = getModuleDebugInfo())
7728 if (cast<RecordDecl>(D)->getDefinition())
7729 DI->EmitAndRetainType(
7730 getContext().getCanonicalTagType(cast<RecordDecl>(D)));
7731 break;
7732
7733 case Decl::Enum:
7734 if (CGDebugInfo *DI = getModuleDebugInfo())
7735 if (cast<EnumDecl>(D)->getDefinition())
7736 DI->EmitAndRetainType(
7737 getContext().getCanonicalTagType(cast<EnumDecl>(D)));
7738 break;
7739
7740 case Decl::HLSLRootSignature:
7741 getHLSLRuntime().addRootSignature(cast<HLSLRootSignatureDecl>(D));
7742 break;
7743 case Decl::HLSLBuffer:
7744 getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
7745 break;
7746
7747 case Decl::OpenACCDeclare:
7748 EmitOpenACCDeclare(cast<OpenACCDeclareDecl>(D));
7749 break;
7750 case Decl::OpenACCRoutine:
7751 EmitOpenACCRoutine(cast<OpenACCRoutineDecl>(D));
7752 break;
7753
7754 default:
7755 // Make sure we handled everything we should, every other kind is a
7756 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
7757 // function. Need to recode Decl::Kind to do that easily.
7758 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
7759 break;
7760 }
7761 }
7762
7763 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
7764 // Do we need to generate coverage mapping?
7765 if (!CodeGenOpts.CoverageMapping)
7766 return;
7767 switch (D->getKind()) {
7768 case Decl::CXXConversion:
7769 case Decl::CXXMethod:
7770 case Decl::Function:
7771 case Decl::ObjCMethod:
7772 case Decl::CXXConstructor:
7773 case Decl::CXXDestructor: {
7774 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
7775 break;
7776 SourceManager &SM = getContext().getSourceManager();
7777 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
7778 break;
7779 if (!llvm::coverage::SystemHeadersCoverage &&
7780 SM.isInSystemHeader(D->getBeginLoc()))
7781 break;
7782 DeferredEmptyCoverageMappingDecls.try_emplace(D, true);
7783 break;
7784 }
7785 default:
7786 break;
7787 };
7788 }
7789
7790 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
7791 // Do we need to generate coverage mapping?
7792 if (!CodeGenOpts.CoverageMapping)
7793 return;
7794 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7795 if (Fn->isTemplateInstantiation())
7796 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
7797 }
7798 DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false);
7799 }
7800
7801 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
7802 // We call takeVector() here to avoid use-after-free.
7803 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
7804 // we deserialize function bodies to emit coverage info for them, and that
7805 // deserializes more declarations. How should we handle that case?
7806 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7807 if (!Entry.second)
7808 continue;
7809 const Decl *D = Entry.first;
7810 switch (D->getKind()) {
7811 case Decl::CXXConversion:
7812 case Decl::CXXMethod:
7813 case Decl::Function:
7814 case Decl::ObjCMethod: {
7815 CodeGenPGO PGO(*this);
7816 GlobalDecl GD(cast<FunctionDecl>(D));
7817 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7818 getFunctionLinkage(GD));
7819 break;
7820 }
7821 case Decl::CXXConstructor: {
7822 CodeGenPGO PGO(*this);
7823 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
7824 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7825 getFunctionLinkage(GD));
7826 break;
7827 }
7828 case Decl::CXXDestructor: {
7829 CodeGenPGO PGO(*this);
7830 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
7831 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7832 getFunctionLinkage(GD));
7833 break;
7834 }
7835 default:
7836 break;
7837 };
7838 }
7839 }
7840
7841 void CodeGenModule::EmitMainVoidAlias() {
7842 // In order to transition away from "__original_main" gracefully, emit an
7843 // alias for "main" in the no-argument case so that libc can detect when
7844 // new-style no-argument main is in used.
7845 if (llvm::Function *F = getModule().getFunction("main")) {
7846 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7847 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
7848 auto *GA = llvm::GlobalAlias::create("__main_void", F);
7849 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7850 }
7851 }
7852 }
7853
7854 /// Turns the given pointer into a constant.
7855 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
7856 const void *Ptr) {
7857 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
7858 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7859 return llvm::ConstantInt::get(i64, PtrInt);
7860 }
7861
7862 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
7863 llvm::NamedMDNode *&GlobalMetadata,
7864 GlobalDecl D,
7865 llvm::GlobalValue *Addr) {
7866 if (!GlobalMetadata)
7867 GlobalMetadata =
7868 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
7869
7870 // TODO: should we report variant information for ctors/dtors?
7871 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7872 llvm::ConstantAsMetadata::get(GetPointerConstant(
7873 CGM.getLLVMContext(), D.getDecl()))};
7874 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
7875 }
7876
7877 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7878 llvm::GlobalValue *CppFunc) {
7879 // Store the list of ifuncs we need to replace uses in.
7880 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
7881 // List of ConstantExprs that we should be able to delete when we're done
7882 // here.
7883 llvm::SmallVector<llvm::ConstantExpr *> CEs;
7884
7885 // It isn't valid to replace the extern-C ifuncs if all we find is itself!
7886 if (Elem == CppFunc)
7887 return false;
7888
7889 // First make sure that all users of this are ifuncs (or ifuncs via a
7890 // bitcast), and collect the list of ifuncs and CEs so we can work on them
7891 // later.
7892 for (llvm::User *User : Elem->users()) {
7893 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
7894 // ifunc directly. In any other case, just give up, as we don't know what we
7895 // could break by changing those.
7896 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7897 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7898 return false;
7899
7900 for (llvm::User *CEUser : ConstExpr->users()) {
7901 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7902 IFuncs.push_back(IFunc);
7903 } else {
7904 return false;
7905 }
7906 }
7907 CEs.push_back(ConstExpr);
7908 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7909 IFuncs.push_back(IFunc);
7910 } else {
7911 // This user is one we don't know how to handle, so fail redirection. This
7912 // will result in an ifunc retaining a resolver name that will ultimately
7913 // fail to be resolved to a defined function.
7914 return false;
7915 }
7916 }
7917
7918 // Now we know this is a valid case where we can do this alias replacement, we
7919 // need to remove all of the references to Elem (and the bitcasts!) so we can
7920 // delete it.
7921 for (llvm::GlobalIFunc *IFunc : IFuncs)
7922 IFunc->setResolver(nullptr);
7923 for (llvm::ConstantExpr *ConstExpr : CEs)
7924 ConstExpr->destroyConstant();
7925
7926 // We should now be out of uses for the 'old' version of this function, so we
7927 // can erase it as well.
7928 Elem->eraseFromParent();
7929
7930 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7931 // The type of the resolver is always just a function-type that returns the
7932 // type of the IFunc, so create that here. If the type of the actual
7933 // resolver doesn't match, it just gets bitcast to the right thing.
7934 auto *ResolverTy =
7935 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
7936 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7937 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
7938 IFunc->setResolver(Resolver);
7939 }
7940 return true;
7941 }
7942
7943 /// For each function which is declared within an extern "C" region and marked
7944 /// as 'used', but has internal linkage, create an alias from the unmangled
7945 /// name to the mangled name if possible. People expect to be able to refer
7946 /// to such functions with an unmangled name from inline assembly within the
7947 /// same translation unit.
7948 void CodeGenModule::EmitStaticExternCAliases() {
7949 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
7950 return;
7951 for (auto &I : StaticExternCValues) {
7952 const IdentifierInfo *Name = I.first;
7953 llvm::GlobalValue *Val = I.second;
7954
7955 // If Val is null, that implies there were multiple declarations that each
7956 // had a claim to the unmangled name. In this case, generation of the alias
7957 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
7958 if (!Val)
7959 break;
7960
7961 llvm::GlobalValue *ExistingElem =
7962 getModule().getNamedValue(Name->getName());
7963
7964 // If there is either not something already by this name, or we were able to
7965 // replace all uses from IFuncs, create the alias.
7966 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7967 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
7968 }
7969 }
7970
7971 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
7972 GlobalDecl &Result) const {
7973 auto Res = Manglings.find(MangledName);
7974 if (Res == Manglings.end())
7975 return false;
7976 Result = Res->getValue();
7977 return true;
7978 }
7979
7980 /// Emits metadata nodes associating all the global values in the
7981 /// current module with the Decls they came from. This is useful for
7982 /// projects using IR gen as a subroutine.
7983 ///
7984 /// Since there's currently no way to associate an MDNode directly
7985 /// with an llvm::GlobalValue, we create a global named metadata
7986 /// with the name 'clang.global.decl.ptrs'.
7987 void CodeGenModule::EmitDeclMetadata() {
7988 llvm::NamedMDNode *GlobalMetadata = nullptr;
7989
7990 for (auto &I : MangledDeclNames) {
7991 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
7992 // Some mangled names don't necessarily have an associated GlobalValue
7993 // in this module, e.g. if we mangled it for DebugInfo.
7994 if (Addr)
7995 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
7996 }
7997 }
7998
7999 /// Emits metadata nodes for all the local variables in the current
8000 /// function.
8001 void CodeGenFunction::EmitDeclMetadata() {
8002 if (LocalDeclMap.empty()) return;
8003
8004 llvm::LLVMContext &Context = getLLVMContext();
8005
8006 // Find the unique metadata ID for this name.
8007 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
8008
8009 llvm::NamedMDNode *GlobalMetadata = nullptr;
8010
8011 for (auto &I : LocalDeclMap) {
8012 const Decl *D = I.first;
8013 llvm::Value *Addr = I.second.emitRawPointer(*this);
8014 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
8015 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
8016 Alloca->setMetadata(
8017 DeclPtrKind, llvm::MDNode::get(
8018 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8019 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
8020 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
8021 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
8022 }
8023 }
8024 }
8025
8026 void CodeGenModule::EmitVersionIdentMetadata() {
8027 llvm::NamedMDNode *IdentMetadata =
8028 TheModule.getOrInsertNamedMetadata("llvm.ident");
8029 std::string Version = getClangFullVersion();
8030 llvm::LLVMContext &Ctx = TheModule.getContext();
8031
8032 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8033 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8034 }
8035
8036 void CodeGenModule::EmitCommandLineMetadata() {
8037 llvm::NamedMDNode *CommandLineMetadata =
8038 TheModule.getOrInsertNamedMetadata("llvm.commandline");
8039 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
8040 llvm::LLVMContext &Ctx = TheModule.getContext();
8041
8042 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8043 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8044 }
8045
8046 void CodeGenModule::EmitCoverageFile() {
8047 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
8048 if (!CUNode)
8049 return;
8050
8051 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
8052 llvm::LLVMContext &Ctx = TheModule.getContext();
8053 auto *CoverageDataFile =
8054 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
8055 auto *CoverageNotesFile =
8056 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
8057 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8058 llvm::MDNode *CU = CUNode->getOperand(i);
8059 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8060 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8061 }
8062 }
8063
8064 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
8065 bool ForEH) {
8066 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
8067 // FIXME: should we even be calling this method if RTTI is disabled
8068 // and it's not for EH?
8069 if (!shouldEmitRTTI(ForEH))
8070 return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
8071
8072 if (ForEH && Ty->isObjCObjectPointerType() &&
8073 LangOpts.ObjCRuntime.isGNUFamily())
8074 return ObjCRuntime->GetEHType(Ty);
8075
8076 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
8077 }
8078
8079 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
8080 // Do not emit threadprivates in simd-only mode.
8081 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8082 return;
8083 for (auto RefExpr : D->varlist()) {
8084 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
8085 bool PerformInit =
8086 VD->getAnyInitializer() &&
8087 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
8088 /*ForRef=*/false);
8089
8090 Address Addr(GetAddrOfGlobalVar(VD),
8091 getTypes().ConvertTypeForMem(VD->getType()),
8092 getContext().getDeclAlign(VD));
8093 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
8094 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
8095 CXXGlobalInits.push_back(InitFunction);
8096 }
8097 }
8098
8099 llvm::Metadata *
8100 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
8101 StringRef Suffix) {
8102 if (auto *FnType = T->getAs<FunctionProtoType>())
8103 T = getContext().getFunctionType(
8104 FnType->getReturnType(), FnType->getParamTypes(),
8105 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
8106
8107 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
8108 if (InternalId)
8109 return InternalId;
8110
8111 if (isExternallyVisible(T->getLinkage())) {
8112 std::string OutName;
8113 llvm::raw_string_ostream Out(OutName);
8114 getCXXABI().getMangleContext().mangleCanonicalTypeName(
8115 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
8116
8117 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
8118 Out << ".normalized";
8119
8120 Out << Suffix;
8121
8122 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
8123 } else {
8124 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
8125 llvm::ArrayRef<llvm::Metadata *>());
8126 }
8127
8128 return InternalId;
8129 }
8130
8131 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForFnType(QualType T) {
8132 assert(isa<FunctionType>(T));
8133 T = GeneralizeFunctionType(
8134 getContext(), T, getCodeGenOpts().SanitizeCfiICallGeneralizePointers);
8135 if (getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
8136 return CreateMetadataIdentifierGeneralized(T);
8137 return CreateMetadataIdentifierForType(T);
8138 }
8139
8140 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
8141 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
8142 }
8143
8144 llvm::Metadata *
8145 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
8146 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
8147 }
8148
8149 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
8150 return CreateMetadataIdentifierImpl(T, GeneralizedMetadataIdMap,
8151 ".generalized");
8152 }
8153
8154 /// Returns whether this module needs the "all-vtables" type identifier.
8155 bool CodeGenModule::NeedAllVtablesTypeId() const {
8156 // Returns true if at least one of vtable-based CFI checkers is enabled and
8157 // is not in the trapping mode.
8158 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8159 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8160 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8161 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8162 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8163 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8164 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8165 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8166 }
8167
8168 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
8169 CharUnits Offset,
8170 const CXXRecordDecl *RD) {
8171 CanQualType T = getContext().getCanonicalTagType(RD);
8172 llvm::Metadata *MD = CreateMetadataIdentifierForType(T);
8173 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8174
8175 if (CodeGenOpts.SanitizeCfiCrossDso)
8176 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
8177 VTable->addTypeMetadata(Offset.getQuantity(),
8178 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8179
8180 if (NeedAllVtablesTypeId()) {
8181 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
8182 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8183 }
8184 }
8185
8186 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
8187 if (!SanStats)
8188 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
8189
8190 return *SanStats;
8191 }
8192
8193 llvm::Value *
8194 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
8195 CodeGenFunction &CGF) {
8196 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
8197 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
8198 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
8199 auto *Call = CGF.EmitRuntimeCall(
8200 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
8201 return Call;
8202 }
8203
8204 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
8205 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
8206 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
8207 /* forPointeeType= */ true);
8208 }
8209
8210 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
8211 LValueBaseInfo *BaseInfo,
8212 TBAAAccessInfo *TBAAInfo,
8213 bool forPointeeType) {
8214 if (TBAAInfo)
8215 *TBAAInfo = getTBAAAccessInfo(T);
8216
8217 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
8218 // that doesn't return the information we need to compute BaseInfo.
8219
8220 // Honor alignment typedef attributes even on incomplete types.
8221 // We also honor them straight for C++ class types, even as pointees;
8222 // there's an expressivity gap here.
8223 if (auto TT = T->getAs<TypedefType>()) {
8224 if (auto Align = TT->getDecl()->getMaxAlignment()) {
8225 if (BaseInfo)
8226 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
8227 return getContext().toCharUnitsFromBits(Align);
8228 }
8229 }
8230
8231 bool AlignForArray = T->isArrayType();
8232
8233 // Analyze the base element type, so we don't get confused by incomplete
8234 // array types.
8235 T = getContext().getBaseElementType(T);
8236
8237 if (T->isIncompleteType()) {
8238 // We could try to replicate the logic from
8239 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
8240 // type is incomplete, so it's impossible to test. We could try to reuse
8241 // getTypeAlignIfKnown, but that doesn't return the information we need
8242 // to set BaseInfo. So just ignore the possibility that the alignment is
8243 // greater than one.
8244 if (BaseInfo)
8245 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
8246 return CharUnits::One();
8247 }
8248
8249 if (BaseInfo)
8250 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
8251
8252 CharUnits Alignment;
8253 const CXXRecordDecl *RD;
8254 if (T.getQualifiers().hasUnaligned()) {
8255 Alignment = CharUnits::One();
8256 } else if (forPointeeType && !AlignForArray &&
8257 (RD = T->getAsCXXRecordDecl())) {
8258 // For C++ class pointees, we don't know whether we're pointing at a
8259 // base or a complete object, so we generally need to use the
8260 // non-virtual alignment.
8261 Alignment = getClassPointerAlignment(RD);
8262 } else {
8263 Alignment = getContext().getTypeAlignInChars(T);
8264 }
8265
8266 // Cap to the global maximum type alignment unless the alignment
8267 // was somehow explicit on the type.
8268 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
8269 if (Alignment.getQuantity() > MaxAlign &&
8270 !getContext().isAlignmentRequired(T))
8271 Alignment = CharUnits::fromQuantity(MaxAlign);
8272 }
8273 return Alignment;
8274 }
8275
8276 bool CodeGenModule::stopAutoInit() {
8277 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
8278 if (StopAfter) {
8279 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
8280 // used
8281 if (NumAutoVarInit >= StopAfter) {
8282 return true;
8283 }
8284 if (!NumAutoVarInit) {
8285 getDiags().Report(diag::warn_trivial_auto_var_limit)
8286 << StopAfter
8287 << (getContext().getLangOpts().getTrivialAutoVarInit() ==
8288 LangOptions::TrivialAutoVarInitKind::Zero
8289 ? "zero"
8290 : "pattern");
8291 }
8292 ++NumAutoVarInit;
8293 }
8294 return false;
8295 }
8296
8297 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
8298 const Decl *D) const {
8299 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
8300 // postfix beginning with '.' since the symbol name can be demangled.
8301 if (LangOpts.HIP)
8302 OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
8303 else
8304 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
8305
8306 // If the CUID is not specified we try to generate a unique postfix.
8307 if (getLangOpts().CUID.empty()) {
8308 SourceManager &SM = getContext().getSourceManager();
8309 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
8310 assert(PLoc.isValid() && "Source location is expected to be valid.");
8311
8312 // Get the hash of the user defined macros.
8313 llvm::MD5 Hash;
8314 llvm::MD5::MD5Result Result;
8315 for (const auto &Arg : PreprocessorOpts.Macros)
8316 Hash.update(Arg.first);
8317 Hash.final(Result);
8318
8319 // Get the UniqueID for the file containing the decl.
8320 llvm::sys::fs::UniqueID ID;
8321 auto Status = FS->status(PLoc.getFilename());
8322 if (!Status) {
8323 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
8324 assert(PLoc.isValid() && "Source location is expected to be valid.");
8325 Status = FS->status(PLoc.getFilename());
8326 }
8327 if (!Status) {
8328 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8329 << PLoc.getFilename() << Status.getError().message();
8330 } else {
8331 ID = Status->getUniqueID();
8332 }
8333 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
8334 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
8335 } else {
8336 OS << getContext().getCUIDHash();
8337 }
8338 }
8339
8340 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
8341 assert(DeferredDeclsToEmit.empty() &&
8342 "Should have emitted all decls deferred to emit.");
8343 assert(NewBuilder->DeferredDecls.empty() &&
8344 "Newly created module should not have deferred decls");
8345 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8346 assert(EmittedDeferredDecls.empty() &&
8347 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8348
8349 assert(NewBuilder->DeferredVTables.empty() &&
8350 "Newly created module should not have deferred vtables");
8351 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8352
8353 assert(NewBuilder->MangledDeclNames.empty() &&
8354 "Newly created module should not have mangled decl names");
8355 assert(NewBuilder->Manglings.empty() &&
8356 "Newly created module should not have manglings");
8357 NewBuilder->Manglings = std::move(Manglings);
8358
8359 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8360
8361 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
8362 }